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 |
---|---|---|---|---|---|---|
./partial_match/97/0x052D64ECD1C8c30DDb7D91fa86b45de0CE86a9e1/sources/Comptroller.sol | * @notice Validates repayBorrow and reverts on rejection. May emit logs. @param vToken Asset being repaid @param payer The address repaying the borrow @param borrower The address of the borrower @param repayAmount The amount of underlying being repaid/ Shh - currently unused Shh - we don't ever want this hook to be marked pure | function repayBorrowVerify(
address vToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external {
vToken;
payer;
borrower;
repayAmount;
borrowerIndex;
if (false) {
maxAssets = maxAssets;
}
}
| 11,472,231 | [
1,
9594,
2071,
528,
38,
15318,
471,
15226,
87,
603,
283,
3710,
18,
16734,
3626,
5963,
18,
225,
331,
1345,
10494,
3832,
2071,
20736,
225,
293,
1773,
1021,
1758,
2071,
528,
310,
326,
29759,
225,
29759,
264,
1021,
1758,
434,
326,
29759,
264,
225,
2071,
528,
6275,
1021,
3844,
434,
6808,
3832,
2071,
20736,
19,
2638,
76,
300,
4551,
10197,
2638,
76,
300,
732,
2727,
1404,
14103,
2545,
333,
3953,
358,
506,
9350,
16618,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2071,
528,
38,
15318,
8097,
12,
203,
3639,
1758,
331,
1345,
16,
203,
3639,
1758,
293,
1773,
16,
203,
3639,
1758,
29759,
264,
16,
203,
3639,
2254,
2071,
528,
6275,
16,
203,
3639,
2254,
29759,
264,
1016,
13,
3903,
288,
203,
3639,
331,
1345,
31,
203,
3639,
293,
1773,
31,
203,
3639,
29759,
264,
31,
203,
3639,
2071,
528,
6275,
31,
203,
3639,
29759,
264,
1016,
31,
203,
203,
3639,
309,
261,
5743,
13,
288,
203,
5411,
943,
10726,
273,
943,
10726,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev samples of imports using brownie and npm style (useful for remix)
* Khronus utilizes brownie as its development framework so all imports in sample contracts, test and auxiliary scripts keep Brownie-eth convensions.
* Brownie style import
* import "Khronus-Project/[email protected]/libraries/KhronusTimeCog.sol"
* NPM install import (this can be used for remix)
* import "@khronus/[email protected]/libraries/KhronusTimeCog.sol";
**/
import "Khronus-Project/[email protected]/contracts/src/KhronusTimeCog.sol";
contract KhronusTimeCog_Test {
/*
This is a contract implementation aimed to allow the testing of the TimeCog library.
*/
//Get a timestamp in days since begining of unix epoch from a Civil Date to make it a Unix Timestamp multiply by number of seconds in day or solidity (1 days)
function getDayTimestamp(uint _year, uint _month, uint _day) external pure returns (uint _timestamp, uint _direction){
(_timestamp, _direction) = KhronusTimeCog.getDayTimestamp(_year, _month, _day);
}
//Get a Unix Timestamp from a full date-time object expressed as an array of 5 integers Year, Month, Day, Hour, Minute.
function getDateObject(uint _timestamp, uint _direction) external pure returns (uint[5] memory _result) {
_result = KhronusTimeCog.getDateObject(_timestamp, _direction);
}
//Get a day Timestamp from a full date object expressed as an array of 3 integers Year, Month, Day, to make it a Unix Timestamp multiply by number of seconds in day or solidity (1 days)
function getDateObjectShort(uint _timestampDays, uint _direction) external pure returns (uint[3] memory _result) {
_result = KhronusTimeCog.getDateObjectShort(_timestampDays, _direction);
}
//Time Delta
function timeDelta(uint[3] memory _baseDate,uint[3] memory _comparedDate) external pure returns (uint _timestampDays, uint _direction){
(_timestampDays, _direction) = KhronusTimeCog.timeDelta(_baseDate, _comparedDate);
}
//Next Unit of time, these functions return the unix timestamp of the next unit of time, the returned timestamp is always rounded to the 0 value.
function nextMinute(uint _timestamp) external pure returns (uint _result) {
_result = KhronusTimeCog.nextMinute(_timestamp);
}
function nextHour(uint _timestamp) external pure returns (uint _result) {
_result = KhronusTimeCog.nextHour(_timestamp);
}
function nextDay(uint _timestamp) external pure returns (uint _result) {
_result = KhronusTimeCog.nextDay(_timestamp);
}
function nextMonth(uint _timestamp) external pure returns (uint _result) {
_result = KhronusTimeCog.nextMonth(_timestamp);
}
//Add Units of Time
function addMinutes(uint _timestamp, uint _minutes) external pure returns (uint _result) {
_result = KhronusTimeCog.addMinutes(_timestamp, _minutes);
}
function addHours(uint _timestamp, uint _hours) external pure returns (uint _result) {
_result = KhronusTimeCog.addHours(_timestamp, _hours);
}
function addDays(uint _timestamp, uint _days) external pure returns (uint _result) {
_result = KhronusTimeCog.addDays(_timestamp, _days);
}
function addMonths(uint _timestamp, uint _months) external pure returns (uint _result) {
_result = KhronusTimeCog.addMonths(_timestamp, _months);
}
//utility functions for Civil Dates
function isLeapYear(uint _year) external pure returns(bool _result) {
_result = KhronusTimeCog.isLeapYear(_year);
}
function getDaysInMonth(uint _year,uint _month)external pure returns(uint _result) {
_result = KhronusTimeCog.getDaysInMonth(_year, _month);
}
function isValidDate(uint _year, uint _month, uint _day) external pure returns(bool _result) {
_result = KhronusTimeCog.isValidDate(_year, _month, _day);
}
function isValidTimestamp(uint _timestamp) external pure returns(bool _result) {
_result = KhronusTimeCog.isValidTimestamp(_timestamp);
}
function isValidDayTimestamp(uint _timestamp) external pure returns(bool _result) {
_result = KhronusTimeCog.isValidDayTimestamp(_timestamp);
}
} | Get a day Timestamp from a full date object expressed as an array of 3 integers Year, Month, Day, to make it a Unix Timestamp multiply by number of seconds in day or solidity (1 days) | function getDateObjectShort(uint _timestampDays, uint _direction) external pure returns (uint[3] memory _result) {
_result = KhronusTimeCog.getDateObjectShort(_timestampDays, _direction);
}
| 14,102,448 | [
1,
967,
279,
2548,
8159,
628,
279,
1983,
1509,
733,
26863,
487,
392,
526,
434,
890,
12321,
16666,
16,
10337,
16,
13735,
16,
358,
1221,
518,
279,
9480,
8159,
10194,
635,
1300,
434,
3974,
316,
2548,
578,
18035,
560,
261,
21,
4681,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10713,
921,
4897,
12,
11890,
389,
5508,
9384,
16,
2254,
389,
9855,
13,
3903,
16618,
1135,
261,
11890,
63,
23,
65,
3778,
389,
2088,
13,
288,
203,
3639,
389,
2088,
273,
1475,
76,
1949,
407,
950,
39,
717,
18,
588,
1626,
921,
4897,
24899,
5508,
9384,
16,
389,
9855,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xcc3C54B95f3f1867A43009B80ed4DD930E3cE2F7/sources/lib/solidity-utils/src/contracts/create3/Create3Factory.sol | @inheritdoc ICreate3Factory hash salt with the deployer address to give each deployer its own namespace | function predictAddress(
address deployer,
bytes32 salt
) external view returns (address) {
salt = keccak256(abi.encodePacked(deployer, salt));
return Create3.addressOf(salt);
}
| 2,800,839 | [
1,
36,
10093,
202,
45,
1684,
23,
1733,
1651,
4286,
598,
326,
7286,
264,
1758,
358,
8492,
1517,
7286,
264,
2097,
4953,
1981,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
7810,
1887,
12,
203,
565,
1758,
7286,
264,
16,
203,
565,
1731,
1578,
4286,
203,
225,
262,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
565,
4286,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
12411,
264,
16,
4286,
10019,
203,
565,
327,
1788,
23,
18,
2867,
951,
12,
5759,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0xEe627d343015DDffAdd5b33FFE84F70Ed5d064B8/sources/Vibra.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 (string memory, string memory) {
_name = "TESTING";
_symbol = "TTC";
_totalSupply = 270000000 * 10**18;
_balances[msg.sender] = _totalSupply;
}
| 16,284,729 | [
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,
377,
3885,
261,
1080,
3778,
16,
533,
3778,
13,
288,
203,
3639,
389,
529,
273,
315,
16961,
1360,
14432,
203,
3639,
389,
7175,
273,
315,
1470,
39,
14432,
7010,
3639,
389,
4963,
3088,
1283,
273,
12732,
17877,
380,
1728,
636,
2643,
31,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
377,
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: Unlicensed
pragma solidity ^0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface 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 eSHILLTOKEN is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address payable;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => uint256) public _lastBuyTime;
mapping (address => bool) private _isExcludedFromFee;
address payable public marketing;
address public marketing_lp;
address payable private _burnPool = 0x0000000000000000000000000000000000000000;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100 * 10**15 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Ethereum Shillings";
string private _symbol = "eSHILL";
uint8 private _decimals = 9;
uint256 public _taxBuyFee = 2;
uint256 public _taxSellFee = 2;
uint256 public _taxTransferFee = 0;
uint256 private _operationsFee = 0; //adjusted on the go
uint256 private _liquidityFee = 0; //adjusted on the go
uint256 private _taxFee = 0; //adjusted on the go
uint256 private _burnFee = 0; //adjusted on the go
uint256 public _marketingBuyFee = 5;
uint256 public _marketingSellFee = 5;
uint256 public _marketingTransferFee = 0;
uint256 public _liquidityBuyFee = 4;
uint256 public _liquiditySellFee = 4;
uint256 public _liquidityTransferFee = 0;
uint256 public _burnBuyFee = 1;
uint256 public _burnSellFee = 1;
uint256 public _burnTransferFee = 0;
uint256 public _pendingLiquidityFees = 0;
uint256 public _dayTraderMultiplicator = 25; // div by 10
uint256 private constant _devAllocation = 3 * 10**15 * 10**9;
uint256 private constant _listingsAllocation = 5 * 10**15 * 10**9;
uint256 private constant _marketingAllocation = 3 * 10**15 * 10**9;
uint256 private constant _privateSaleAllocation = 29 * 10**15 * 10**9;
uint256 private constant _LPAllocation = 25 * 10**15 * 10**9;
uint256 private constant _burnAllocation = 35 * 10**15 * 10**9;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxWalletHolding = 65 * 10**13 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 15 * 10**13 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address payable _marketing, address _marketing_lp, address _dev, address _listings) public {
marketing = _marketing;
marketing_lp = _marketing_lp;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_dev] = true;
_isExcludedFromFee[_listings] = true;
uint256 currentRate = _getRate();
_rOwned[_dev] = _devAllocation.mul(currentRate);
_rOwned[_marketing] = _marketingAllocation.mul(currentRate);
_rOwned[_listings] = _listingsAllocation.mul(currentRate);
_rOwned[_burnPool] = _burnAllocation.mul(currentRate);
_rOwned[_msgSender()] = (_LPAllocation + _privateSaleAllocation).mul(currentRate);
emit Transfer(address(0), _msgSender(), _tTotal);
emit Transfer(_msgSender(), _dev, _devAllocation);
emit Transfer(_msgSender(), _marketing, _marketingAllocation);
emit Transfer(_msgSender(), _burnPool, _burnAllocation);
emit Transfer(_msgSender(), _listings, _listingsAllocation);
}
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) {
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 totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
//this can be called externally by deployer to immediately process accumulated fees accordingly (distribute to treasury & liquidity)
function manualSwapAndLiquify() public onlyOwner() {
uint256 contractTokenBalance = balanceOf(address(this));
swapAndLiquify(contractTokenBalance);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTax(uint256 _taxType, uint _taxSize) external onlyOwner() {
if (_taxType == 1) {
_taxSellFee = _taxSize;
}
else if (_taxType == 2) {
_taxBuyFee = _taxSize;
}
else if (_taxType == 3) {
_taxTransferFee = _taxSize;
}
else if (_taxType == 4) {
_marketingBuyFee = _taxSize;
}
else if (_taxType == 5) {
_marketingSellFee = _taxSize;
}
else if (_taxType == 6) {
_marketingTransferFee = _taxSize;
}
else if (_taxType == 7) {
_burnBuyFee = _taxSize;
}
else if (_taxType == 8) {
_burnSellFee = _taxSize;
}
else if (_taxType == 9) {
_burnTransferFee = _taxSize;
}
else if (_taxType == 10) {
_liquidityBuyFee = _taxSize;
}
else if (_taxType == 11) {
_liquiditySellFee = _taxSize;
}
else if (_taxType == 12) {
_liquidityTransferFee = _taxSize;
}
else if (_taxType == 13) {
_dayTraderMultiplicator = _taxSize;
}
}
function setMaxWalletHolding(uint256 maxHolding) external onlyOwner() {
_maxWalletHolding = maxHolding;
}
//this is to be called to distribute private sale allocations
function distributePresaleAllocations(address payable [] memory recipients, uint256[] memory allocations) public onlyOwner() {
require(recipients.length > 0, "At least one recipient must be in the array");
require(recipients.length == allocations.length, "Number of recipients must equal number of allocations");
uint256 currentRate = _getRate();
for (uint8 i = 0; i < recipients.length; i++) {
if (!recipients[i].isContract()) {
uint256 _rAlloc = allocations[i].mul(10**18).mul(currentRate);
_rOwned[recipients[i]] = _rAlloc;
_rOwned[_msgSender()] = _rOwned[_msgSender()] - _rAlloc;
emit Transfer(_msgSender(), recipients[i], allocations[i].mul(10**18));
}
}
}
function setSwapAndLiquifyEnabled(bool _enabled, uint256 _numTokensMin) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
numTokensSellToAddToLiquidity = _numTokensMin;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to receive ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
uint256[4] memory tValues = _getTValuesArray(tAmount);
uint256[3] memory rValues = _getRValuesArray(tAmount, tValues[1], tValues[2], tValues[3]);
return (rValues[0], rValues[1], rValues[2], tValues[0], tValues[1], tValues[2], tValues[3]);
}
function _getTValuesArray(uint256 tAmount) private view returns (uint256[4] memory val) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tOperations = calculateOperationsFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tOperations);
return [tTransferAmount, tFee, tLiquidity, tOperations];
}
function _getRValuesArray(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tOperations) private view returns (uint256[3] memory val) {
uint256 currentRate = _getRate();
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(tLiquidity.mul(currentRate)).sub(tOperations.mul(currentRate));
return [rAmount, rTransferAmount, rFee];
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
_pendingLiquidityFees = _pendingLiquidityFees.add(tLiquidity);
}
function _takeOperations(uint256 tOperations) private {
uint256 currentRate = _getRate();
uint256 tBurn = 0;
if (_operationsFee > 0) {
tBurn = _burnFee.mul(tOperations).div(_operationsFee);
emit Transfer(address(this), address(0), tBurn);
}
uint256 rOperations = tOperations.sub(tBurn).mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rOperations);
_rOwned[_burnPool] = _rOwned[_burnPool].add(tBurn.mul(currentRate));
}
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 calculateOperationsFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_operationsFee).div(
10**2
);
}
function removeAllFee() private {
_taxFee = 0;
_liquidityFee = 0;
_operationsFee = 0;
_burnFee = 0;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//depending on type of transfer (buy, sell, or p2p tokens transfer) different taxes & fees are applied
bool isTransferBuy = from == uniswapV2Pair;
bool isTransferSell = to == uniswapV2Pair;
if (!isTransferBuy && !isTransferSell) {
_operationsFee = _marketingTransferFee.add(_burnTransferFee);
_liquidityFee = _liquidityTransferFee;
_taxFee = _taxTransferFee;
_burnFee = _burnTransferFee;
}
else if (isTransferBuy) {
_operationsFee = _marketingBuyFee.add(_burnBuyFee);
_liquidityFee = _liquidityBuyFee;
_taxFee = _taxBuyFee;
_burnFee = _burnBuyFee;
_lastBuyTime[to] = block.timestamp;
}
else if (isTransferSell) {
uint tax_multiplicator = 10;
_operationsFee = _marketingSellFee.add(_burnSellFee);
_liquidityFee = _liquiditySellFee;
_taxFee = _taxSellFee;
_burnFee = _burnSellFee;
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
if (_lastBuyTime[from] != 0 && (_lastBuyTime[from] + (24 hours) > block.timestamp) ) {
//increasing sell tax when user is selling within 24 hrs (Day Trader Tax)
tax_multiplicator = _dayTraderMultiplicator;
}
}
_operationsFee = _operationsFee.mul(tax_multiplicator).div(10);
_liquidityFee = _liquidityFee.mul(tax_multiplicator).div(10);
_taxFee = _taxFee.mul(tax_multiplicator).div(10);
_burnFee = _burnFee.mul(tax_multiplicator).div(10);
}
//transfer amount, it will take tax, liquidity & treasury fees
_tokenTransfer(from,to,amount,takeFee);
removeAllFee();
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 liquidityPart = 0;
if (_pendingLiquidityFees < contractTokenBalance) liquidityPart = _pendingLiquidityFees;
uint256 distributionPart = contractTokenBalance.sub(liquidityPart);
uint256 liquidityHalfPart = liquidityPart.div(2);
uint256 liquidityHalfTokenPart = liquidityPart.sub(liquidityHalfPart);
//now swapping half of the liquidity part + all of the distribution part into ETH
uint256 totalETHSwap = liquidityHalfPart.add(distributionPart);
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(totalETHSwap);
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 liquidityBalance = liquidityHalfPart.mul(newBalance).div(totalETHSwap);
// add liquidity to uniswap
if (liquidityHalfTokenPart > 0 && liquidityBalance > 0) addLiquidity(liquidityHalfTokenPart, liquidityBalance);
emit SwapAndLiquify(liquidityHalfPart, liquidityBalance, liquidityHalfPart);
newBalance = address(this).balance;
marketing.sendValue(newBalance);
_pendingLiquidityFees = 0;
}
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,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
marketing_lp,
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!_isExcludedFromFee[recipient] && (recipient != uniswapV2Pair)) require(balanceOf(recipient) < _maxWalletHolding, "Max Wallet holding limit exceeded");
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tOperations) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeOperations(tOperations);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} | this method is responsible for taking all fee, if takeFee is true | function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!_isExcludedFromFee[recipient] && (recipient != uniswapV2Pair)) require(balanceOf(recipient) < _maxWalletHolding, "Max Wallet holding limit exceeded");
}
| 5,856,275 | [
1,
2211,
707,
353,
14549,
364,
13763,
777,
14036,
16,
309,
4862,
14667,
353,
638,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
2316,
5912,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
16,
6430,
4862,
14667,
13,
3238,
288,
203,
3639,
309,
12,
5,
22188,
14667,
13,
12787,
14667,
5621,
203,
3639,
389,
13866,
8336,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
309,
16051,
67,
291,
16461,
1265,
14667,
63,
20367,
65,
597,
261,
20367,
480,
640,
291,
91,
438,
58,
22,
4154,
3719,
2583,
12,
12296,
951,
12,
20367,
13,
411,
389,
1896,
16936,
20586,
310,
16,
315,
2747,
20126,
19918,
1800,
12428,
8863,
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
] |
./partial_match/1/0xe12cB2D1cFB370A245A2A34DE3dbC845C341bD92/sources/RoosCoin.sol | Addresses excluded from receiving rewards
| mapping(address => bool) private _excludedFromRewards; | 2,862,959 | [
1,
7148,
8845,
628,
15847,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
24602,
1265,
17631,
14727,
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
] |
pragma solidity 0.5.7;
pragma experimental ABIEncoderV2;
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @dev Contract module which provides an authorisation control mechanism, where
* there is an 'owner' that can grant access to a specific 'reader'.
* The 'reader' can request access to an 'owner'.
*/
contract Authorisation is Ownable {
using SafeMath for uint256;
using SafeMath32 for uint32;
using SafeMath16 for uint16;
event AuthorisationGranted(
uint256 authorisationId,
address _owner,
address _reader
);
event AuthorisationRequested(
address indexed _reader,
address indexed _owner
);
event AuthorisationRemoved(address indexed _owner, address indexed _reader);
struct AuthorisationStruct {
address owner;
mapping(address => bool) allowed;
}
struct RequestAuthorisationStruct {
address reader;
mapping(address => bool) requested;
}
mapping(address => AuthorisationStruct) authorisationStructs;
mapping(address => RequestAuthorisationStruct) requestAuthorisationStructs;
/**
* @dev Gives authorisation to the '_reader'.
*/
function giveAuthorisation(address _reader) public {
_authorise(_msgSender(), _reader);
}
/**
* @dev Removes authorisation to the '_reader'.
*/
function removeAuthorisation(address _reader) public {
authorisationStructs[_msgSender()].allowed[_reader] = false;
}
/**
* @dev Check authorisation of the '_reader' for the '_owner'.
*/
function isAuthorised(address _owner, address _reader)
public
view
returns (bool)
{
return _isAuthorised(_owner, _reader);
}
/**
* @dev Request auhtorisation of the sender to the '_owner'.
*/
function requestAuthorisation(address _owner) public {
requestAuthorisationStructs[_msgSender()].reader = _msgSender();
requestAuthorisationStructs[_msgSender()].requested[_owner] = true;
}
/**
* @dev Approves authorisation by the sender to the '_reader'.
*/
function approveAuthorisation(address _reader) public {
requestAuthorisationStructs[_reader].requested[_msgSender()] = false;
_authorise(_msgSender(), _reader);
}
/**
* @dev Gives authorisation to the '_reader'. Only the '_owner' can execute it.
*/
function _authorise(address _owner, address _reader) private {
if (!_isAuthorised(_owner, _reader)) {
authorisationStructs[_owner].owner = _owner;
authorisationStructs[_owner].allowed[_reader] = true;
}
}
/**
* @dev Gives authorisation to the '_reader'. Only the '_owner' can execute it.
*/
function _isAuthorised(address _owner, address _reader)
private
view
returns (bool)
{
return authorisationStructs[_owner].allowed[_reader];
}
} | * @dev Check authorisation of the '_reader' for the '_owner'./ | function isAuthorised(address _owner, address _reader)
public
view
returns (bool)
{
return _isAuthorised(_owner, _reader);
}
| 6,394,164 | [
1,
1564,
2869,
10742,
434,
326,
2070,
10530,
11,
364,
326,
2070,
8443,
10332,
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,
353,
3594,
5918,
12,
2867,
389,
8443,
16,
1758,
389,
10530,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
389,
291,
3594,
5918,
24899,
8443,
16,
389,
10530,
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
] |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../library/LibSafeMath.sol";
import "../ERC1155Mintable.sol";
import "../mixin/MixinOwnable.sol";
import "../mixin/MixinPausable.sol";
import "../HashRegistry.sol";
contract SagaHistoricMinter is Ownable, MixinPausable {
using LibSafeMath for uint256;
uint256 public tokenType;
ERC1155Mintable public mintableErc1155;
HashRegistry public registry;
// historic pricing params
uint256 immutable public startingPriceForHistoric;
uint256 immutable public pricePerMintForHistoric;
// max total minting supply
uint256 immutable maxMintingSupply;
address payable public treasury;
constructor(
address _registry,
address _mintableErc1155,
address payable _treasury,
uint256 _tokenType,
uint256 _startingPriceForHistoric,
uint256 _pricePerMintForHistoric,
uint256 _maxMintingSupply
) {
registry = HashRegistry(_registry);
mintableErc1155 = ERC1155Mintable(_mintableErc1155);
treasury = _treasury;
tokenType = _tokenType;
startingPriceForHistoric = _startingPriceForHistoric;
pricePerMintForHistoric = _pricePerMintForHistoric;
maxMintingSupply = _maxMintingSupply;
}
modifier onlyUnderMaxSupply(uint256 mintingAmount) {
require(maxIndex() + mintingAmount <= maxMintingSupply, 'max supply minted');
_;
}
function pause() external onlyOwner() {
_pause();
}
function unpause() external onlyOwner() {
_unpause();
}
function setTreasury(address payable _treasury) external onlyOwner() {
treasury = _treasury;
}
function maxIndex() public view returns (uint256) {
return mintableErc1155.maxIndex(tokenType);
}
function pricingCurveForHistoric(uint256 _maxIndex) public view returns (uint256) {
return _maxIndex.safeMul(pricePerMintForHistoric).safeAdd(startingPriceForHistoric);
}
function mint(address[] calldata _dsts, uint256[] calldata _txHashes) public payable whenNotPaused() onlyUnderMaxSupply(_dsts.length) {
require(_dsts.length == _txHashes.length, "dsts, txhashes length mismatch");
// verify and transfer fee
uint256 price = 0;
for (uint256 i = 0; i < _dsts.length; ++i) {
price += pricingCurveForHistoric(maxIndex() + i);
}
require(price <= msg.value, "insufficient funds to pay for mint");
treasury.transfer(price);
msg.sender.transfer(msg.value.safeSub(price));
_mint(_dsts, _txHashes);
}
function _mint(address[] memory dsts, uint256[] memory txHashes) internal {
uint256[] memory tokenIds = new uint256[](dsts.length);
for (uint256 i = 0; i < dsts.length; ++i) {
uint256 index = maxIndex() + 1 + i;
uint256 tokenId = tokenType | index;
tokenIds[i] = tokenId;
}
mintableErc1155.mintNonFungible(tokenType, dsts);
registry.writeToRegistry(tokenIds, txHashes);
}
}
pragma solidity ^0.7.0;
import "./LibRichErrors.sol";
import "./LibSafeMathRichErrors.sol";
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
pragma solidity ^0.7.0;
import "./library/LibSafeMath.sol";
import "./library/LibAddress.sol";
import "./ERC1155.sol";
import "./interface/IERC1155Mintable.sol";
import "./mixin/MixinOwnable.sol";
import "./mixin/MixinContractURI.sol";
import "./mixin/MixinTokenURI.sol";
/// @dev Mintable form of ERC1155
/// Shows how easy it is to mint new items
contract ERC1155Mintable is
IERC1155Mintable,
ERC1155,
MixinContractURI,
MixinTokenURI
{
using LibSafeMath for uint256;
using LibAddress for address;
uint256 internal nonce;
/// mapping from token to max index
mapping (uint256 => uint256) public maxIndex;
mapping (uint256 => mapping(address => bool)) internal creatorApproval;
modifier onlyCreator(uint256 _id) {
require(creatorApproval[_id][msg.sender], "not an approved creator of id");
_;
}
function setCreatorApproval(uint256 id, address creator, bool status) external onlyCreator(id) {
creatorApproval[id][creator] = status;
}
/// @dev creates a new token
/// @param isNF is non-fungible token
/// @return type_ of token (a unique identifier)
function create(
bool isNF
)
external
override
onlyOwner()
returns (uint256 type_)
{
// Store the type in the upper 128 bits
type_ = (++nonce << 128);
// Set a flag if this is an NFI.
if (isNF) {
type_ = type_ | TYPE_NF_BIT;
}
creatorApproval[type_][msg.sender] = true;
// emit a Transfer event with Create semantic to help with discovery.
emit TransferSingle(
msg.sender,
address(0x0),
address(0x0),
type_,
0
);
emit URI(uri(type_), type_);
}
/// @dev creates a new token
/// @param type_ of token
function createWithType(
uint256 type_
)
external
onlyOwner()
{
creatorApproval[type_][msg.sender] = true;
// emit a Transfer event with Create semantic to help with discovery.
emit TransferSingle(
msg.sender,
address(0x0),
address(0x0),
type_,
0
);
emit URI(uri(type_), type_);
}
/// @dev mints fungible tokens
/// @param id token type
/// @param to beneficiaries of minted tokens
/// @param quantities amounts of minted tokens
function mintFungible(
uint256 id,
address[] calldata to,
uint256[] calldata quantities
)
external
override
onlyCreator(id)
{
// sanity checks
require(
isFungible(id),
"TRIED_TO_MINT_FUNGIBLE_FOR_NON_FUNGIBLE_TOKEN"
);
// mint tokens
for (uint256 i = 0; i < to.length; ++i) {
// cache to reduce number of loads
address dst = to[i];
uint256 quantity = quantities[i];
// Grant the items to the caller
balances[id][dst] = quantity.safeAdd(balances[id][dst]);
// Emit the Transfer/Mint event.
// the 0x0 source address implies a mint
// It will also provide the circulating supply info.
emit TransferSingle(
msg.sender,
address(0x0),
dst,
id,
quantity
);
// if `to` is a contract then trigger its callback
if (dst.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received(
msg.sender,
msg.sender,
id,
quantity,
""
);
require(
callbackReturnValue == ERC1155_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
}
/// @dev mints a non-fungible token
/// @param type_ token type
/// @param to beneficiaries of minted tokens
function mintNonFungible(
uint256 type_,
address[] calldata to
)
external
override
onlyCreator(type_)
{
require(
isNonFungible(type_),
"TRIED_TO_MINT_NON_FUNGIBLE_FOR_FUNGIBLE_TOKEN"
);
// Index are 1-based.
uint256 index = maxIndex[type_] + 1;
for (uint256 i = 0; i < to.length; ++i) {
// cache to reduce number of loads
address dst = to[i];
uint256 id = type_ | index + i;
nfOwners[id] = dst;
// You could use base-type id to store NF type balances if you wish.
balances[type_][dst] = balances[type_][dst].safeAdd(1);
emit TransferSingle(msg.sender, address(0x0), dst, id, 1);
// if `to` is a contract then trigger its callback
if (dst.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received(
msg.sender,
msg.sender,
id,
1,
""
);
require(
callbackReturnValue == ERC1155_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
// record the `maxIndex` of this nft type
// this allows us to mint more nft's of this type in a subsequent call.
maxIndex[type_] = to.length.safeAdd(maxIndex[type_]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
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 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract MixinPausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.7.0;
import "./library/LibSafeMath.sol";
import "./ERC1155Mintable.sol";
import "./mixin/MixinOwnable.sol";
contract HashRegistry is Ownable {
using LibSafeMath for uint256;
ERC1155Mintable public mintableErc1155;
mapping(uint256 => uint256) public tokenIdToTxHash;
mapping(uint256 => uint256) public txHashToTokenId;
mapping(address => bool) public permissedWriters;
constructor(
address _mintableErc1155
) {
permissedWriters[msg.sender] = true;
mintableErc1155 = ERC1155Mintable(_mintableErc1155);
}
event UpdatedRegistry(
uint256 tokenId,
uint256 txHash
);
modifier onlyIfPermissed(address writer) {
require(permissedWriters[writer] == true, "writer can't write to registry");
_;
}
function updatePermissedWriterStatus(address _writer, bool status) public onlyIfPermissed(msg.sender) {
permissedWriters[_writer] = status;
}
function writeToRegistry(uint256[] memory tokenIds, uint256[] memory txHashes) public onlyIfPermissed(msg.sender) {
require(tokenIds.length == txHashes.length, "tokenIds and txHashes size mismatch");
for (uint256 i = 0; i < tokenIds.length; ++i) {
uint256 tokenId = tokenIds[i];
uint256 txHash = txHashes[i];
require(mintableErc1155.ownerOf(tokenId) != address(0), 'token does not exist');
require(txHashToTokenId[txHash] == 0, 'txHash already exists');
require(tokenIdToTxHash[tokenId] == 0, 'tokenId already exists');
tokenIdToTxHash[tokenId] = txHash;
txHashToTokenId[txHash] = tokenId;
emit UpdatedRegistry(tokenId, txHash);
}
}
}
pragma solidity ^0.7.0;
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
pragma solidity ^0.7.0;
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
pragma solidity ^0.7.0;
/**
* Utility library of inline functions on addresses
*/
library LibAddress {
/**
* 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;
}
}
pragma solidity ^0.7.0;
import "./library/LibSafeMath.sol";
import "./library/LibAddress.sol";
import "./interface/IERC1155.sol";
import "./interface/IERC1155Receiver.sol";
import "./mixin/MixinNonFungibleToken.sol";
import "./mixin/MixinOwnable.sol";
import "./WhitelistExchangesProxy.sol";
contract ERC1155 is
IERC1155,
MixinNonFungibleToken,
Ownable
{
using LibAddress for address;
using LibSafeMath for uint256;
// selectors for receiver callbacks
bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61;
bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81;
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
// owner => (operator => approved)
mapping (address => mapping(address => bool)) internal operatorApproval;
address public exchangesRegistry;
function setExchangesRegistry(address newExchangesRegistry) external onlyOwner() {
exchangesRegistry = newExchangesRegistry;
}
/// @notice Transfers value amount of an _id from the _from address to the _to address specified.
/// @dev MUST emit TransferSingle event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if balance of sender for token `_id` is lower than the `_value` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.
/// @param from Source address
/// @param to Target address
/// @param id ID of the token type
/// @param value Transfer amount
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
override
external
{
// sanity checks
require(
to != address(0x0),
"CANNOT_TRANSFER_TO_ADDRESS_ZERO"
);
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"INSUFFICIENT_ALLOWANCE"
);
// perform transfer
if (isNonFungible(id)) {
require(
value == 1,
"AMOUNT_EQUAL_TO_ONE_REQUIRED"
);
require(
nfOwners[id] == from,
"NFT_NOT_OWNED_BY_FROM_ADDRESS"
);
nfOwners[id] = to;
// You could keep balance of NF type in base type id like so:
// uint256 baseType = getNonFungibleBaseType(_id);
// balances[baseType][_from] = balances[baseType][_from].safeSub(_value);
// balances[baseType][_to] = balances[baseType][_to].safeAdd(_value);
} else {
balances[id][from] = balances[id][from].safeSub(value);
balances[id][to] = balances[id][to].safeAdd(value);
}
emit TransferSingle(msg.sender, from, to, id, value);
// if `to` is a contract then trigger its callback
if (to.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received(
msg.sender,
from,
id,
value,
data
);
require(
callbackReturnValue == ERC1155_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
/// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call).
/// @dev MUST emit TransferBatch event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if length of `_ids` is not the same as length of `_values`.
/// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
/// @param from Source addresses
/// @param to Target addresses
/// @param ids IDs of each token type
/// @param values Transfer amounts per token type
/// @param data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
override
external
{
// sanity checks
require(
to != address(0x0),
"CANNOT_TRANSFER_TO_ADDRESS_ZERO"
);
require(
ids.length == values.length,
"TOKEN_AND_VALUES_LENGTH_MISMATCH"
);
// Only supporting a global operator approval allows us to do
// only 1 check and not to touch storage to handle allowances.
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"INSUFFICIENT_ALLOWANCE"
);
// perform transfers
for (uint256 i = 0; i < ids.length; ++i) {
// Cache value to local variable to reduce read costs.
uint256 id = ids[i];
uint256 value = values[i];
if (isNonFungible(id)) {
require(
value == 1,
"AMOUNT_EQUAL_TO_ONE_REQUIRED"
);
require(
nfOwners[id] == from,
"NFT_NOT_OWNED_BY_FROM_ADDRESS"
);
nfOwners[id] = to;
} else {
balances[id][from] = balances[id][from].safeSub(value);
balances[id][to] = balances[id][to].safeAdd(value);
}
}
emit TransferBatch(msg.sender, from, to, ids, values);
// if `to` is a contract then trigger its callback
if (to.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived(
msg.sender,
from,
ids,
values,
data
);
require(
callbackReturnValue == ERC1155_BATCH_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external override {
operatorApproval[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/// @notice Queries the approval status of an operator for a given owner.
/// @param owner The owner of the Tokens
/// @param operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) public override view returns (bool) {
bool approved = operatorApproval[owner][operator];
if (!approved && exchangesRegistry != address(0)) {
return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true;
}
return approved;
}
/// @notice Get the balance of an account's Tokens.
/// @param owner The address of the token holder
/// @param id ID of the Token
/// @return The _owner's balance of the Token type requested
function balanceOf(address owner, uint256 id) external override view returns (uint256) {
if (isNonFungibleItem(id)) {
return nfOwners[id] == owner ? 1 : 0;
}
return balances[id][owner];
}
/// @notice Get the balance of multiple account/token pairs
/// @param owners The addresses of the token holders
/// @param ids ID of the Tokens
/// @return balances_ The _owner's balance of the Token types requested
function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external override view returns (uint256[] memory balances_) {
// sanity check
require(
owners.length == ids.length,
"OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH"
);
// get balances
balances_ = new uint256[](owners.length);
for (uint256 i = 0; i < owners.length; ++i) {
uint256 id = ids[i];
if (isNonFungibleItem(id)) {
balances_[i] = nfOwners[id] == owners[i] ? 1 : 0;
} else {
balances_[i] = balances[id][owners[i]];
}
}
return balances_;
}
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.0;
import "./IERC1155.sol";
/// @dev Mintable form of ERC1155
/// Shows how easy it is to mint new items
interface IERC1155Mintable is
IERC1155
{
/// @dev creates a new token
/// @param isNF is non-fungible token
/// @return type_ of token (a unique identifier)
function create(
bool isNF
)
external
returns (uint256 type_);
/// @dev mints fungible tokens
/// @param id token type
/// @param to beneficiaries of minted tokens
/// @param quantities amounts of minted tokens
function mintFungible(
uint256 id,
address[] calldata to,
uint256[] calldata quantities
)
external;
/// @dev mints a non-fungible token
/// @param type_ token type
/// @param to beneficiaries of minted tokens
function mintNonFungible(
uint256 type_,
address[] calldata to
)
external;
}
pragma solidity ^0.7.0;
import "./MixinOwnable.sol";
contract MixinContractURI is Ownable {
string public contractURI;
function setContractURI(string calldata newContractURI) external onlyOwner() {
contractURI = newContractURI;
}
}
pragma solidity ^0.7.0;
import "./MixinOwnable.sol";
import "../library/LibString.sol";
contract MixinTokenURI is Ownable {
using LibString for string;
string public baseMetadataURI = "";
function setBaseMetadataURI(string memory newBaseMetadataURI) public onlyOwner() {
baseMetadataURI = newBaseMetadataURI;
}
function uri(uint256 _id) public view returns (string memory) {
return LibString.strConcat(
baseMetadataURI,
LibString.uint2hexstr(_id)
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.0;
/// @title ERC-1155 Multi Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
/// Note: The ERC-165 identifier for this interface is 0xd9b67a26.
interface IERC1155 {
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
/// Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _value
);
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
///Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _values
);
/// @dev MUST emit when an approval is updated.
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/// @dev MUST emit when the URI is updated for a token ID.
/// URIs are defined in RFC 3986.
/// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema".
event URI(
string _value,
uint256 indexed _id
);
/// @notice Transfers value amount of an _id from the _from address to the _to address specified.
/// @dev MUST emit TransferSingle event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if balance of sender for token `_id` is lower than the `_value` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.
/// @param from Source address
/// @param to Target address
/// @param id ID of the token type
/// @param value Transfer amount
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
/// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call).
/// @dev MUST emit TransferBatch event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if length of `_ids` is not the same as length of `_values`.
/// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
/// @param from Source addresses
/// @param to Target addresses
/// @param ids IDs of each token type
/// @param values Transfer amounts per token type
/// @param data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external;
/// @notice Queries the approval status of an operator for a given owner.
/// @param owner The owner of the Tokens
/// @param operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) external view returns (bool);
/// @notice Get the balance of an account's Tokens.
/// @param owner The address of the token holder
/// @param id ID of the Token
/// @return The _owner's balance of the Token type requested
function balanceOf(address owner, uint256 id) external view returns (uint256);
/// @notice Get the balance of multiple account/token pairs
/// @param owners The addresses of the token holders
/// @param ids ID of the Tokens
/// @return balances_ The _owner's balance of the Token types requested
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.0;
interface IERC1155Receiver {
/// @notice Handle the receipt of a single ERC1155 token type
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransferFrom`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
///transaction being reverted
/// Note: the 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 id An array containing the ids of the token being transferred
/// @param value An array containing the amount of tokens being transferred
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/// @notice Handle the receipt of multiple ERC1155 token types
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransferFrom`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted
/// Note: the 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 ids An array containing ids of each token being transferred
/// @param values An array containing amounts of each token being transferred
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
pragma solidity ^0.7.0;
contract MixinNonFungibleToken {
uint256 constant internal TYPE_MASK = uint256(uint128(~0)) << 128;
uint256 constant internal NF_INDEX_MASK = uint128(~0);
uint256 constant internal TYPE_NF_BIT = 1 << 255;
mapping (uint256 => address) internal nfOwners;
/// @dev Returns true if token is non-fungible
function isNonFungible(uint256 id) public pure returns(bool) {
return id & TYPE_NF_BIT == TYPE_NF_BIT;
}
/// @dev Returns true if token is fungible
function isFungible(uint256 id) public pure returns(bool) {
return id & TYPE_NF_BIT == 0;
}
/// @dev Returns index of non-fungible token
function getNonFungibleIndex(uint256 id) public pure returns(uint256) {
return id & NF_INDEX_MASK;
}
/// @dev Returns base type of non-fungible token
function getNonFungibleBaseType(uint256 id) public pure returns(uint256) {
return id & TYPE_MASK;
}
/// @dev Returns true if input is base-type of a non-fungible token
function isNonFungibleBaseType(uint256 id) public pure returns(bool) {
// A base type has the NF bit but does not have an index.
return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK == 0);
}
/// @dev Returns true if input is a non-fungible token
function isNonFungibleItem(uint256 id) public pure returns(bool) {
// A base type has the NF bit but does has an index.
return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0);
}
/// @dev returns owner of a non-fungible token
function ownerOf(uint256 id) public view returns (address) {
return nfOwners[id];
}
}
pragma solidity ^0.7.0;
import "./mixin/MixinOwnable.sol";
contract WhitelistExchangesProxy is Ownable {
mapping(address => bool) internal proxies;
bool public paused = true;
function setPaused(bool newPaused) external onlyOwner() {
paused = newPaused;
}
function updateProxyAddress(address proxy, bool status) external onlyOwner() {
proxies[proxy] = status;
}
function isAddressWhitelisted(address proxy) external view returns (bool) {
if (paused) {
return false;
} else {
return proxies[proxy];
}
}
}
pragma solidity ^0.7.0;
contract Context {
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.7.0;
library LibString {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function uint2hexstr(uint i) internal pure returns (string memory) {
if (i == 0) {
return "0";
}
uint j = i;
uint len;
while (j != 0) {
len++;
j = j >> 4;
}
uint mask = 15;
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
uint curr = (i & mask);
bstr[k--] = curr > 9 ? byte(uint8(55 + curr)) : byte(uint8(48 + curr));
i = i >> 4;
}
return string(bstr);
}
}
| @dev Returns true if input is a non-fungible token A base type has the NF bit but does has an index. | function isNonFungibleItem(uint256 id) public pure returns(bool) {
return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0);
}
| 63,671 | [
1,
1356,
638,
309,
810,
353,
279,
1661,
17,
12125,
75,
1523,
1147,
432,
1026,
618,
711,
326,
423,
42,
2831,
1496,
1552,
711,
392,
770,
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,
353,
3989,
42,
20651,
1523,
1180,
12,
11890,
5034,
612,
13,
1071,
16618,
1135,
12,
6430,
13,
288,
203,
3639,
327,
261,
350,
473,
3463,
67,
26473,
67,
15650,
422,
3463,
67,
26473,
67,
15650,
13,
597,
261,
350,
473,
423,
42,
67,
9199,
67,
11704,
480,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import './TimelockExecutorBase.sol';
contract ArcTimelock is TimelockExecutorBase {
address private _ethereumGovernanceExecutor;
event EthereumGovernanceExecutorUpdate(
address previousEthereumGovernanceExecutor,
address newEthereumGovernanceExecutor
);
modifier onlyEthereumGovernanceExecutor() {
require(msg.sender == _ethereumGovernanceExecutor, 'UNAUTHORIZED_EXECUTOR');
_;
}
constructor(
address ethereumGovernanceExecutor,
uint256 delay,
uint256 gracePeriod,
uint256 minimumDelay,
uint256 maximumDelay,
address guardian
) TimelockExecutorBase(delay, gracePeriod, minimumDelay, maximumDelay, guardian) {
_ethereumGovernanceExecutor = ethereumGovernanceExecutor;
}
/**
* @dev Queue the message in the Executor
* @param targets list of contracts called by each action's associated transaction
* @param values list of value in wei for each action's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target
**/
function queue(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
bool[] memory withDelegatecalls
) external onlyEthereumGovernanceExecutor {
_queue(targets, values, signatures, calldatas, withDelegatecalls);
}
/**
* @dev Update the address of the Ethereum Governance Executor contract responsible for sending transactions to ARC
* @param ethereumGovernanceExecutor the address of the Ethereum Governance Executor contract
**/
function updateEthereumGovernanceExecutor(address ethereumGovernanceExecutor) external onlyThis {
emit EthereumGovernanceExecutorUpdate(_ethereumGovernanceExecutor, ethereumGovernanceExecutor);
_ethereumGovernanceExecutor = ethereumGovernanceExecutor;
}
/**
* @dev get the current address of ethereumGovernanceExecutor
* @return the address of the Ethereum Governance Executor contract
**/
function getEthereumGovernanceExecutor() external view returns (address) {
return _ethereumGovernanceExecutor;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import '../dependencies/SafeMath.sol';
import '../interfaces/ITimelockExecutor.sol';
abstract contract TimelockExecutorBase is ITimelockExecutor {
using SafeMath for uint256;
uint256 private _delay;
uint256 private _gracePeriod;
uint256 private _minimumDelay;
uint256 private _maximumDelay;
address private _guardian;
uint256 private _actionsSetCounter;
mapping(uint256 => ActionsSet) private _actionsSets;
mapping(bytes32 => bool) private _queuedActions;
modifier onlyGuardian() {
require(msg.sender == _guardian, 'ONLY_BY_GUARDIAN');
_;
}
modifier onlyThis() {
require(msg.sender == address(this), 'UNAUTHORIZED_ORIGIN_ONLY_THIS');
_;
}
constructor(
uint256 delay,
uint256 gracePeriod,
uint256 minimumDelay,
uint256 maximumDelay,
address guardian
) {
require(delay >= minimumDelay, 'DELAY_SHORTER_THAN_MINIMUM');
require(delay <= maximumDelay, 'DELAY_LONGER_THAN_MAXIMUM');
_delay = delay;
_gracePeriod = gracePeriod;
_minimumDelay = minimumDelay;
_maximumDelay = maximumDelay;
_guardian = guardian;
}
/// @inheritdoc ITimelockExecutor
function execute(uint256 actionsSetId) external payable override {
require(getCurrentState(actionsSetId) == ActionsSetState.Queued, 'ONLY_QUEUED_ACTIONS');
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
require(block.timestamp >= actionsSet.executionTime, 'TIMELOCK_NOT_FINISHED');
actionsSet.executed = true;
uint256 actionCount = actionsSet.targets.length;
bytes[] memory returnedData = new bytes[](actionCount);
for (uint256 i = 0; i < actionCount; i++) {
returnedData[i] = _executeTransaction(
actionsSet.targets[i],
actionsSet.values[i],
actionsSet.signatures[i],
actionsSet.calldatas[i],
actionsSet.executionTime,
actionsSet.withDelegatecalls[i]
);
}
emit ActionsSetExecuted(actionsSetId, msg.sender, returnedData);
}
/// @inheritdoc ITimelockExecutor
function cancel(uint256 actionsSetId) external override onlyGuardian {
ActionsSetState state = getCurrentState(actionsSetId);
require(state == ActionsSetState.Queued, 'ONLY_BEFORE_EXECUTED');
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
actionsSet.canceled = true;
for (uint256 i = 0; i < actionsSet.targets.length; i++) {
_cancelTransaction(
actionsSet.targets[i],
actionsSet.values[i],
actionsSet.signatures[i],
actionsSet.calldatas[i],
actionsSet.executionTime,
actionsSet.withDelegatecalls[i]
);
}
emit ActionsSetCanceled(actionsSetId);
}
/// @inheritdoc ITimelockExecutor
function getActionsSetById(uint256 actionsSetId)
external
view
override
returns (ActionsSet memory)
{
return _actionsSets[actionsSetId];
}
/// @inheritdoc ITimelockExecutor
function getCurrentState(uint256 actionsSetId) public view override returns (ActionsSetState) {
require(_actionsSetCounter >= actionsSetId, 'INVALID_ACTION_ID');
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
if (actionsSet.canceled) {
return ActionsSetState.Canceled;
} else if (actionsSet.executed) {
return ActionsSetState.Executed;
} else if (block.timestamp > actionsSet.executionTime.add(_gracePeriod)) {
return ActionsSetState.Expired;
} else {
return ActionsSetState.Queued;
}
}
/// @inheritdoc ITimelockExecutor
function isActionQueued(bytes32 actionHash) public view override returns (bool) {
return _queuedActions[actionHash];
}
function receiveFunds() external payable {}
/// @inheritdoc ITimelockExecutor
function updateGuardian(address guardian) external override onlyThis {
emit GuardianUpdate(_guardian, guardian);
_guardian = guardian;
}
/// @inheritdoc ITimelockExecutor
function updateDelay(uint256 delay) external override onlyThis {
_validateDelay(delay);
emit DelayUpdate(_delay, delay);
_delay = delay;
}
/// @inheritdoc ITimelockExecutor
function updateGracePeriod(uint256 gracePeriod) external override onlyThis {
emit GracePeriodUpdate(_gracePeriod, gracePeriod);
_gracePeriod = gracePeriod;
}
/// @inheritdoc ITimelockExecutor
function updateMinimumDelay(uint256 minimumDelay) external override onlyThis {
uint256 previousMinimumDelay = _minimumDelay;
_minimumDelay = minimumDelay;
_validateDelay(_delay);
emit MinimumDelayUpdate(previousMinimumDelay, minimumDelay);
}
/// @inheritdoc ITimelockExecutor
function updateMaximumDelay(uint256 maximumDelay) external override onlyThis {
uint256 previousMaximumDelay = _maximumDelay;
_maximumDelay = maximumDelay;
_validateDelay(_delay);
emit MaximumDelayUpdate(previousMaximumDelay, maximumDelay);
}
/// @inheritdoc ITimelockExecutor
function getDelay() external view override returns (uint256) {
return _delay;
}
/// @inheritdoc ITimelockExecutor
function getGracePeriod() external view override returns (uint256) {
return _gracePeriod;
}
/// @inheritdoc ITimelockExecutor
function getMinimumDelay() external view override returns (uint256) {
return _minimumDelay;
}
/// @inheritdoc ITimelockExecutor
function getMaximumDelay() external view override returns (uint256) {
return _maximumDelay;
}
/// @inheritdoc ITimelockExecutor
function getGuardian() external view override returns (address) {
return _guardian;
}
/// @inheritdoc ITimelockExecutor
function getActionsSetCount() external view override returns (uint256) {
return _actionsSetCounter;
}
/**
* @dev target.delegatecall cannot be provided a value directly and is sent
* with the entire available msg.value. In this instance, we only want each proposed action
* to execute with exactly the value defined in the proposal. By splitting executeDelegateCall
* into a seperate function, it can be called from this contract with a defined amout of value,
* reducing the risk that a delegatecall is executed with more value than intended
* @return success - boolean indicating it the delegate call was successfull
* @return resultdata - bytes returned by the delegate call
**/
function executeDelegateCall(address target, bytes calldata data)
external
payable
onlyThis
returns (bool, bytes memory)
{
bool success;
bytes memory resultData;
// solium-disable-next-line security/no-call-value
(success, resultData) = target.delegatecall(data);
return (success, resultData);
}
/**
* @dev Queue the ActionsSet
* @param targets list of contracts called by each action's associated transaction
* @param values list of value in wei for each action's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target
**/
function _queue(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
bool[] memory withDelegatecalls
) internal {
require(targets.length != 0, 'INVALID_EMPTY_TARGETS');
require(
targets.length == values.length &&
targets.length == signatures.length &&
targets.length == calldatas.length &&
targets.length == withDelegatecalls.length,
'INCONSISTENT_PARAMS_LENGTH'
);
uint256 actionsSetId = _actionsSetCounter;
uint256 executionTime = block.timestamp.add(_delay);
_actionsSetCounter++;
for (uint256 i = 0; i < targets.length; i++) {
bytes32 actionHash =
keccak256(
abi.encode(
targets[i],
values[i],
signatures[i],
calldatas[i],
executionTime,
withDelegatecalls[i]
)
);
require(!isActionQueued(actionHash), 'DUPLICATED_ACTION');
_queuedActions[actionHash] = true;
}
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
actionsSet.targets = targets;
actionsSet.values = values;
actionsSet.signatures = signatures;
actionsSet.calldatas = calldatas;
actionsSet.withDelegatecalls = withDelegatecalls;
actionsSet.executionTime = executionTime;
emit ActionsSetQueued(
actionsSetId,
targets,
values,
signatures,
calldatas,
withDelegatecalls,
executionTime
);
}
function _executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) internal returns (bytes memory) {
require(address(this).balance >= value, 'NOT_ENOUGH_CONTRACT_BALANCE');
bytes32 actionHash =
keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall));
_queuedActions[actionHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
bool success;
bytes memory resultData;
if (withDelegatecall) {
(success, resultData) = this.executeDelegateCall{value: value}(target, callData);
} else {
// solium-disable-next-line security/no-call-value
(success, resultData) = target.call{value: value}(callData);
}
return _verifyCallResult(success, resultData);
}
function _cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) internal {
bytes32 actionHash =
keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall));
_queuedActions[actionHash] = false;
}
function _validateDelay(uint256 delay) internal view {
require(delay >= _minimumDelay, 'DELAY_SHORTER_THAN_MINIMUM');
require(delay <= _maximumDelay, 'DELAY_LONGER_THAN_MAXIMUM');
}
function _verifyCallResult(bool success, bytes memory returndata)
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('FAILED_ACTION_EXECUTION');
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.7.5;
pragma abicoder v2;
interface ITimelockExecutor {
enum ActionsSetState {
Queued,
Executed,
Canceled,
Expired
}
struct ActionsSet {
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
uint256 executionTime;
bool executed;
bool canceled;
}
/**
* @dev emitted when an ActionsSet is queued
* @param id Id of the ActionsSet
* @param targets list of contracts called by each action's associated transaction
* @param values list of value in wei for each action's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target
* @param executionTime the time these actions can be executed
**/
event ActionsSetQueued(
uint256 id,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
bool[] withDelegatecalls,
uint256 executionTime
);
/**
* @dev emitted when an ActionsSet is executed successfully
* @param id Id of the ActionsSet
* @param initiatorExecution address that triggered the ActionsSet execution
* @param returnedData returned data from the ActionsSet execution
**/
event ActionsSetExecuted(uint256 id, address indexed initiatorExecution, bytes[] returnedData);
/**
* @dev emitted when an ActionsSet is cancelled by the guardian
* @param id Id of the ActionsSet
**/
event ActionsSetCanceled(uint256 id);
/**
* @dev emitted when a new guardian is set
* @param previousGuardian previous guardian
* @param newGuardian new guardian
**/
event GuardianUpdate(address previousGuardian, address newGuardian);
/**
* @dev emitted when a new delay (between queueing and execution) is set
* @param previousDelay previous delay
* @param newDelay new delay
**/
event DelayUpdate(uint256 previousDelay, uint256 newDelay);
/**
* @dev emitted when a GracePeriod is updated
* @param previousGracePeriod previous grace period
* @param newGracePeriod new grace period
**/
event GracePeriodUpdate(uint256 previousGracePeriod, uint256 newGracePeriod);
/**
* @dev emitted when a Minimum Delay is updated
* @param previousMinimumDelay previous minimum delay
* @param newMinimumDelay new minimum delay
**/
event MinimumDelayUpdate(uint256 previousMinimumDelay, uint256 newMinimumDelay);
/**
* @dev emitted when a Maximum Delay is updated
* @param previousMaximumDelay previous maximum delay
* @param newMaximumDelay new maximum delay
**/
event MaximumDelayUpdate(uint256 previousMaximumDelay, uint256 newMaximumDelay);
/**
* @dev Execute the ActionsSet
* @param actionsSetId id of the ActionsSet to execute
**/
function execute(uint256 actionsSetId) external payable;
/**
* @dev Cancel the ActionsSet
* @param actionsSetId id of the ActionsSet to cancel
**/
function cancel(uint256 actionsSetId) external;
/**
* @dev Get the ActionsSet by Id
* @param actionsSetId id of the ActionsSet
* @return the ActionsSet requested
**/
function getActionsSetById(uint256 actionsSetId) external view returns (ActionsSet memory);
/**
* @dev Get the current state of an ActionsSet
* @param actionsSetId id of the ActionsSet
* @return The current state of the ActionsSet
**/
function getCurrentState(uint256 actionsSetId) external view returns (ActionsSetState);
/**
* @dev Returns whether an action (via actionHash) is queued
* @param actionHash hash of the action to be checked
* keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall))
* @return true if underlying action of actionHash is queued
**/
function isActionQueued(bytes32 actionHash) external view returns (bool);
/**
* @dev Update guardian
* @param guardian address of the new guardian
**/
function updateGuardian(address guardian) external;
/**
* @dev Update the delay
* @param delay delay between queue and execution of an ActionSet
**/
function updateDelay(uint256 delay) external;
/**
* @dev Set the grace period - time before a queued action will expire
* @param gracePeriod The gracePeriod in seconds
**/
function updateGracePeriod(uint256 gracePeriod) external;
/**
* @dev Set the minimum allowed delay between queing and exection
* @param minimumDelay The minimum delay in seconds
**/
function updateMinimumDelay(uint256 minimumDelay) external;
/**
* @dev Set the maximum allowed delay between queing and exection
* @param maximumDelay The maximum delay in seconds
**/
function updateMaximumDelay(uint256 maximumDelay) external;
/**
* @dev Getter of the delay between queuing and execution
* @return The delay in seconds
**/
function getDelay() external view returns (uint256);
/**
* @dev Getter of grace period constant
* @return grace period in seconds
**/
function getGracePeriod() external view returns (uint256);
/**
* @dev Getter of minimum delay constant
* @return minimum delay in seconds
**/
function getMinimumDelay() external view returns (uint256);
/**
* @dev Getter of maximum delay constant
* @return maximum delay in seconds
**/
function getMaximumDelay() external view returns (uint256);
/**
* @dev Get guardian address
* @return guardian address
**/
function getGuardian() external view returns (address);
/**
* @dev Get ActionSet count
* @return current count of action sets processed
**/
function getActionsSetCount() external view returns (uint256);
} | @inheritdoc ITimelockExecutor | function getMaximumDelay() external view override returns (uint256) {
return _maximumDelay;
}
| 148,736 | [
1,
36,
10093,
467,
10178,
292,
975,
6325,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
25194,
6763,
1435,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
389,
15724,
6763,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, 2**256 - 1);
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(uint256 l, uint256 h, uint256 d) private pure returns (uint256) {
uint256 pow2 = d & (~d + 1);
d /= pow2;
l /= pow2;
l += h * ((~pow2 + 1) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
} | taken from https:medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 license is CC-BY-4.0 | library FullMath {
pragma solidity ^0.8.0;
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, 2**256 - 1);
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(uint256 l, uint256 h, uint256 d) private pure returns (uint256) {
uint256 pow2 = d & (~d + 1);
d /= pow2;
l /= pow2;
l += h * ((~pow2 + 1) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
} | 14,107,130 | [
1,
29113,
628,
2333,
30,
19011,
18,
832,
19,
12645,
2586,
7904,
19,
15949,
17,
267,
17,
30205,
560,
17,
2680,
17,
23,
17,
8849,
87,
17,
464,
17,
685,
655,
1115,
17,
24,
1966,
1611,
24,
73,
20,
3672,
70,
21,
8630,
353,
16525,
17,
6486,
17,
24,
18,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
12083,
11692,
10477,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
445,
1983,
27860,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
261,
11890,
5034,
328,
16,
2254,
5034,
366,
13,
288,
203,
3639,
2254,
5034,
9740,
273,
14064,
1711,
12,
92,
16,
677,
16,
576,
636,
5034,
300,
404,
1769,
203,
3639,
328,
273,
619,
380,
677,
31,
203,
3639,
366,
273,
9740,
300,
328,
31,
203,
3639,
309,
261,
7020,
411,
328,
13,
366,
3947,
404,
31,
203,
565,
289,
203,
203,
565,
445,
1983,
7244,
12,
11890,
5034,
328,
16,
2254,
5034,
366,
16,
2254,
5034,
302,
13,
3238,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
7602,
22,
273,
302,
473,
261,
98,
72,
397,
404,
1769,
203,
3639,
302,
9531,
7602,
22,
31,
203,
3639,
328,
9531,
7602,
22,
31,
203,
3639,
328,
1011,
366,
380,
14015,
98,
23509,
22,
397,
404,
13,
342,
7602,
22,
397,
404,
1769,
203,
3639,
2254,
5034,
436,
273,
404,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
436,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
436,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
436,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
436,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
436,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
436,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
436,
31,
203,
3639,
436,
6413,
576,
300,
302,
380,
2
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-05
*/
/*
website: bns.finance
This project is freshly written to change the way ICO is done.
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNNN SSSSSSSSSSSSSSS DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFIIIIIIIIII
B::::::::::::::::B N:::::::N N::::::N SS:::::::::::::::S D::::::::::::DDD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
B::::::BBBBBB:::::B N::::::::N N::::::NS:::::SSSSSS::::::S D:::::::::::::::DD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
BB:::::B B:::::BN:::::::::N N::::::NS:::::S SSSSSSS DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EFF::::::FFFFFFFFF::::FII::::::II
B::::B B:::::BN::::::::::N N::::::NS:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F FFFFFF I::::I
B::::B B:::::BN:::::::::::N N::::::NS:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::BBBBBB:::::B N:::::::N::::N N::::::N S::::SSSS D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B:::::::::::::BB N::::::N N::::N N::::::N SS::::::SSSSS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::BBBBBB:::::B N::::::N N::::N:::::::N SSS::::::::SS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::B B:::::BN::::::N N:::::::::::N SSSSSS::::S D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B::::B B:::::BN::::::N N::::::::::N S:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::B B:::::BN::::::N N:::::::::N S:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F I::::I
BB:::::BBBBBB::::::BN::::::N N::::::::NSSSSSSS S:::::S DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EFF:::::::FF II::::::II
B:::::::::::::::::B N::::::N N:::::::NS::::::SSSSSS:::::S ...... D:::::::::::::::DD E::::::::::::::::::::EF::::::::FF I::::::::I
B::::::::::::::::B N::::::N N::::::NS:::::::::::::::SS .::::. D::::::::::::DDD E::::::::::::::::::::EF::::::::FF I::::::::I
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNN SSSSSSSSSSSSSSS ...... DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFF IIIIIIIIII
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SAO");
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, "SMO");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "IB");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "RR");
}
/**
* @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, "IBC");
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), "CNC");
// 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, "DAB0");
_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, "LF1");
if (returndata.length != 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "LF2");
}
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 public _totalSupply;
string public _name;
string public _symbol;
uint8 public _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
// /**
// * @dev Returns the name of the token.
// */
// function name() public view returns (string memory) {
// return _name;
// }
// /**
// * @dev Returns the symbol of the token, usually a shorter version of the
// * name.
// */
// function symbol() public view returns (string memory) {
// return _symbol;
// }
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
// function decimals() public view returns (uint8) {
// return _decimals;
// }
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ISA");
require(recipient != address(0), "IRA");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "TIF");
_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), "M0");
_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), "B0");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "BIB");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "IA");
require(spender != address(0), "A0");
_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 { }
}
contract BnsdLaunchPool is Context {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of a raising pool.
struct RaisePoolInfo {
IERC20 raiseToken; // Address of raising token contract.
uint256 maxTokensPerPerson; // Maximum tokens a user can buy.
uint256 totalTokensOnSale; // Total tokens available on offer.
uint256 startBlock; // When the sale starts
uint256 endBlock; // When the sale ends
uint256 totalTokensSold; // Total tokens sold to users so far
uint256 tokensDeposited; // Total ICO tokens deposited
uint256 votes; // Voted by users
address owner; // Owner of the pool
bool updateLocked; // No pool info can be updated once this is turned ON
bool balanceAdded; // Whether ICO tokens are added in correct amount
bool paymentMethodAdded; // Supported currencies added or not
string poolName; // Human readable string name of the pool
}
struct AirdropPoolInfo {
uint256 totalTokensAvailable; // Total tokens staked so far.
IERC20 airdropToken; // Address of staking LP token.
bool airdropExists;
}
// Info of a raising pool.
struct UseCasePoolInfo {
uint256 tokensAllocated; // Total tokens available for this use
uint256 tokensClaimed; // Total tokens claimed
address reserveAdd; // Address where tokens will be released for that usecase.
bool tokensDeposited; // No pool info can be updated once this is turned ON
bool exists; // Whether reserve already exists for a pool
string useName; // Human readable string name of the pool
uint256[] unlock_perArray; // Release percent for usecase
uint256[] unlock_daysArray; // Release days for usecase
}
struct DistributionInfo {
uint256[] percentArray; // Percentage of tokens to be unlocked every phase
uint256[] daysArray; // Days from the endDate when tokens starts getting unlocked
}
// The BNSD TOKEN!
address public timeLock;
// Dev address.
address public devaddr;
// Temp dev address while switching
address private potentialAdmin;
// To store owner diistribution info after sale ends
mapping (uint256 => DistributionInfo) private ownerDistInfo;
// To store user distribution info after sale ends
mapping (uint256 => DistributionInfo) private userDistInfo;
// To store tokens on sale and their rates
mapping (uint256 => mapping (address => uint256)) public saleRateInfo;
// To store invite codes and corresponding token address and pool owners, INVITE CODE => TOKEN => OWNER => bool
mapping (uint256 => mapping (address => mapping (address => bool))) private inviteCodeList;
// To store user contribution for a sale - POOL => USER => USDT
mapping (uint256 => mapping (address => mapping (address => uint256))) public userDepositInfo;
// To store total token promised to a user - POOL => USER
mapping (uint256 => mapping (address => uint256)) public userTokenAllocation;
// To store total token claimed by a user already
mapping (uint256 => mapping (address => uint256)) public userTokenClaimed;
// To store total token redeemed by users after sale
mapping (uint256 => uint256) public totalTokenClaimed;
// To store total token raised by a project - POOL => TOKEN => AMT
mapping (uint256 => mapping (address => uint256)) public fundsRaisedSoFar;
mapping (uint256 => address) private tempAdmin;
// To store total token claimed by a project
mapping (uint256 => mapping (address => uint256)) public fundsClaimedSoFar;
// To store addresses voted for a project - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public userVotes;
// No of blocks in a day - 6700
uint256 public constant BLOCKS_PER_DAY = 6700; // Changing to 5 for test cases
// Info of each pool on blockchain.
RaisePoolInfo[] public poolInfo;
// Info of reserve pool of any project - POOL => RESERVE_ADD => USECASEINFO
mapping (uint256 => mapping (address => UseCasePoolInfo)) public useCaseInfo;
// To store total token reserved
mapping (uint256 => uint256) public totalTokenReserved;
// To store total reserved claimed
mapping (uint256 => uint256) public totalReservedTokenClaimed;
// To store list of all sales associated with a token
mapping (address => uint256[]) public listSaleTokens;
// To store list of all currencies allowed for a sale
mapping (uint256 => address[]) public listSupportedCurrencies;
// To store list of all reserve addresses for a sale
mapping (uint256 => address[]) public listReserveAddresses;
// To check if staking is enabled on a token
mapping (address => bool) public stakingEnabled;
// To get staking weight of a token
mapping (address => uint256) public stakingWeight;
// To store sum of weight of all staking tokens
uint256 public totalStakeWeight;
// To store list of staking addresses
address[] public stakingPools;
// To store stats of staked tokens per sale
mapping (uint256 => mapping (address => uint256)) public stakedLPTokensInfo;
// To store user staked amount for a sale - POOL => USER => LP_TOKEN
mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo;
// To store reward claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public rewardClaimed;
// To store airdrop claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public airdropClaimed;
// To store extra airdrop tokens withdrawn by fund raiser - POOL => BOOL
mapping (uint256 => bool) public extraAirdropClaimed;
// To store airdrop info for a sale
mapping (uint256 => AirdropPoolInfo) public airdropInfo;
// To store airdrop tokens balance of a user , TOKEN => USER => BAL
mapping (address => mapping (address => uint256)) public airdropBalances;
uint256 public fee = 300; // To be divided by 1e4 before using it anywhere => 3.00%
uint256 public constant rewardPer = 8000; // To be divided by 1e4 before using it anywhere => 80.00%
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Stake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event UnStake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event MoveStake(address indexed user, address indexed lptoken, uint256 pid, uint256 indexed pidnew, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event WithdrawAirdrop(address indexed user, address indexed token, uint256 amount);
event ClaimAirdrop(address indexed user, address indexed token, uint256 amount);
event AirdropDeposit(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event AirdropExtraWithdraw(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event Voted(address indexed user, uint256 indexed pid);
constructor() public {
devaddr = _msgSender();
}
modifier onlyAdmin() {
require(devaddr == _msgSender(), "ND");
_;
}
modifier onlyAdminOrTimeLock() {
require((devaddr == _msgSender() || timeLock == _msgSender()), "ND");
_;
}
function setTimeLockAdd(address _add) public onlyAdmin {
timeLock = _add;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function getListOfSale(address _token) external view returns (uint256[] memory) {
return listSaleTokens[_token];
}
function getUserDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].percentArray;
}
function getUserDistDays(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].daysArray;
}
function getReserveUnlockPercent(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_perArray;
}
function getReserveUnlockDays(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_daysArray;
}
function getUserDistBlocks(uint256 _pid) external view returns (uint256[] memory) {
uint256[] memory daysArray = userDistInfo[_pid].daysArray;
uint256 endPool = poolInfo[_pid].endBlock;
for(uint256 i=0; i<daysArray.length; i++){
daysArray[i] = (daysArray[i].mul(BLOCKS_PER_DAY)).add(endPool);
}
return daysArray;
}
function getOwnerDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].percentArray;
}
function getOwnerDistDays(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].daysArray;
}
// Add a new token sale to the pool. Can only be called by the person having the invite code.
function addNewPool(uint256 totalTokens, uint256 maxPerPerson, uint256 startBlock, uint256 endBlock, string memory namePool, IERC20 tokenAddress, uint256 _inviteCode) external returns (uint256) {
require(endBlock > startBlock, "ESC"); // END START COMPARISON FAILED
require(startBlock > block.number, "TLS"); // TIME LIMIT START SALE
require(maxPerPerson !=0 && totalTokens!=0, "IIP"); // INVALID INDIVIDUAL PER PERSON
require(inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()]==true,"IIC"); // INVALID INVITE CODE
poolInfo.push(RaisePoolInfo({
raiseToken: tokenAddress,
maxTokensPerPerson: maxPerPerson,
totalTokensOnSale: totalTokens,
startBlock: startBlock,
endBlock: endBlock,
poolName: namePool,
updateLocked: false,
owner: _msgSender(),
totalTokensSold: 0,
balanceAdded: false,
tokensDeposited: 0,
paymentMethodAdded: false,
votes: 0
}));
uint256 poolId = (poolInfo.length - 1);
listSaleTokens[address(tokenAddress)].push(poolId);
// This makes the invite code claimed
inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()] = false;
return poolId;
}
function _checkSumArray(uint256[] memory _percentArray) internal pure returns (bool) {
uint256 _sum;
for (uint256 i = 0; i < _percentArray.length; i++) {
_sum = _sum.add(_percentArray[i]);
}
return (_sum==10000);
}
function _checkValidDaysArray(uint256[] memory _daysArray) internal pure returns (bool) {
uint256 _lastDay = _daysArray[0];
for (uint256 i = 1; i < _daysArray.length; i++) {
if(_lastDay < _daysArray[i]){
_lastDay = _daysArray[i];
}
else {
return false;
}
}
return true;
}
function _checkUpdateAllowed(uint256 _pid) internal view{
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.updateLocked == false, "CT2"); // CRITICAL TERMINATION 2
require(pool.owner==_msgSender(), "OAU"); // OWNER AUTHORIZATION FAILED
require(pool.startBlock > block.number, "CT"); // CRITICAL TERMINATION
}
// Add rule for funds locking after sale
function updateUserDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
userDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Add rule for funds unlocking of the fund raiser after sale
function updateOwnerDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
ownerDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Lock sale detail changes in future
function lockPool(uint256 _pid) external {
require(poolInfo[_pid].paymentMethodAdded==true, "CP"); // CHECK PAYMENT METHOD FAILED
_checkUpdateAllowed(_pid);
poolInfo[_pid].updateLocked = true;
}
// Add supported currencies and their rate w.r.t token on sale
// rateToken = price of one satoshi of the token in terms of token to be raised * 1e18
// 1 BNSD = 0.00021 ETH => 1e18 BNSD Satoshi = 0.00021 * 1e18 ETH satoshi => 1 BNSD Satoshi = 0.00021 ETH satoshi => rateToken = 0.00021 * 1e18 = 21 * 1e13
// rateToken for BNSD/ETH pair = 21 * 1e13;
function addSupportedCurrencies(uint256 _pid, address _tokenRaise, uint256 rateToken) external {
_checkUpdateAllowed(_pid);
require(rateToken!=0, "IR"); // INVALID RATE
require(_tokenRaise!=address(poolInfo[_pid].raiseToken), "IT"); // INVALIID PURCHASE TOKEN
if(address(this).balance == 0){ //inject PRESENT ETHER
listSupportedCurrencies[_pid].push(_tokenRaise);
}
saleRateInfo[_pid][_tokenRaise] = rateToken;
poolInfo[_pid].paymentMethodAdded = true;
}
function getSupportedCurrencies(uint256 _pid) external view returns (address[] memory) {
return listSupportedCurrencies[_pid];
}
function _checkUpdateReserveAllowed(uint256 _pid, address _resAdd) internal view returns (bool) {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
return (poolU.exists == false || poolU.tokensDeposited == false);
// if(poolU.exists == false || poolU.tokensDeposited == false){
// return true;
// }
// return false;
}
function addReservePool(uint256 _pid, address _reserveAdd, string memory _nameReserve, uint256 _totalTokens, uint256[] memory _perArray, uint256[] memory _daysArray) external {
_checkUpdateAllowed(_pid);
require(_checkUpdateReserveAllowed(_pid, _reserveAdd) == true, "UB"); // UPDATE RESERVE FAILED
require(_checkSumArray(_perArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
require(_perArray.length==_daysArray.length, "IAL"); // INVALID ARRAY LENGTH
if(useCaseInfo[_pid][_reserveAdd].exists == false){
listReserveAddresses[_pid].push(_reserveAdd);
}
useCaseInfo[_pid][_reserveAdd] = UseCasePoolInfo({
reserveAdd: _reserveAdd,
useName: _nameReserve,
tokensAllocated: _totalTokens,
unlock_perArray: _perArray,
unlock_daysArray: _daysArray,
tokensDeposited: false,
tokensClaimed: 0,
exists: true
});
}
function getReserveAddresses(uint256 _pid) external view returns (address[] memory) {
return listReserveAddresses[_pid];
}
function tokensPurchaseAmt(uint256 _pid, address _tokenAdd, uint256 amt) public view returns (uint256) {
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
require(rateToken!=0, "NAT"); // NOT AVAILABLE TOKEN
return (amt.mul(1e18)).div(rateToken);
}
// Check if user can deposit specfic amount of funds to the pool
function _checkDepositAllowed(uint256 _pid, address _tokenAdd, uint256 _amt) internal view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 userBought = userTokenAllocation[_pid][_msgSender()];
uint256 purchasePossible = tokensPurchaseAmt(_pid, _tokenAdd, _amt);
require(pool.balanceAdded == true, "NA"); // NOT AVAILABLE
require(pool.startBlock <= block.number, "NT1"); // NOT AVAILABLE TIME 1
require(pool.endBlock >= block.number, "NT2"); // NOT AVAILABLE TIME 2
require(pool.totalTokensSold.add(purchasePossible) <= pool.totalTokensOnSale, "PLE"); // POOL LIMIT EXCEEDED
require(userBought.add(purchasePossible) <= pool.maxTokensPerPerson, "ILE"); // INDIVIDUAL LIMIT EXCEEDED
return purchasePossible;
}
// Check max a user can deposit right now
function getMaxDepositAllowed(uint256 _pid, address _tokenAdd, address _user) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 maxBuyPossible = (pool.maxTokensPerPerson).sub(userTokenAllocation[_pid][_user]);
uint256 maxBuyPossiblePoolLimit = (pool.totalTokensOnSale).sub(pool.totalTokensSold);
if(maxBuyPossiblePoolLimit < maxBuyPossible){
maxBuyPossible = maxBuyPossiblePoolLimit;
}
if(block.number >= pool.startBlock && block.number <= pool.endBlock && pool.balanceAdded == true){
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
return (maxBuyPossible.mul(rateToken).div(1e18));
}
else {
return 0;
}
}
// Check if deposit is enabled for a pool
function checkDepositEnabled(uint256 _pid) external view returns (bool){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.balanceAdded == true && pool.startBlock <= block.number && pool.endBlock >= block.number && pool.totalTokensSold <= pool.totalTokensOnSale && pool.paymentMethodAdded==true){
return true;
}
else {
return false;
}
}
// Deposit ICO tokens to start a pool for ICO.
function depositICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT VALID TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number < pool.endBlock, "NT"); // No point adding tokens after sale has ended - Possible deadlock case
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
pool.tokensDeposited = (pool.tokensDeposited).add(_amount);
if(pool.tokensDeposited >= pool.totalTokensOnSale){
pool.balanceAdded = true;
}
emit Deposit(msgSender, _pid, _amount);
}
// Deposit Airdrop tokens anytime before end of the sale.
function depositAirdropTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.endBlock, "NT"); // NOT VALID TIME
AirdropPoolInfo storage airdrop = airdropInfo[_pid];
require((_tokenAdd == airdrop.airdropToken || airdrop.airdropExists==false), "NOT"); // NOT VALID TOKEN
require(_msgSender() == pool.owner || _msgSender() == devaddr , "NAU"); // NOT AUTHORISED USER
_tokenAdd.safeTransferFrom(_msgSender(), address(this), _amount);
airdrop.totalTokensAvailable = (airdrop.totalTokensAvailable).add(_amount);
if(!airdrop.airdropExists){
airdrop.airdropToken = _tokenAdd;
airdrop.airdropExists = true;
}
emit AirdropDeposit(_msgSender(), address(_tokenAdd), _pid, _amount);
}
// Withdraw extra airdrop tokens - Possible only if no one added liquidity to one of the pools
function withdrawExtraAirdropTokens(uint256 _pid) external {
require(extraAirdropClaimed[_pid]==false, "NA"); // NOT AVAILABLE
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "NSE"); // SALE NOT ENDED
address msgSender = _msgSender();
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
uint256 extraTokens = calculateExtraAirdropTokens(_pid);
require(extraTokens!=0, "NAT"); // NOT AVAILABLE TOKEN
extraAirdropClaimed[_pid] = true;
airdropInfo[_pid].airdropToken.safeTransfer(msgSender, extraTokens);
emit AirdropExtraWithdraw(msg.sender, address(airdropInfo[_pid].airdropToken), _pid, extraTokens);
}
function calculateExtraAirdropTokens(uint256 _pid) public view returns (uint256){
if(extraAirdropClaimed[_pid] == true) return 0;
uint256 _totalTokens;
for (uint256 i=0; i<stakingPools.length; i++){
uint256 stake = stakedLPTokensInfo[_pid][stakingPools[i]];
if(address(this).balance == 0){ //inject PRESENT ETHER
_totalTokens = _totalTokens.add(((stakingWeight[stakingPools[i]]).mul(airdropInfo[_pid].totalTokensAvailable)).div(totalStakeWeight));
}
}
return _totalTokens;
}
// Deposit LP tokens for a sale.
function stakeLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NST"); // NOT STAKING TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.startBlock, "NT"); // NOT VALID TIME
address msgSender = _msgSender();
_lpAdd.safeTransferFrom(msgSender, address(this), _amount);
stakedLPTokensInfo[_pid][address(_lpAdd)] = (stakedLPTokensInfo[_pid][address(_lpAdd)]).add(_amount);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).add(_amount);
emit Stake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw LP tokens from a sale after it's over => Automatically claims rewards and airdrops also
function withdrawLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NAT"); // NOT AUTHORISED TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SALE NOT ENDED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).sub(_amount);
_lpAdd.safeTransfer(msgSender, _amount);
emit UnStake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw airdrop tokens accumulated over one or more than one sale.
function withdrawAirdropTokens(IERC20 _token, uint256 _amount) external {
address msgSender = _msgSender();
airdropBalances[address(_token)][msgSender] = (airdropBalances[address(_token)][msgSender]).sub(_amount);
_token.safeTransfer(msgSender, _amount);
emit WithdrawAirdrop(msgSender, address(_token), _amount);
}
// Move LP tokens from one sale to another directly => Automatically claims rewards and airdrops also
function moveLPTokens(uint256 _pid, uint256 _newpid, uint256 _amount, address _lpAdd) external {
require(stakingEnabled[_lpAdd]==true, "NAT1"); // NOT AUTHORISED TOKEN 1
RaisePoolInfo storage poolOld = poolInfo[_pid];
RaisePoolInfo storage poolNew = poolInfo[_newpid];
require(block.number > poolOld.endBlock, "NUA"); // OLD SALE NOT ENDED
require(block.number < poolNew.startBlock, "NSA"); // SALE START CHECK FAILED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][_lpAdd] = (userStakeInfo[_pid][msgSender][_lpAdd]).sub(_amount);
userStakeInfo[_newpid][msgSender][_lpAdd] = (userStakeInfo[_newpid][msgSender][_lpAdd]).add(_amount);
emit MoveStake(msg.sender, _lpAdd, _pid, _newpid, _amount);
}
function claimRewardAndAirdrop(uint256 _pid) public {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SUM INVALID
_claimReward(_pid, _msgSender());
_claimAirdrop(_pid, _msgSender());
}
function _claimReward(uint256 _pid, address _user) internal {
if (rewardClaimed[_pid][_user]==false){
rewardClaimed[_pid][_user] = true;
for (uint256 i=0; i<stakingPools.length; i++){
for(uint256 j=0; j<listSupportedCurrencies[_pid].length; j++){
uint256 _tokenAmt = getReward(_pid, _user, stakingPools[i], listSupportedCurrencies[_pid][j]);
_creditAirdrop(_user, listSupportedCurrencies[_pid][j], _tokenAmt);
}
}
}
}
function _claimAirdrop(uint256 _pid, address _user) internal {
if (airdropClaimed[_pid][_user]==false){
airdropClaimed[_pid][_user] = true;
address _airdropToken = address(airdropInfo[_pid].airdropToken);
uint256 _tokenAmt = 0;
for (uint256 i=0; i<stakingPools.length; i++){
_tokenAmt = _tokenAmt.add(getAirdrop(_pid, _user, stakingPools[i]));
}
if(_tokenAmt !=0){
_creditAirdrop(_user, _airdropToken, _tokenAmt);
}
}
}
function _creditAirdrop(address _user, address _token, uint256 _amt) internal {
airdropBalances[_token][_user] = (airdropBalances[_token][_user]).add(_amt);
emit ClaimAirdrop(_user, _token, _amt);
}
function getReward(uint256 _pid, address _user, address _lpAdd, address _token) public view returns (uint256) {
uint256 stake = stakedLPTokensInfo[_pid][_lpAdd];
if(address(this).balance==0) return 0; //inject PRESENT ETHER
uint256 _multipliedData = (userStakeInfo[_pid][_user][_lpAdd]).mul(fundsRaisedSoFar[_pid][_token]);
_multipliedData = (_multipliedData).mul(rewardPer).mul(fee).mul(stakingWeight[_lpAdd]);
return (((_multipliedData).div(stake)).div(1e8)).div(totalStakeWeight);
}
function getAirdrop(uint256 _pid, address _user, address _lpAdd) public view returns (uint256) {
uint256 _userStaked = userStakeInfo[_pid][_user][_lpAdd];
uint256 _totalStaked = stakedLPTokensInfo[_pid][_lpAdd];
if(address(this).balance==0) return 0; //inject PRESENT ETHER
return ((((_userStaked).mul(airdropInfo[_pid].totalTokensAvailable).mul(stakingWeight[_lpAdd])).div(_totalStaked))).div(totalStakeWeight);
}
// Deposit ICO tokens for a use case as reserve.
function depositReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd, address _resAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(poolU.tokensDeposited == false, "DR"); // TOKENS NOT DEPOSITED
require(poolU.tokensAllocated == _amount && _amount!=0, "NA"); // NOT AVAILABLE
require(block.number < pool.endBlock, "CRN"); // CANNOT_RESERVE_NOW to avoid deadlocks
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
totalTokenReserved[_pid] = (totalTokenReserved[_pid]).add(_amount);
poolU.tokensDeposited = true;
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw extra unsold ICO tokens or extra deposited tokens.
function withdrawExtraICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number > pool.endBlock, "NA"); // NOT AVAILABLE TIME
uint256 _amtAvail = pool.tokensDeposited.sub(pool.totalTokensSold);
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE TOKEN
pool.tokensDeposited = (pool.tokensDeposited).sub(_amount);
_tokenAdd.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
// Fetch extra ICO tokens available.
function fetchExtraICOTokens(uint256 _pid) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
return pool.tokensDeposited.sub(pool.totalTokensSold);
}
// Deposit tokens to a pool for ICO.
function deposit(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
address msgSender = _msgSender();
uint256 _buyThisStep = _checkDepositAllowed(_pid, address(_tokenAdd), _amount);
// require(_buyThisStep >= _amount, "CDE");
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
userDepositInfo[_pid][msgSender][address(_tokenAdd)] = userDepositInfo[_pid][msgSender][address(_tokenAdd)].add(_amount);
userTokenAllocation[_pid][msgSender] = userTokenAllocation[_pid][msgSender].add(_buyThisStep);
poolInfo[_pid].totalTokensSold = poolInfo[_pid].totalTokensSold.add(_buyThisStep);
fundsRaisedSoFar[_pid][address(_tokenAdd)] = fundsRaisedSoFar[_pid][address(_tokenAdd)].add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Vote your favourite ICO project.
function voteProject(uint256 _pid) external {
address msgSender = _msgSender();
require(userVotes[_pid][msgSender]==false,"AVO"); // ALREADY VOTED
require(poolInfo[_pid].endBlock >= block.number,"CVO"); // CANNOT VOTE NOW
userVotes[_pid][msgSender] = true;
poolInfo[_pid].votes = (poolInfo[_pid].votes).add(1);
emit Voted(msgSender, _pid);
}
function _calculatePerAvailable(uint256[] memory _daysArray, uint256[] memory _percentArray, uint256 blockEnd) internal view returns (uint256) {
uint256 _defaultPer = 10000;
uint256 _perNow;
if(address(this).balance==0){ //inject PRESENT ETHER
return _defaultPer;
}
uint256 daysDone = ((block.number).sub(blockEnd)).div(BLOCKS_PER_DAY);
for (uint256 i = 0; i < _daysArray.length; i++) {
if(_daysArray[i] <= daysDone){
_perNow = _perNow.add(_percentArray[i]);
}
else {
break;
}
}
return _perNow;
}
function _getPercentAvailable(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = userDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now - public
function amountAvailToWithdrawUser(uint256 _pid, address _user) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailable(_pid, pool.endBlock);
return ((percentAvail).mul(userTokenAllocation[_pid][_user]).div(10000)).sub(userTokenClaimed[_pid][_user]);
}
else {
return 0;
}
}
// Withdraw ICO tokens after sale is over based on distribution rules.
function withdrawUser(uint256 _pid, uint256 _amount) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
uint256 _amtAvail = amountAvailToWithdrawUser(_pid, msgSender);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
userTokenClaimed[_pid][msgSender] = userTokenClaimed[_pid][msgSender].add(_amount);
totalTokenClaimed[_pid] = totalTokenClaimed[_pid].add(_amount);
pool.raiseToken.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
function _getPercentAvailableFundRaiser(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = ownerDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now
function amountAvailToWithdrawFundRaiser(uint256 _pid, IERC20 _tokenAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableFundRaiser(_pid, pool.endBlock);
return (((percentAvail).mul(fundsRaisedSoFar[_pid][address(_tokenAdd)]).div(10000))).sub(fundsClaimedSoFar[_pid][address(_tokenAdd)]);
}
else {
return 0;
}
}
function _getPercentAvailableReserve(uint256 _pid, uint256 blockEnd, address _resAdd) internal view returns (uint256){
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
uint256[] storage _percentArray = poolU.unlock_perArray;
uint256[] storage _daysArray = poolU.unlock_daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by reserve user till now
function amountAvailToWithdrawReserve(uint256 _pid, address _resAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableReserve(_pid, pool.endBlock, _resAdd);
return ((percentAvail).mul(poolU.tokensAllocated).div(10000)).sub(poolU.tokensClaimed);
}
else {
return 0;
}
}
// Withdraw ICO tokens for various use cases as per the schedule promised on provided address.
function withdrawReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_msgSender()];
require(poolU.reserveAdd == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
require(_tokenAdd == poolInfo[_pid].raiseToken, "NT"); // NOT AUTHORISED TOKEN
uint256 _amtAvail = amountAvailToWithdrawReserve(_pid, _msgSender());
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE USER
poolU.tokensClaimed = poolU.tokensClaimed.add(_amount);
totalTokenReserved[_pid] = totalTokenReserved[_pid].sub(_amount);
totalReservedTokenClaimed[_pid] = totalReservedTokenClaimed[_pid].add(_amount);
_tokenAdd.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _pid, _amount);
}
// Withdraw raised funds after sale is over as per the schedule promised
function withdrawFundRaiser(uint256 _pid, uint256 _amount, IERC20 _tokenAddress) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.owner == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
uint256 _amtAvail = amountAvailToWithdrawFundRaiser(_pid, _tokenAddress);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
uint256 _fee = ((_amount).mul(fee)).div(1e4);
uint256 _actualTransfer = _amtAvail.sub(_fee);
uint256 _feeDev = (_fee).mul(10000 - rewardPer).div(1e4); // Remaining tokens for reward mining
fundsClaimedSoFar[_pid][address(_tokenAddress)] = fundsClaimedSoFar[_pid][address(_tokenAddress)].add(_amount);
_tokenAddress.safeTransfer(_msgSender(), _actualTransfer);
_tokenAddress.safeTransfer(devaddr, _feeDev);
emit Withdraw(_msgSender(), _pid, _actualTransfer);
emit Withdraw(devaddr, _pid, _feeDev);
}
// Update dev address by initiating with the previous dev.
function changeDev(address _newowner) external onlyAdmin {
potentialAdmin = _newowner;
}
function becomeDev() external {
require(potentialAdmin == msg.sender, "NA"); // NOT ALLOWED
devaddr = msg.sender;
}
// Update temp pool owner address by initiating with the previous pool owner.
function changePoolOwner(uint256 _pid, address _newowner) external {
require(_msgSender()==poolInfo[_pid].owner, "OA"); // NOT AUTHORISED USER
tempAdmin[_pid] = _newowner;
}
// Claim pool ownership with new address
function becomePoolOwner(uint256 _pid) external {
if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender();
}
// Update fee, can never be more than 3%.
function changeFee(uint256 _fee) external onlyAdmin{
require(_fee <= 300, "MAX3"); // MAX FEE POSSIBLE
fee = _fee;
}
// To generate a new invite code
function generateNewCode(address _token, address _poolOwner) external onlyAdminOrTimeLock returns (uint256) {
uint256 inviteCode = block.number;
inviteCodeList[inviteCode][_token][_poolOwner] = true;
return inviteCode;
}
// To invalidate an invite code
function invalidateOldCode(uint256 _inviteCode, address _token, address _poolOwner) external onlyAdmin {
inviteCodeList[_inviteCode][_token][_poolOwner] = false;
}
// To add or update a staking pool with weight
function addStakingPool(address _token, uint256 _weight) external onlyAdmin {
if(stakingEnabled[_token]==false){
stakingPools.push(_token);
stakingEnabled[_token] = true;
}
totalStakeWeight = totalStakeWeight.sub(stakingWeight[_token]).add(_weight);
stakingWeight[_token] = _weight;
}
} | To store list of all reserve addresses for a sale | mapping (uint256 => address[]) public listReserveAddresses;
| 1,045,255 | [
1,
774,
1707,
666,
434,
777,
20501,
6138,
364,
279,
272,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
261,
11890,
5034,
516,
225,
1758,
63,
5717,
1071,
666,
607,
6527,
7148,
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
] |
/*
_____ ____ _____ ______ _______ ____ _____ ______ _____
____|\ \ ____|\ \ ___|\ \ | \/ \ | ||\ \ |\ \ ___|\ \
| | \ \ / /\ \ | |\ \ / /\ \ | | \\ \| \ \ / /\ \
| |______/| | | || | | | / /\ / /\ || | \| \ \ || | |____|
| |----'\ | |__| || |/____/ / /\ \_/ / / /|| | | \ | || | ____
| |_____/ | .--. || |\ \ | | \|_|/ / / || | | \ | || | | |
| | | | | || | | || | | | || | | |\ \| || | |_, |
|____| |____| |____||____| |____||\____\ |____| /|____| |____||\_____/||\ ___\___/ /|
| | | | | || | | || | | | | / | | | |/ \| ||| | /____ / |
|____| |____| |____||____| |____| \|____| |____|/ |____| |____| |___|/ \|___| | /
)/ \( )/ \( )/ \( )/ \( \( )/ \( |____|/
' ' ' ' ' ' ' ' ' ' ' )/
'
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: VAMPRewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* 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
*/
pragma solidity ^0.5.17;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/IRewardDistributionRecipient.sol
pragma solidity ^0.5.0;
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
function notifyRewardAmount() external;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
// File: contracts/CurveRewards.sol
pragma solidity ^0.5.0;
pragma solidity ^0.5.17;
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public uni = IERC20(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
uni.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
uni.safeTransfer(msg.sender, amount);
}
}
contract VAMPUNIPOOL is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public vamp = IERC20(0xeFe8AfF127Df9e1ea70233EDE4E04fcF0652d475);
uint256 public DURATION = 7 days;
uint256 public generation = 3;
uint256 public initreward = 93500 ether;
uint256 public starttime = 1601308800;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkhalve checkStart{
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public updateReward(msg.sender) checkStart{
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkhalve checkStart{
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
vamp.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
modifier checkhalve() {
if (block.timestamp >= periodFinish) {
generation = generation.add(1);
if (generation == 4) {
DURATION = 6 days;
initreward = 136000 ether;
rewardRate = initreward.div(DURATION);
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(initreward);
} else if (generation == 5) {
DURATION = 5 days;
initreward = 178500 ether;
rewardRate = initreward.div(DURATION);
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(initreward);
} else if (generation == 6) {
DURATION = 3 days;
initreward = 229500 ether;
rewardRate = initreward.div(DURATION);
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(initreward);
} else if (generation > 6) {
uint256 balance = vamp.balanceOf(address(this));
require(balance > 0, "Contract is empty, all rewards distributed");
vamp.safeTransfer(owner(), balance); //transfer any leftover rewards to the owner to be burned or airdropped.
}
}
_;
}
modifier checkStart(){
require(block.timestamp > starttime,"not start");
_;
}
function notifyRewardAmount()
external
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = initreward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = initreward.add(leftover).div(DURATION);
}
// vamp.mint(address(this),initreward);
starttime = block.timestamp;
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(initreward);
}
} | stake visibility is public as overriding LPTokenWrapper's stake() function | function stake(uint256 amount) public updateReward(msg.sender) checkhalve checkStart{
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
| 491,785 | [
1,
334,
911,
9478,
353,
1071,
487,
19488,
511,
52,
1345,
3611,
1807,
384,
911,
1435,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
911,
12,
11890,
5034,
3844,
13,
1071,
1089,
17631,
1060,
12,
3576,
18,
15330,
13,
866,
22314,
537,
866,
1685,
95,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
4515,
384,
911,
374,
8863,
203,
3639,
2240,
18,
334,
911,
12,
8949,
1769,
203,
3639,
3626,
934,
9477,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xd920556b0f3522bB1257923292A256F1e3023e07/sources/TokenWrapper.sol | * @dev Returns total amount of staked tokens/ | {
return _totalStaked;
}
| 9,746,345 | [
1,
1356,
2078,
3844,
434,
384,
9477,
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,
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,
288,
203,
3639,
327,
389,
4963,
510,
9477,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "./PodPut.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../lib/Conversion.sol";
/**
* @title WPodPut
* @author Pods Finance
*
* @notice Represents a tokenized Put option series for ETH. Internally it Wraps
* ETH to treat it seamlessly.
*
* @dev Put options represents the right, not the obligation to sell the underlying asset
* for strike price units of the strike asset.
*
* There are four main actions that can be done with an option:
*
* Sellers can mint fungible Put option tokens by locking strikePrice * amountOfOptions
* strike asset units until expiration. Buyers can exercise their Put, meaning
* selling their underlying asset for strikePrice * amountOfOptions units of strike asset.
* At the end, seller can retrieve back its collateral, that could be the underlying asset
* AND/OR strike based on the contract's current ratio of underlying and strike assets.
*
* There are many option's style, but the most usual are: American and European.
* The difference between them are the moments that the buyer is allowed to exercise and
* the moment that seller can retrieve its locked collateral.
*
* Exercise:
* American -> any moment until expiration
* European -> only after expiration and until the end of the exercise window
*
* Withdraw:
* American -> after expiration
* European -> after end of exercise window
*
* Let's take an example: there is such a put option series where buyers
* may sell 1 ETH for 300 USDC until Dec 31, 2021.
*
* In this case:
*
* - Expiration date: Dec 31, 2021
* - Underlying asset: ETH
* - Strike asset: USDC
* - Strike price: 300 USDC
*
* USDC holders may call mint() until the expiration date, which in turn:
*
* - Will lock their USDC into this contract
* - Will issue put tokens corresponding to this USDC amount
* - This contract is agnostic about where options could be bought or sold and how much the
* the option premium should be.
*
* USDC holders who also hold the option tokens may call unmint() until the
* expiration date, which in turn:
*
* - Will unlock their USDC from this contract
* - Will burn the corresponding amount of put tokens
*
* Put token holders may call exerciseEth() until the expiration date, to
* exercise their option, which in turn:
*
* - Will sell 1 ETH for 300 USDC (the strike price) each.
* - Will burn the corresponding amount of put tokens.
*
* IMPORTANT: Note that after expiration, option tokens are worthless since they can not
* be exercised and its price should be worth 0 in a healthy market.
*
*/
contract WPodPut is PodPut, Conversion {
event Received(address indexed sender, uint256 value);
constructor(
string memory name,
string memory symbol,
IPodOption.ExerciseType exerciseType,
address strikeAsset,
uint256 strikePrice,
uint256 expiration,
uint256 exerciseWindowSize,
IConfigurationManager configurationManager
)
public
PodPut(
name,
symbol,
exerciseType,
_parseAddressFromUint(configurationManager.getParameter("WRAPPED_NETWORK_TOKEN")),
strikeAsset,
strikePrice,
expiration,
exerciseWindowSize,
configurationManager
)
{} // solhint-disable-line no-empty-blocks
/**
* @notice Unlocks collateral by burning option tokens.
*
* Options can only be burned while the series is NOT expired.
*
* @param amountOfOptions The amount option tokens to be burned
*/
function unmint(uint256 amountOfOptions) external override unmintWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender);
require(strikeToSend > 0, "WPodPut: amount of options is too low");
// Sends strike asset
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend);
}
/**
* @notice Allow Put token holders to use them to sell some amount of units
* of ETH for the amount * strike price units of the strike token.
*
* @dev It uses the amount of ETH sent to exchange to the strike amount
*
* During the process:
*
* - The amount of ETH is transferred into this contract as a payment for the strike tokens
* - The ETH is wrapped into WETH
* - The amount of ETH * strikePrice of strike tokens are transferred to the caller
* - The amount of option tokens are burned
*
* On American options, this function can only called anytime before expiration.
* For European options, this function can only be called during the exerciseWindow.
* Meaning, after expiration and before the end of exercise window.
*/
function exerciseEth() external payable exerciseWindow {
uint256 amountOfOptions = msg.value;
require(amountOfOptions > 0, "WPodPut: you can not exercise zero options");
// Calculate the strike amount equivalent to pay for the underlying requested
uint256 strikeToSend = _strikeToTransfer(amountOfOptions);
// Burn the option tokens equivalent to the underlying requested
_burn(msg.sender, amountOfOptions);
// Retrieve the underlying asset from caller
IWETH(underlyingAsset()).deposit{ value: msg.value }();
// Releases the strike asset to caller, completing the exchange
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
emit Exercise(msg.sender, amountOfOptions);
}
/**
* @notice After series expiration in case of American or after exercise window for European,
* allow minters who have locked their strike asset tokens to withdraw them proportionally
* to their minted options.
*
* @dev If assets had been exercised during the option series the minter may withdraw
* the exercised assets or a combination of exercised and strike asset tokens.
*/
function withdraw() external override withdrawWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _withdraw();
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
if (underlyingToSend > 0) {
IWETH(underlyingAsset()).withdraw(underlyingToSend);
Address.sendValue(msg.sender, underlyingToSend);
}
emit Withdraw(msg.sender, strikeToSend, underlyingToSend);
}
receive() external payable {
require(msg.sender == this.underlyingAsset(), "WPodPut: Only deposits from WETH are allowed");
emit Received(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "./PodOption.sol";
/**
* @title PodPut
* @author Pods Finance
*
* @notice Represents a tokenized Put option series for some long/short token pair.
*
* @dev Put options represents the right, not the obligation to sell the underlying asset
* for strike price units of the strike asset.
*
* There are four main actions that can be done with an option:
*
* Sellers can mint fungible Put option tokens by locking strikePrice * amountOfOptions
* strike asset units until expiration. Buyers can exercise their Put, meaning
* selling their underlying asset for strikePrice * amountOfOptions units of strike asset.
* At the end, seller can retrieve back its collateral, that could be the underlying asset
* AND/OR strike based on the contract's current ratio of underlying and strike assets.
*
* There are many option's style, but the most usual are: American and European.
* The difference between them are the moments that the buyer is allowed to exercise and
* the moment that seller can retrieve its locked collateral.
*
* Exercise:
* American -> any moment until expiration
* European -> only after expiration and until the end of the exercise window
*
* Withdraw:
* American -> after expiration
* European -> after end of exercise window
*
* Let's take an example: there is such an European Put option series where buyers
* may sell 1 WETH for 300 USDC until Dec 31, 2021.
*
* In this case:
*
* - Expiration date: Dec 31, 2021
* - Underlying asset: WETH
* - Strike asset: USDC
* - Strike price: 300 USDC
*
* USDC holders may call mint() until the expiration date, which in turn:
*
* - Will lock their USDC into this contract
* - Will mint/issue option tokens corresponding to this USDC amount
* - This contract is agnostic about where to sell/buy and how much should be the
* the option premium.
*
* USDC holders who also hold the option tokens may call unmint() until the
* expiration date, which in turn:
*
* - Will unlock their USDC from this contract
* - Will burn the corresponding amount of options tokens
*
* Option token holders may call exercise() after the expiration date and
* before the end of exercise window, to exercise their option, which in turn:
*
* - Will sell 1 ETH for 300 USDC (the strike price) each.
* - Will burn the corresponding amount of option tokens.
*
* USDC holders that minted options initially can call withdraw() after the
* end of exercise window, which in turn:
*
* - Will give back its amount of collateral locked. That could be o mix of
* underlying asset and strike asset based if and how the pool was exercised.
*
* IMPORTANT: Note that after expiration, option tokens are worthless since they can not
* be exercised and its price should worth 0 in a healthy market.
*
*/
contract PodPut is PodOption {
constructor(
string memory name,
string memory symbol,
IPodOption.ExerciseType exerciseType,
address underlyingAsset,
address strikeAsset,
uint256 strikePrice,
uint256 expiration,
uint256 exerciseWindowSize,
IConfigurationManager configurationManager
)
public
PodOption(
name,
symbol,
IPodOption.OptionType.PUT,
exerciseType,
underlyingAsset,
strikeAsset,
strikePrice,
expiration,
exerciseWindowSize,
configurationManager
)
{} // solhint-disable-line no-empty-blocks
/**
* @notice Locks strike asset and write option tokens.
*
* @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token.
*
* It presumes the caller has already called IERC20.approve() on the
* strike token contract to move caller funds.
*
* This function is meant to be called by strike token holders wanting
* to write option tokens. Calling it will lock `amountOfOptions` * `strikePrice`
* units of `strikeToken` into this contract
*
* Options can only be minted while the series is NOT expired.
*
* It is also important to notice that options will be sent back
* to `msg.sender` and not the `owner`. This behavior is designed to allow
* proxy contracts to mint on others behalf. The `owner` will be able to remove
* the deposited collateral after series expiration or by calling unmint(), even
* if a third-party minted options on its behalf.
*
* @param amountOfOptions The amount option tokens to be issued
* @param owner Which address will be the owner of the options
*/
function mint(uint256 amountOfOptions, address owner) external override tradeWindow {
require(amountOfOptions > 0, "PodPut: you can not mint zero options");
uint256 amountToTransfer = _strikeToTransfer(amountOfOptions);
_mintOptions(amountOfOptions, amountToTransfer, owner);
IERC20(strikeAsset()).safeTransferFrom(msg.sender, address(this), amountToTransfer);
emit Mint(owner, amountOfOptions);
}
/**
* @notice Unlocks collateral by burning option tokens.
*
* Options can only be burned while the series is NOT expired.
*
* @param amountOfOptions The amount option tokens to be burned
*/
function unmint(uint256 amountOfOptions) external virtual override unmintWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender);
require(strikeToSend > 0, "PodPut: amount of options is too low");
// Sends strike asset
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend);
}
/**
* @notice Allow Put token holders to use them to sell some amount of units
* of the underlying token for the amount * strike price units of the
* strike token.
*
* @dev It presumes the caller has already called IERC20.approve() on the
* underlying token contract to move caller funds.
*
* During the process:
*
* - The amount * strikePrice of strike tokens are transferred to the caller
* - The amount of option tokens are burned
* - The amount of underlying tokens are transferred into
* this contract as a payment for the strike tokens
*
* On American options, this function can only called anytime before expiration.
* For European options, this function can only be called during the exerciseWindow.
* Meaning, after expiration and before the end of exercise window.
*
* @param amountOfOptions The amount option tokens to be exercised
*/
function exercise(uint256 amountOfOptions) external virtual override exerciseWindow {
require(amountOfOptions > 0, "PodPut: you can not exercise zero options");
// Calculate the strike amount equivalent to pay for the underlying requested
uint256 amountOfStrikeToTransfer = _strikeToTransfer(amountOfOptions);
// Burn the option tokens equivalent to the underlying requested
_burn(msg.sender, amountOfOptions);
// Retrieve the underlying asset from caller
IERC20(underlyingAsset()).safeTransferFrom(msg.sender, address(this), amountOfOptions);
// Releases the strike asset to caller, completing the exchange
IERC20(strikeAsset()).safeTransfer(msg.sender, amountOfStrikeToTransfer);
emit Exercise(msg.sender, amountOfOptions);
}
/**
* @notice After series expiration in case of American or after exercise window for European,
* allow minters who have locked their strike asset tokens to withdraw them proportionally
* to their minted options.
*
* @dev If assets had been exercised during the option series the minter may withdraw
* the exercised assets or a combination of exercised and strike asset tokens.
*/
function withdraw() external virtual override withdrawWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _withdraw();
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
if (underlyingToSend > 0) {
IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend);
}
emit Withdraw(msg.sender, strikeToSend, underlyingToSend);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
event Deposit(address indexed depositor, uint256 amount);
event Withdrawal(address indexed recipient, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
contract Conversion {
/**
* @notice Parses the address represented by an uint
*/
function _parseAddressFromUint(uint256 x) internal pure returns (address) {
bytes memory data = new bytes(32);
assembly {
mstore(add(data, 32), x)
}
return abi.decode(data, (address));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IPodOption.sol";
import "../lib/CappedOption.sol";
import "../lib/RequiredDecimals.sol";
import "../interfaces/IConfigurationManager.sol";
/**
* @title PodOption
* @author Pods Finance
*
* @notice This contract represents the basic structure of the financial instrument
* known as Option, sharing logic between both a PUT or a CALL types.
*
* @dev There are four main actions that can be called in an Option:
*
* A) mint => A minter can lock collateral and create new options before expiration.
* B) unmint => The minter who previously minted can choose for leaving its position any given time
* until expiration.
* C) exercise => The option bearer the can exchange its option for the collateral at the strike price.
* D) withdraw => The minter can retrieve collateral at the end of the series.
*
* Depending on the type (PUT / CALL) or the exercise (AMERICAN / EUROPEAN), those functions have
* different behave and should be override accordingly.
*/
abstract contract PodOption is IPodOption, ERC20, RequiredDecimals, CappedOption {
using SafeERC20 for IERC20;
/**
* @dev Minimum allowed exercise window: 24 hours
*/
uint256 public constant MIN_EXERCISE_WINDOW_SIZE = 86400;
OptionType private immutable _optionType;
ExerciseType private immutable _exerciseType;
IConfigurationManager public immutable configurationManager;
address private immutable _underlyingAsset;
uint8 private immutable _underlyingAssetDecimals;
address private immutable _strikeAsset;
uint8 private immutable _strikeAssetDecimals;
uint256 private immutable _strikePrice;
uint256 private immutable _expiration;
uint256 private _startOfExerciseWindow;
/**
* @notice Reserve share balance
* @dev Tracks the shares of the total asset reserve by address
*/
mapping(address => uint256) public shares;
/**
* @notice Minted option balance
* @dev Tracks amount of minted options by address
*/
mapping(address => uint256) public mintedOptions;
/**
* @notice Total reserve shares
*/
uint256 public totalShares = 0;
constructor(
string memory name,
string memory symbol,
OptionType optionType,
ExerciseType exerciseType,
address underlyingAsset,
address strikeAsset,
uint256 strikePrice,
uint256 expiration,
uint256 exerciseWindowSize,
IConfigurationManager _configurationManager
) public ERC20(name, symbol) CappedOption(_configurationManager) {
require(Address.isContract(underlyingAsset), "PodOption: underlying asset is not a contract");
require(Address.isContract(strikeAsset), "PodOption: strike asset is not a contract");
require(underlyingAsset != strikeAsset, "PodOption: underlying asset and strike asset must differ");
require(expiration > block.timestamp, "PodOption: expiration should be in the future");
require(strikePrice > 0, "PodOption: strike price must be greater than zero");
if (exerciseType == ExerciseType.EUROPEAN) {
require(
exerciseWindowSize >= MIN_EXERCISE_WINDOW_SIZE,
"PodOption: exercise window must be greater than or equal 86400"
);
_startOfExerciseWindow = expiration.sub(exerciseWindowSize);
} else {
require(exerciseWindowSize == 0, "PodOption: exercise window size must be equal to zero");
_startOfExerciseWindow = block.timestamp;
}
configurationManager = _configurationManager;
_optionType = optionType;
_exerciseType = exerciseType;
_expiration = expiration;
_underlyingAsset = underlyingAsset;
_strikeAsset = strikeAsset;
uint8 underlyingDecimals = tryDecimals(IERC20(underlyingAsset));
_underlyingAssetDecimals = underlyingDecimals;
_strikeAssetDecimals = tryDecimals(IERC20(strikeAsset));
_strikePrice = strikePrice;
_setupDecimals(underlyingDecimals);
}
/**
* @notice Checks if the options series has already expired.
*/
function hasExpired() external override view returns (bool) {
return _hasExpired();
}
/**
* @notice External function to calculate the amount of strike asset
* needed given the option amount
*/
function strikeToTransfer(uint256 amountOfOptions) external override view returns (uint256) {
return _strikeToTransfer(amountOfOptions);
}
/**
* @notice Checks if the options trade window has opened.
*/
function isTradeWindow() external override view returns (bool) {
return _isTradeWindow();
}
/**
* @notice Checks if the options exercise window has opened.
*/
function isExerciseWindow() external override view returns (bool) {
return _isExerciseWindow();
}
/**
* @notice Checks if the options withdraw window has opened.
*/
function isWithdrawWindow() external override view returns (bool) {
return _isWithdrawWindow();
}
/**
* @notice The option type. eg: CALL, PUT
*/
function optionType() external override view returns (OptionType) {
return _optionType;
}
/**
* @notice Exercise type. eg: AMERICAN, EUROPEAN
*/
function exerciseType() external override view returns (ExerciseType) {
return _exerciseType;
}
/**
* @notice The sell price of each unit of underlyingAsset; given in units
* of strikeAsset, e.g. 0.99 USDC
*/
function strikePrice() external override view returns (uint256) {
return _strikePrice;
}
/**
* @notice The number of decimals of strikePrice
*/
function strikePriceDecimals() external override view returns (uint8) {
return _strikeAssetDecimals;
}
/**
* @notice The timestamp in seconds that represents the series expiration
*/
function expiration() external override view returns (uint256) {
return _expiration;
}
/**
* @notice How many decimals does the strike token have? E.g.: 18
*/
function strikeAssetDecimals() public override view returns (uint8) {
return _strikeAssetDecimals;
}
/**
* @notice The asset used as the strike asset, e.g. USDC, DAI
*/
function strikeAsset() public override view returns (address) {
return _strikeAsset;
}
/**
* @notice How many decimals does the underlying token have? E.g.: 18
*/
function underlyingAssetDecimals() public override view returns (uint8) {
return _underlyingAssetDecimals;
}
/**
* @notice The asset used as the underlying token, e.g. WETH, WBTC, UNI
*/
function underlyingAsset() public override view returns (address) {
return _underlyingAsset;
}
/**
* @notice getSellerWithdrawAmounts returns the seller position based on his amount of shares
* and the current option position
*
* @param owner address of the user to check the withdraw amounts
*
* @return strikeAmount current amount of strike the user will receive. It may change until maturity
* @return underlyingAmount current amount of underlying the user will receive. It may change until maturity
*/
function getSellerWithdrawAmounts(address owner)
public
override
view
returns (uint256 strikeAmount, uint256 underlyingAmount)
{
uint256 ownerShares = shares[owner];
strikeAmount = ownerShares.mul(strikeReserves()).div(totalShares);
underlyingAmount = ownerShares.mul(underlyingReserves()).div(totalShares);
return (strikeAmount, underlyingAmount);
}
/**
* @notice The timestamp in seconds that represents the start of exercise window
*/
function startOfExerciseWindow() public override view returns (uint256) {
return _startOfExerciseWindow;
}
/**
* @notice Utility function to check the amount of the underlying tokens
* locked inside this contract
*/
function underlyingReserves() public override view returns (uint256) {
return IERC20(_underlyingAsset).balanceOf(address(this));
}
/**
* @notice Utility function to check the amount of the strike tokens locked
* inside this contract
*/
function strikeReserves() public override view returns (uint256) {
return IERC20(_strikeAsset).balanceOf(address(this));
}
/**
* @dev Modifier with the conditions to be able to mint
* based on option exerciseType.
*/
modifier tradeWindow() {
require(_isTradeWindow(), "PodOption: trade window has closed");
_;
}
/**
* @dev Modifier with the conditions to be able to unmint
* based on option exerciseType.
*/
modifier unmintWindow() {
require(_isTradeWindow() || _isExerciseWindow(), "PodOption: not in unmint window");
_;
}
/**
* @dev Modifier with the conditions to be able to exercise
* based on option exerciseType.
*/
modifier exerciseWindow() {
require(_isExerciseWindow(), "PodOption: not in exercise window");
_;
}
/**
* @dev Modifier with the conditions to be able to withdraw
* based on exerciseType.
*/
modifier withdrawWindow() {
require(_isWithdrawWindow(), "PodOption: option has not expired yet");
_;
}
/**
* @dev Internal function to check expiration
*/
function _hasExpired() internal view returns (bool) {
return block.timestamp >= _expiration;
}
/**
* @dev Internal function to check trade window
*/
function _isTradeWindow() internal view returns (bool) {
if (_hasExpired()) {
return false;
} else if (_exerciseType == ExerciseType.EUROPEAN) {
return !_isExerciseWindow();
}
return true;
}
/**
* @dev Internal function to check window exercise started
*/
function _isExerciseWindow() internal view returns (bool) {
return !_hasExpired() && block.timestamp >= _startOfExerciseWindow;
}
/**
* @dev Internal function to check withdraw started
*/
function _isWithdrawWindow() internal view returns (bool) {
return _hasExpired();
}
/**
* @dev Internal function to calculate the amount of strike asset needed given the option amount
* @param amountOfOptions Intended amount to options to mint
*/
function _strikeToTransfer(uint256 amountOfOptions) internal view returns (uint256) {
uint256 strikeAmount = amountOfOptions.mul(_strikePrice).div(10**uint256(underlyingAssetDecimals()));
require(strikeAmount > 0, "PodOption: amount of options is too low");
return strikeAmount;
}
/**
* @dev Calculate number of reserve shares based on the amount of collateral locked by the minter
*/
function _calculatedShares(uint256 amountOfCollateral) internal view returns (uint256 ownerShares) {
uint256 currentStrikeReserves = strikeReserves();
uint256 currentUnderlyingReserves = underlyingReserves();
uint256 numerator = amountOfCollateral.mul(totalShares);
uint256 denominator;
if (_optionType == OptionType.PUT) {
denominator = currentStrikeReserves.add(
currentUnderlyingReserves.mul(_strikePrice).div(uint256(10)**underlyingAssetDecimals())
);
} else {
denominator = currentUnderlyingReserves.add(
currentStrikeReserves.mul(uint256(10)**underlyingAssetDecimals()).div(_strikePrice)
);
}
ownerShares = numerator.div(denominator);
return ownerShares;
}
/**
* @dev Mint options, creating the shares accordingly to the amount of collateral provided
* @param amountOfOptions The amount option tokens to be issued
* @param amountOfCollateral The amount of collateral provided to mint options
* @param owner Which address will be the owner of the options
*/
function _mintOptions(
uint256 amountOfOptions,
uint256 amountOfCollateral,
address owner
) internal capped(amountOfOptions) {
require(owner != address(0), "PodOption: zero address cannot be the owner");
if (totalShares > 0) {
uint256 ownerShares = _calculatedShares(amountOfCollateral);
shares[owner] = shares[owner].add(ownerShares);
totalShares = totalShares.add(ownerShares);
} else {
shares[owner] = amountOfCollateral;
totalShares = amountOfCollateral;
}
mintedOptions[owner] = mintedOptions[owner].add(amountOfOptions);
_mint(msg.sender, amountOfOptions);
}
/**
* @dev Unmints options, burning the option tokens removing shares accordingly and releasing a certain
* amount of collateral.
* @param amountOfOptions The amount option tokens to be burned
* @param owner Which address options will be burned from
*/
function _unmintOptions(uint256 amountOfOptions, address owner)
internal
returns (uint256 strikeToSend, uint256 underlyingToSend)
{
require(shares[owner] > 0, "PodOption: you do not have minted options");
require(amountOfOptions <= mintedOptions[owner], "PodOption: not enough minted options");
uint256 burnedShares = shares[owner].mul(amountOfOptions).div(mintedOptions[owner]);
if (_optionType == IPodOption.OptionType.PUT) {
uint256 strikeAssetDeposited = totalSupply().mul(_strikePrice).div(10**uint256(decimals()));
uint256 totalInterest = 0;
if (strikeReserves() > strikeAssetDeposited) {
totalInterest = strikeReserves().sub(strikeAssetDeposited);
}
strikeToSend = amountOfOptions.mul(_strikePrice).div(10**uint256(decimals())).add(
totalInterest.mul(burnedShares).div(totalShares)
);
// In the case we lost some funds due to precision, the last user to unmint will still be able to perform.
if (strikeToSend > strikeReserves()) {
strikeToSend = strikeReserves();
}
} else {
uint256 underlyingAssetDeposited = totalSupply();
uint256 currentUnderlyingAmount = underlyingReserves().add(strikeReserves().div(_strikePrice));
uint256 totalInterest = 0;
if (currentUnderlyingAmount > underlyingAssetDeposited) {
totalInterest = currentUnderlyingAmount.sub(underlyingAssetDeposited);
}
underlyingToSend = amountOfOptions.add(totalInterest.mul(burnedShares).div(totalShares));
}
shares[owner] = shares[owner].sub(burnedShares);
mintedOptions[owner] = mintedOptions[owner].sub(amountOfOptions);
totalShares = totalShares.sub(burnedShares);
_burn(owner, amountOfOptions);
}
/**
* @dev Removes all shares, returning the amounts that would be withdrawable
*/
function _withdraw() internal returns (uint256 strikeToSend, uint256 underlyingToSend) {
uint256 ownerShares = shares[msg.sender];
require(ownerShares > 0, "PodOption: you do not have balance to withdraw");
(strikeToSend, underlyingToSend) = getSellerWithdrawAmounts(msg.sender);
shares[msg.sender] = 0;
mintedOptions[msg.sender] = 0;
totalShares = totalShares.sub(ownerShares);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IPodOption is IERC20 {
/** Enums */
// @dev 0 for Put, 1 for Call
enum OptionType { PUT, CALL }
// @dev 0 for European, 1 for American
enum ExerciseType { EUROPEAN, AMERICAN }
/** Events */
event Mint(address indexed minter, uint256 amount);
event Unmint(address indexed minter, uint256 optionAmount, uint256 strikeAmount, uint256 underlyingAmount);
event Exercise(address indexed exerciser, uint256 amount);
event Withdraw(address indexed minter, uint256 strikeAmount, uint256 underlyingAmount);
/** Functions */
/**
* @notice Locks collateral and write option tokens.
*
* @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token.
*
* The collateral could be the strike or the underlying asset depending on the option type: Put or Call,
* respectively
*
* It presumes the caller has already called IERC20.approve() on the
* strike/underlying token contract to move caller funds.
*
* Options can only be minted while the series is NOT expired.
*
* It is also important to notice that options will be sent back
* to `msg.sender` and not the `owner`. This behavior is designed to allow
* proxy contracts to mint on others behalf. The `owner` will be able to remove
* the deposited collateral after series expiration or by calling unmint(), even
* if a third-party minted options on its behalf.
*
* @param amountOfOptions The amount option tokens to be issued
* @param owner Which address will be the owner of the options
*/
function mint(uint256 amountOfOptions, address owner) external;
/**
* @notice Allow option token holders to use them to exercise the amount of units
* of the locked tokens for the equivalent amount of the exercisable assets.
*
* @dev It presumes the caller has already called IERC20.approve() exercisable asset
* to move caller funds.
*
* On American options, this function can only called anytime before expiration.
* For European options, this function can only be called during the exerciseWindow.
* Meaning, after expiration and before the end of exercise window.
*
* @param amountOfOptions The amount option tokens to be exercised
*/
function exercise(uint256 amountOfOptions) external;
/**
* @notice After series expiration in case of American or after exercise window for European,
* allow minters who have locked their collateral to withdraw them proportionally
* to their minted options.
*
* @dev If assets had been exercised during the option series the minter may withdraw
* the exercised assets or a combination of exercised and collateral.
*/
function withdraw() external;
/**
* @notice Unlocks collateral by burning option tokens.
*
* Options can only be burned while the series is NOT expired.
*
* @param amountOfOptions The amount option tokens to be burned
*/
function unmint(uint256 amountOfOptions) external;
function optionType() external view returns (OptionType);
function exerciseType() external view returns (ExerciseType);
function underlyingAsset() external view returns (address);
function underlyingAssetDecimals() external view returns (uint8);
function strikeAsset() external view returns (address);
function strikeAssetDecimals() external view returns (uint8);
function strikePrice() external view returns (uint256);
function strikePriceDecimals() external view returns (uint8);
function expiration() external view returns (uint256);
function startOfExerciseWindow() external view returns (uint256);
function hasExpired() external view returns (bool);
function isTradeWindow() external view returns (bool);
function isExerciseWindow() external view returns (bool);
function isWithdrawWindow() external view returns (bool);
function strikeToTransfer(uint256 amountOfOptions) external view returns (uint256);
function getSellerWithdrawAmounts(address owner)
external
view
returns (uint256 strikeAmount, uint256 underlyingAmount);
function underlyingReserves() external view returns (uint256);
function strikeReserves() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IConfigurationManager.sol";
import "../interfaces/ICapProvider.sol";
/**
* @title CappedOption
* @author Pods Finance
*
* @notice Controls a maximum cap for a guarded release
*/
abstract contract CappedOption is IERC20 {
using SafeMath for uint256;
IConfigurationManager private immutable _configurationManager;
constructor(IConfigurationManager configurationManager) public {
_configurationManager = configurationManager;
}
/**
* @dev Modifier to stop transactions that exceed the cap
*/
modifier capped(uint256 amountOfOptions) {
uint256 cap = capSize();
if (cap > 0) {
require(this.totalSupply().add(amountOfOptions) <= cap, "CappedOption: amount exceed cap");
}
_;
}
/**
* @dev Get the cap size
*/
function capSize() public view returns (uint256) {
ICapProvider capProvider = ICapProvider(_configurationManager.getCapProvider());
return capProvider.getCap(address(this));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract RequiredDecimals {
uint256 private constant _MAX_TOKEN_DECIMALS = 38;
/**
* Tries to fetch the decimals of a token, if not existent, fails with a require statement
*
* @param token An instance of IERC20
* @return The decimals of a token
*/
function tryDecimals(IERC20 token) internal view returns (uint8) {
// solhint-disable-line private-vars-leading-underscore
bytes memory payload = abi.encodeWithSignature("decimals()");
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(token).staticcall(payload);
require(success, "RequiredDecimals: required decimals");
uint8 decimals = abi.decode(returnData, (uint8));
require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38");
return decimals;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.6.12;
interface IConfigurationManager {
function setParameter(bytes32 name, uint256 value) external;
function setEmergencyStop(address emergencyStop) external;
function setPricingMethod(address pricingMethod) external;
function setIVGuesser(address ivGuesser) external;
function setIVProvider(address ivProvider) external;
function setPriceProvider(address priceProvider) external;
function setCapProvider(address capProvider) external;
function setAMMFactory(address ammFactory) external;
function setOptionFactory(address optionFactory) external;
function setOptionHelper(address optionHelper) external;
function setOptionPoolRegistry(address optionPoolRegistry) external;
function getParameter(bytes32 name) external view returns (uint256);
function owner() external view returns (address);
function getEmergencyStop() external view returns (address);
function getPricingMethod() external view returns (address);
function getIVGuesser() external view returns (address);
function getIVProvider() external view returns (address);
function getPriceProvider() external view returns (address);
function getCapProvider() external view returns (address);
function getAMMFactory() external view returns (address);
function getOptionFactory() external view returns (address);
function getOptionHelper() external view returns (address);
function getOptionPoolRegistry() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface ICapProvider {
function setCap(address target, uint256 value) external;
function getCap(address target) external view returns (uint256);
}
| * @dev Modifier with the conditions to be able to withdraw based on exerciseType./ | modifier withdrawWindow() {
require(_isWithdrawWindow(), "PodOption: option has not expired yet");
_;
}
| 527,992 | [
1,
9829,
598,
326,
4636,
358,
506,
7752,
358,
598,
9446,
2511,
603,
24165,
559,
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,
9606,
598,
9446,
3829,
1435,
288,
203,
3639,
2583,
24899,
291,
1190,
9446,
3829,
9334,
315,
5800,
1895,
30,
1456,
711,
486,
7708,
4671,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.13;
/**
* Overflow aware uint math functions.
*
* Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol
*/
contract SafeMath {
//internals
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
require(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
require(c>=a && c>=b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
require(b > 0);
uint c = a / b;
require(a == b * c + a % b);
return c;
}
}
/**
* ERC 20 token
*
* https://github.com/ethereum/EIPs/issues/20
*/
interface Token {
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* ERC 20 token
*
* https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is Token {
/**
* Reviewed:
* - Integer overflow = OK, checked
*/
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
/**
* PIX crowdsale ICO contract.
*
* Security criteria evaluated against http://ethereum.stackexchange.com/questions/8551/methodological-security-review-of-a-smart-contract
*
*
*/
contract PIXToken is StandardToken, SafeMath {
string public name = "PIX Token";
string public symbol = "PIX";
// Initial founder address (set in constructor)
// This address is used as a controller address, in order to properly handle administration of the token.
address public founder = 0x0;
// Deposit Address - The funds will be sent here immediately after payments are made to the contract
address public deposit = 0x0;
/*
Multi-stage sale contract.
Notes:
All token sales are tied to USD. No token sales are for a fixed amount of Wei, this can shift and change over time.
Due to this, the following needs to be paid attention to:
1. The value of the token fluctuates in reference to the centsPerEth set on the contract.
2. The tokens are priced in cents. So all token purchases will be calculated out live at that time.
Funding Stages:
1. Pre-Sale, there will be 15M USD ( 125M tokens ) for sale. Bonus of 20%
2. Day 1 sale, there will be 20M USD - the pre-sale amount of tokens for sale. (~166.6m tokens - Pre-Sale tokens) Bonus of 15%
3. Day 2 sale, there will be 20M USD (~166.6m tokens) tokens for sale. Bonus of 10%
4. Days 3-10 sale, there will be 20M USD (~166.6m tokens) tokens for sale. Bonus of 5%
Post-Sale:
1. 30% of the total token count is reserved for release every year, at 1/4th of the originally reserved value per year.
2. 20% of the total token count [Minus the number of excess bonus tokens from the pre-sale] is issued out to the team when the sale has completed.
3. Purchased tokens come available to be withdrawn 31 days after the sale has completed.
*/
enum State { PreSale, Day1, Day2, Day3, Running, Halted } // the states through which this contract goes
State state;
// Pricing for the pre-sale in US Cents.
uint public capPreSale = 15 * 10**8; // 15M USD cap for pre-sale, this subtracts from day1 cap
uint public capDay1 = 20 * 10**8; // 20M USD cap for day 1
uint public capDay2 = 20 * 10**8; // 20M USD cap for day 2
uint public capDay3 = 20 * 10**8; // 20M USD cap for day 3 - 10
// Token pricing information
uint public weiPerEther = 10**18;
uint public centsPerEth = 23000;
uint public centsPerToken = 12;
// Amount of funds raised in stages of pre-sale
uint public raisePreSale = 0; // USD raise during the pre-sale period
uint public raiseDay1 = 0; // USD raised on Day 1
uint public raiseDay2 = 0; // USD raised on Day 2
uint public raiseDay3 = 0; // USD raised during days 3-10
// Block timing/contract unlocking information
uint public publicSaleStart = 1502280000; // Aug 9, 2017 Noon UTC
uint public day2Start = 1502366400; // Aug 10, 2017 Noon UTC
uint public day3Start = 1502452800; // Aug 11, 2017 Noon UTC
uint public saleEnd = 1503144000; // Aug 19, 2017 Noon UTC
uint public coinTradeStart = 1505822400; // Sep 19, 2017 Noon UTC
uint public year1Unlock = 1534680000; // Aug 19, 2018 Noon UTC
uint public year2Unlock = 1566216000; // Aug 19, 2019 Noon UTC
uint public year3Unlock = 1597838400; // Aug 19, 2020 Noon UTC
uint public year4Unlock = 1629374400; // Aug 19, 2021 Noon UTC
// Have the post-reward allocations been completed
bool public allocatedFounders = false;
bool public allocated1Year = false;
bool public allocated2Year = false;
bool public allocated3Year = false;
bool public allocated4Year = false;
// Token count information
uint public totalTokensSale = 500000000; //total number of tokens being sold in the ICO, excluding bonuses, reserve, and team distributions
uint public totalTokensReserve = 330000000;
uint public totalTokensCompany = 220000000;
bool public halted = false; //the founder address can set this to true to halt the crowdsale due to emergency.
mapping(address => uint256) presaleWhitelist; // Pre-sale Whitelist
event Buy(address indexed sender, uint eth, uint fbt);
event Withdraw(address indexed sender, address to, uint eth);
event AllocateTokens(address indexed sender);
function PIXToken(address depositAddress) {
/*
Initialize the contract with a sane set of owners
*/
founder = msg.sender; // Allocate the founder address as a usable address separate from deposit.
deposit = depositAddress; // Store the deposit address.
}
function setETHUSDRate(uint centsPerEthInput) public {
/*
Sets the current ETH/USD Exchange rate in cents. This modifies the token price in Wei.
*/
require(msg.sender == founder);
centsPerEth = centsPerEthInput;
}
/*
Gets the current state of the contract based on the block number involved in the current transaction.
*/
function getCurrentState() constant public returns (State) {
if(halted) return State.Halted;
else if(block.timestamp < publicSaleStart) return State.PreSale;
else if(block.timestamp > publicSaleStart && block.timestamp <= day2Start) return State.Day1;
else if(block.timestamp > day2Start && block.timestamp <= day3Start) return State.Day2;
else if(block.timestamp > day3Start && block.timestamp <= saleEnd) return State.Day3;
else return State.Running;
}
/*
Gets the current amount of bonus per purchase in percent.
*/
function getCurrentBonusInPercent() constant public returns (uint) {
State s = getCurrentState();
if (s == State.Halted) revert();
else if(s == State.PreSale) return 20;
else if(s == State.Day1) return 15;
else if(s == State.Day2) return 10;
else if(s == State.Day3) return 5;
else return 0;
}
/*
Get the current price of the token in WEI. This should be the weiPerEther/centsPerEth * centsPerToken
*/
function getTokenPriceInWEI() constant public returns (uint){
uint weiPerCent = safeDiv(weiPerEther, centsPerEth);
return safeMul(weiPerCent, centsPerToken);
}
/*
Entry point for purchasing for one's self.
*/
function buy() payable public {
buyRecipient(msg.sender);
}
/*
Main purchasing function for the contract
1. Should validate the current state, from the getCurrentState() function
2. Should only allow the founder to order during the pre-sale
3. Should correctly calculate the values to be paid out during different stages of the contract.
*/
function buyRecipient(address recipient) payable public {
State current_state = getCurrentState(); // Get the current state of the contract.
uint usdCentsRaise = safeDiv(safeMul(msg.value, centsPerEth), weiPerEther); // Get the current number of cents raised by the payment.
if(current_state == State.PreSale)
{
require (presaleWhitelist[msg.sender] > 0);
raisePreSale = safeAdd(raisePreSale, usdCentsRaise); //add current raise to pre-sell amount
require(raisePreSale < capPreSale && usdCentsRaise < presaleWhitelist[msg.sender]); //ensure pre-sale cap, 15m usd * 100 so we have cents
presaleWhitelist[msg.sender] = presaleWhitelist[msg.sender] - usdCentsRaise; // Remove the amount purchased from the pre-sale permitted for that user
}
else if (current_state == State.Day1)
{
raiseDay1 = safeAdd(raiseDay1, usdCentsRaise); //add current raise to pre-sell amount
require(raiseDay1 < (capDay1 - raisePreSale)); //ensure day 1 cap, which is lower by the amount we pre-sold
}
else if (current_state == State.Day2)
{
raiseDay2 = safeAdd(raiseDay2, usdCentsRaise); //add current raise to pre-sell amount
require(raiseDay2 < capDay2); //ensure day 2 cap
}
else if (current_state == State.Day3)
{
raiseDay3 = safeAdd(raiseDay3, usdCentsRaise); //add current raise to pre-sell amount
require(raiseDay3 < capDay3); //ensure day 3 cap
}
else revert();
uint tokens = safeDiv(msg.value, getTokenPriceInWEI()); // Calculate number of tokens to be paid out
uint bonus = safeDiv(safeMul(tokens, getCurrentBonusInPercent()), 100); // Calculate number of bonus tokens
if (current_state == State.PreSale) {
// Remove the extra 5% from the totalTokensCompany, in order to keep the 550m on track.
totalTokensCompany = safeSub(totalTokensCompany, safeDiv(bonus, 4));
}
uint totalTokens = safeAdd(tokens, bonus);
balances[recipient] = safeAdd(balances[recipient], totalTokens);
totalSupply = safeAdd(totalSupply, totalTokens);
deposit.transfer(msg.value); // Send deposited Ether to the deposit address on file.
Buy(recipient, msg.value, totalTokens);
}
/*
Allocate reserved and founders tokens based on the running time and state of the contract.
*/
function allocateReserveAndFounderTokens() {
require(msg.sender==founder);
require(getCurrentState() == State.Running);
uint tokens = 0;
if(block.timestamp > saleEnd && !allocatedFounders)
{
allocatedFounders = true;
tokens = totalTokensCompany;
balances[founder] = safeAdd(balances[founder], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > year1Unlock && !allocated1Year)
{
allocated1Year = true;
tokens = safeDiv(totalTokensReserve, 4);
balances[founder] = safeAdd(balances[founder], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > year2Unlock && !allocated2Year)
{
allocated2Year = true;
tokens = safeDiv(totalTokensReserve, 4);
balances[founder] = safeAdd(balances[founder], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > year3Unlock && !allocated3Year)
{
allocated3Year = true;
tokens = safeDiv(totalTokensReserve, 4);
balances[founder] = safeAdd(balances[founder], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > year4Unlock && !allocated4Year)
{
allocated4Year = true;
tokens = safeDiv(totalTokensReserve, 4);
balances[founder] = safeAdd(balances[founder], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else revert();
AllocateTokens(msg.sender);
}
/**
* Emergency Stop ICO.
*
* Applicable tests:
*
* - Test unhalting, buying, and succeeding
*/
function halt() {
require(msg.sender==founder);
halted = true;
}
function unhalt() {
require(msg.sender==founder);
halted = false;
}
/*
Change founder address (Controlling address for contract)
*/
function changeFounder(address newFounder) {
require(msg.sender==founder);
founder = newFounder;
}
/*
Change deposit address (Address to which funds are deposited)
*/
function changeDeposit(address newDeposit) {
require(msg.sender==founder);
deposit = newDeposit;
}
/*
Add people to the pre-sale whitelist
Amount should be the value in USD that the purchaser is allowed to buy
IE: 100 is $100 is 10000 cents. The correct value to enter is 100
*/
function addPresaleWhitelist(address toWhitelist, uint256 amount){
require(msg.sender==founder && amount > 0);
presaleWhitelist[toWhitelist] = amount * 100;
}
/**
* ERC 20 Standard Token interface transfer function
*
* Prevent transfers until freeze period is over.
*
* Applicable tests:
*
* - Test restricted early transfer
* - Test transfer after restricted period
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(block.timestamp > coinTradeStart);
return super.transfer(_to, _value);
}
/**
* ERC 20 Standard Token interface transfer function
*
* Prevent transfers until freeze period is over.
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(block.timestamp > coinTradeStart);
return super.transferFrom(_from, _to, _value);
}
function() payable {
buyRecipient(msg.sender);
}
} | USD raised during days 3-10
| uint public raiseDay3 = 0; | 1,809,755 | [
1,
3378,
40,
11531,
4982,
4681,
890,
17,
2163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1071,
1002,
4245,
23,
273,
374,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
}
contract ERC20Events {
event Approval(address indexed from, address indexed to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint value) public returns (bool);
function transfer(address dst, uint value) public returns (bool);
function transferFrom(
address src, address dst, uint value
) public returns (bool);
}
contract DCUCoin is ERC20, DSMath, DSStop {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 internal supply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) approvals;
constructor(uint256 token_supply, string token_name, string token_symbol) public {
balances[msg.sender] = token_supply;
supply = token_supply;
name = token_name;
symbol = token_symbol;
}
function() public payable {
revert();
}
function setName(string token_name) auth public {
name = token_name;
}
function totalSupply() constant public returns (uint256) {
return supply;
}
function balanceOf(address src) public view returns (uint) {
return balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return approvals[src][guy];
}
function transfer(address dst, uint value) public stoppable returns (bool) {
// uint never less than 0. The negative number will become to a big positive number
require(value < supply);
require(balances[msg.sender] >= value);
balances[msg.sender] = sub(balances[msg.sender], value);
balances[dst] = add(balances[dst], value);
emit Transfer(msg.sender, dst, value);
return true;
}
function transferFrom(address src, address dst, uint value) public stoppable returns (bool)
{
// uint never less than 0. The negative number will become to a big positive number
require(value < supply);
require(approvals[src][msg.sender] >= value);
require(balances[src] >= value);
approvals[src][msg.sender] = sub(approvals[src][msg.sender], value);
balances[src] = sub(balances[src], value);
balances[dst] = add(balances[dst], value);
emit Transfer(src, dst, value);
return true;
}
function approve(address guy, uint value) public stoppable returns (bool) {
// uint never less than 0. The negative number will become to a big positive number
require(value < supply);
approvals[msg.sender][guy] = value;
emit Approval(msg.sender, guy, value);
return true;
}
} | uint never less than 0. The negative number will become to a big positive number | function approve(address guy, uint value) public stoppable returns (bool) {
require(value < supply);
approvals[msg.sender][guy] = value;
emit Approval(msg.sender, guy, value);
return true;
}
| 7,847,244 | [
1,
11890,
5903,
5242,
2353,
374,
18,
1021,
6092,
1300,
903,
12561,
358,
279,
5446,
6895,
1300,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6617,
537,
12,
2867,
3058,
93,
16,
2254,
460,
13,
1071,
2132,
19586,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
1132,
411,
14467,
1769,
203,
203,
3639,
6617,
4524,
63,
3576,
18,
15330,
6362,
6891,
93,
65,
273,
460,
31,
203,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
3058,
93,
16,
460,
1769,
203,
203,
3639,
327,
638,
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
] |
./partial_match/1/0xc8024fB5C7beD98CcE0e498E54B7D89816B3521B/sources/GenesisLiquidityPool.sol | @dev Apply the change in the GEX oracle address proposed using the requestAddressChange() function. This function can only be called 30 days after the request of the change. | function applyOracleChange() external onlyOwner {
changeRequests[address(oracleGeminon)].changeRequested = false;
oracleGeminon = IGeminonOracle(changeRequests[address(oracleGeminon)].newAddressRequested);
oracleAge = uint64(block.timestamp);
}
| 3,668,724 | [
1,
7001,
326,
2549,
316,
326,
611,
2294,
20865,
1758,
20084,
1450,
326,
590,
1887,
3043,
1435,
445,
18,
1220,
445,
848,
1338,
506,
2566,
5196,
4681,
1839,
326,
590,
434,
326,
2549,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
2230,
23601,
3043,
1435,
3903,
1338,
5541,
288,
203,
203,
3639,
2549,
6421,
63,
2867,
12,
280,
16066,
43,
351,
267,
265,
13,
8009,
3427,
11244,
273,
629,
31,
203,
3639,
20865,
43,
351,
267,
265,
273,
13102,
351,
267,
265,
23601,
12,
3427,
6421,
63,
2867,
12,
280,
16066,
43,
351,
267,
265,
13,
8009,
2704,
1887,
11244,
1769,
203,
3639,
20865,
9692,
273,
2254,
1105,
12,
2629,
18,
5508,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./interfaces/IGatewayTokenController.sol";
import "./interfaces/IFlagsStorage.sol";
import "./library/BitMask.sol";
/**
* @dev FlagsStorage is the main contract to store KYC-related flags for Gateway Token System.
* KYC flags are identifiable by short identifiers in bytes32 strings. After adding flags
* those bit indexes could be used by GatewayToken implementations to associate flags per token.
*/
contract FlagsStorage is IFlagsStorage {
using EnumerableSet for EnumerableSet.Bytes32Set;
using Address for address;
using BitMask for uint256;
EnumerableSet.Bytes32Set private supportedFlags;
address public override daoController;
uint256 public override supportedFlagsMask;
uint256 public override unsupportedFlagsMask;
mapping(bytes32 => uint8) public override flagIndexes;
// @dev Modifier to prevent calls from anyone except Identity.com Admin
modifier onlyDAOController() {
require(msg.sender == daoController, "NOT DAO ADDRESS");
_;
}
constructor(address _daoController) public {
// require(_daoController.isContract(), "DAO CONTROLLER IS NOT A CONTRACT");
daoController = _daoController;
}
/**
* @dev Triggers to transfer ownership of this contract to new DAO Controller, reverts on zero address and wallet addresses
* @param _newDAOController New DAO Controller contract address
* @notice Only executed by existing DAO Manager
*/
function updateDAOManager(address _newDAOController) onlyDAOController public override {
require(_newDAOController != address(0), "NEW DAO CONTROLLER IS ZERO ADDRESS");
require(_newDAOController.isContract(), "NEW DAO CONTROLLER IS NOT A CONTRACT");
emit DAOControllerUpdated(daoController, _newDAOController);
daoController = _newDAOController;
}
/**
* @dev Triggers to add new flag into gateway token system
* @param _flag Flag short identifier
* @param _index Flag index (limited to 255)
* @notice Only executed by existing DAO Manager
*/
function addFlag(bytes32 _flag, uint8 _index) onlyDAOController public override {
_addFlag(_flag, _index);
}
/**
* @dev Triggers to add multiple flags into gateway token system
* @param _flags Array of flag short identifiers
* @param _indexes Array of flag indexes (limited to 255)
* @notice Only executed by existing DAO Manager
*/
function addFlags(bytes32[] memory _flags, uint8[] memory _indexes) onlyDAOController public override {
require(_flags.length == _indexes.length, "Incorect variables length");
for (uint8 i = 0; i < _flags.length; i++) {
_addFlag(_flags[i], _indexes[i]);
}
}
/**
* @dev Triggers to remove existing flag from gateway token system
* @param _flag Flag short identifier
* @notice Only executed by existing DAO Manager
*/
function removeFlag(bytes32 _flag) onlyDAOController public override {
require(supportedFlags.contains(_flag), "Flag not supported"); // additional check to reduce incorrect FlagRemoved event
_removeFlag(_flag);
}
/**
* @dev Triggers to remove multiple existing flags from gateway token system
* @param _flags Array of flag short identifiers
* @notice Only executed by existing DAO Manager
*/
function removeFlags(bytes32[] memory _flags) onlyDAOController public override {
for (uint8 i = 0; i < _flags.length; i++) {
require(supportedFlags.contains(_flags[i]), "Flag not supported"); // additional check to reduce incorrect FlagRemoved events
_removeFlag(_flags[i]);
}
}
/**
* @dev Triggers to check if a particular flag is supported
* @param _flag Flag short identifier
* @return Boolean for flag support
*/
function isFlagSupported(bytes32 _flag) public view override returns (bool) {
return supportedFlags.contains(_flag);
}
/**
* @dev Triggers to check if several flags are supported
* @param _flags Array of flags
* @return Array of booleans with support per flag
*/
function isFlagsSupported(bytes32[] memory _flags) public view override returns (bool[] memory) {
uint len = _flags.length;
bool[] memory result = new bool[](len);
for (uint8 i = 0; i < _flags.length; i++) {
result[i] = supportedFlags.contains(_flags[i]);
}
return result;
}
/**
* @dev Internal function to add new flag
*/
function _addFlag(bytes32 _flag, uint8 _index) internal {
require(!supportedFlagsMask.checkBit(_index), "Index already used");
require(!supportedFlags.contains(_flag), "Flag already exist");
if (unsupportedFlagsMask.checkBit(_index)) {
unsupportedFlagsMask = unsupportedFlagsMask.clearBit(_index);
}
flagIndexes[_flag] = _index;
supportedFlags.add(_flag);
supportedFlagsMask = supportedFlagsMask.setBit(_index);
emit FlagAdded(_flag, _index);
}
/**
* @dev Internal function to remove existing flag
*/
function _removeFlag(bytes32 _flag) internal {
supportedFlags.remove(_flag);
uint8 _index = flagIndexes[_flag];
supportedFlagsMask = supportedFlagsMask.clearBit(_index);
unsupportedFlagsMask = unsupportedFlagsMask.setBit(_index);
delete flagIndexes[_flag];
emit FlagRemoved(_flag);
}
} | * @dev Triggers to transfer ownership of this contract to new DAO Controller, reverts on zero address and wallet addresses @param _newDAOController New DAO Controller contract address @notice Only executed by existing DAO Manager/ | function updateDAOManager(address _newDAOController) onlyDAOController public override {
require(_newDAOController != address(0), "NEW DAO CONTROLLER IS ZERO ADDRESS");
require(_newDAOController.isContract(), "NEW DAO CONTROLLER IS NOT A CONTRACT");
emit DAOControllerUpdated(daoController, _newDAOController);
daoController = _newDAOController;
}
| 6,458,344 | [
1,
15114,
358,
7412,
23178,
434,
333,
6835,
358,
394,
463,
20463,
6629,
16,
15226,
87,
603,
3634,
1758,
471,
9230,
6138,
225,
389,
2704,
18485,
2933,
1166,
463,
20463,
6629,
6835,
1758,
225,
5098,
7120,
635,
2062,
463,
20463,
8558,
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,
565,
445,
1089,
18485,
1318,
12,
2867,
389,
2704,
18485,
2933,
13,
1338,
18485,
2933,
1071,
3849,
288,
203,
3639,
2583,
24899,
2704,
18485,
2933,
480,
1758,
12,
20,
3631,
315,
12917,
463,
20463,
8020,
25353,
4437,
18449,
11689,
10203,
8863,
203,
3639,
2583,
24899,
2704,
18485,
2933,
18,
291,
8924,
9334,
315,
12917,
463,
20463,
8020,
25353,
4437,
4269,
432,
8020,
2849,
1268,
8863,
203,
203,
3639,
3626,
463,
20463,
2933,
7381,
12,
2414,
83,
2933,
16,
389,
2704,
18485,
2933,
1769,
203,
3639,
15229,
2933,
273,
389,
2704,
18485,
2933,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-31
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.5.12;
contract GemLike {
function allowance(address, address) public returns (uint);
function approve(address, uint) public;
function transfer(address, uint) public returns (bool);
function transferFrom(address, address, uint) public returns (bool);
}
contract ValueLike {
function peek() public returns (uint, bool);
}
contract SaiTubLike {
function skr() public view returns (GemLike);
function gem() public view returns (GemLike);
function gov() public view returns (GemLike);
function sai() public view returns (GemLike);
function pep() public view returns (ValueLike);
function vox() public view returns (VoxLike);
function bid(uint) public view returns (uint);
function ink(bytes32) public view returns (uint);
function tag() public view returns (uint);
function tab(bytes32) public returns (uint);
function rap(bytes32) public returns (uint);
function draw(bytes32, uint) public;
function shut(bytes32) public;
function exit(uint) public;
function give(bytes32, address) public;
}
contract VoxLike {
function par() public returns (uint);
}
contract JoinLike {
function ilk() public returns (bytes32);
function gem() public returns (GemLike);
function dai() public returns (GemLike);
function join(address, uint) public;
function exit(address, uint) public;
}
contract VatLike {
function ilks(bytes32) public view returns (uint, uint, uint, uint, uint);
function hope(address) public;
function frob(bytes32, address, address, address, int, int) public;
}
contract ManagerLike {
function vat() public view returns (address);
function urns(uint) public view returns (address);
function open(bytes32, address) public returns (uint);
function frob(uint, int, int) public;
function give(uint, address) public;
function move(uint, address, uint) public;
}
contract OtcLike {
function getPayAmount(address, address, uint) public view returns (uint);
function buyAllAmount(address, uint, address, uint) public;
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
contract ICErc20 {
address public underlying;
function mint(uint256 mintAmount) external returns (uint);
function redeemUnderlying(uint256 redeemAmount) external returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getCash() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @author Brendan Asselstine
* @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias.
* @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94
*/
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
require(_upperBound > 0, "UniformRand/min-bound");
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
/**
* @reviewers: [@clesaege, @unknownunknown1, @ferittuncer]
* @auditors: []
* @bounties: [<14 days 10 ETH max payout>]
* @deployments: []
*/
/**
* @title SortitionSumTreeFactory
* @author Enrique Piqueras - <[email protected]>
* @dev A factory of trees that keep track of staked values for sortition.
*/
library SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint K; // The maximum number of childs per node.
// We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around.
uint[] stack;
uint[] nodes;
// Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node.
mapping(bytes32 => uint) IDsToNodeIndexes;
mapping(uint => bytes32) nodeIndexesToIDs;
}
/* Storage */
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
/* internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack.length = 0;
tree.nodes.length = 0;
tree.nodes.push(0);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _ID The ID of the value.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) { // No existing node.
if (_value != 0) { // Non zero value.
// Append.
// Add node.
if (tree.stack.length == 0) { // No vacant spots.
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
uint parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.length--;
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else { // Existing node.
if (_value == 0) { // Zero value.
// Remove.
// Remember value and set to 0.
uint value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (_value != tree.nodes[treeIndex]) { // New, non zero value.
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue);
}
}
}
/* internal Views */
/**
* @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned.
* @param _key The key of the tree to get the leaves from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination.
* `O(n)` where
* `n` is the maximum number of nodes ever appended.
*/
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
) internal view returns(uint startIndex, uint[] memory values, bool hasMore) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.nodes.length; i++) {
if ((tree.K * i) + 1 >= tree.nodes.length) {
startIndex = i;
break;
}
}
// Get the values.
uint loopStartIndex = startIndex + _cursor;
values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count);
uint valuesIndex = 0;
for (uint j = loopStartIndex; j < tree.nodes.length; j++) {
if (valuesIndex < _count) {
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return The drawn ID.
* `O(k * log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = 0;
uint currentDrawnNumber = _drawnNumber % tree.nodes[0];
while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint nodeIndex = (tree.K * treeIndex) + i;
uint nodeValue = tree.nodes[nodeIndex];
if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child.
else { // Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
/** @dev Gets a specified ID's associated value.
* @param _key The key of the tree.
* @param _ID The ID of the value.
* @return The associated value.
*/
function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) value = 0;
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (tree.nodes.length == 0) {
return 0;
} else {
return tree.nodes[0];
}
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value;
}
}
}
/**
* @author Brendan Asselstine
* @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances.
*
* Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw.
* When a new draw is opened, the previous opened draw is committed.
*
* The committed balance for an address is the total of their balances for committed Draws.
* An address's open balance is their balance in the open Draw.
*/
library DrawManager {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
using SafeMath for uint256;
/**
* The ID to use for the selection tree.
*/
bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws";
uint8 public constant MAX_BRANCHES_PER_NODE = 10;
/**
* Stores information for all draws.
*/
struct State {
/**
* Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index.
* There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS.
*/
SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees;
/**
* Stores the consolidated draw index that an address deposited to.
*/
mapping(address => uint256) consolidatedDrawIndices;
/**
* Stores the last Draw index that an address deposited to.
*/
mapping(address => uint256) latestDrawIndices;
/**
* Stores a mapping of Draw index => Draw total
*/
mapping(uint256 => uint256) __deprecated__drawTotals;
/**
* The current open Draw index
*/
uint256 openDrawIndex;
/**
* The total of committed balances
*/
uint256 __deprecated__committedSupply;
}
/**
* @notice Opens the next Draw and commits the previous open Draw (if any).
* @param self The drawState this library is attached to
* @return The index of the new open Draw
*/
function openNextDraw(State storage self) public returns (uint256) {
if (self.openDrawIndex == 0) {
// If there is no previous draw, we must initialize
self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE);
} else {
// else add current draw to sortition sum trees
bytes32 drawId = bytes32(self.openDrawIndex);
uint256 drawTotal = openSupply(self);
self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId);
}
// now create a new draw
uint256 drawIndex = self.openDrawIndex.add(1);
self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE);
self.openDrawIndex = drawIndex;
return drawIndex;
}
/**
* @notice Deposits the given amount into the current open draw by the given user.
* @param self The DrawManager state
* @param _addr The address to deposit for
* @param _amount The amount to deposit
*/
function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openDrawIndex = self.openDrawIndex;
// update the current draw
uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId);
currentAmount = currentAmount.add(_amount);
drawSet(self, openDrawIndex, currentAmount, _addr);
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
// if this is the user's first draw, set it
if (consolidatedDrawIndex == 0) {
self.consolidatedDrawIndices[_addr] = openDrawIndex;
// otherwise, if the consolidated draw is not this draw
} else if (consolidatedDrawIndex != openDrawIndex) {
// if a second draw does not exist
if (latestDrawIndex == 0) {
// set the second draw to the current draw
self.latestDrawIndices[_addr] = openDrawIndex;
// otherwise if a second draw exists but is not the current one
} else if (latestDrawIndex != openDrawIndex) {
// merge it into the first draw, and update the second draw index to this one
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr);
drawSet(self, latestDrawIndex, 0, _addr);
self.latestDrawIndices[_addr] = openDrawIndex;
}
}
}
/**
* @notice Deposits into a user's committed balance, thereby bypassing the open draw.
* @param self The DrawManager state
* @param _addr The address of the user for whom to deposit
* @param _amount The amount to deposit
*/
function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
// if they have a committed balance
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr);
} else { // they must not have any committed balance
self.latestDrawIndices[_addr] = consolidatedDrawIndex;
self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1);
drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr);
}
}
/**
* @notice Withdraws a user's committed and open draws.
* @param self The DrawManager state
* @param _addr The address whose balance to withdraw
*/
function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) {
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0) {
drawSet(self, consolidatedDrawIndex, 0, _addr);
delete self.consolidatedDrawIndices[_addr];
}
if (latestDrawIndex != 0) {
drawSet(self, latestDrawIndex, 0, _addr);
delete self.latestDrawIndices[_addr];
}
}
/**
* @notice Withdraw's from a user's open balance
* @param self The DrawManager state
* @param _addr The user to withdrawn from
* @param _amount The amount to withdraw
*/
function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId);
require(_amount <= openTotal, "DrawMan/exceeds-open");
uint256 remaining = openTotal.sub(_amount);
drawSet(self, self.openDrawIndex, remaining, _addr);
}
/**
* @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available.
* @param self The DrawManager state
* @param _addr The user to withdraw from
* @param _amount The amount to withdraw.
*/
function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
uint256 consolidatedAmount = 0;
uint256 latestAmount = 0;
uint256 total = 0;
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
total = total.add(latestAmount);
}
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
total = total.add(consolidatedAmount);
}
// If the total is greater than zero, then consolidated *must* have the committed balance
// However, if the total is zero then the consolidated balance may be the open balance
if (total == 0) {
return;
}
require(_amount <= total, "Pool/exceed");
uint256 remaining = total.sub(_amount);
// if there was a second amount that needs to be updated
if (remaining > consolidatedAmount) {
uint256 secondRemaining = remaining.sub(consolidatedAmount);
drawSet(self, latestDrawIndex, secondRemaining, _addr);
} else if (latestAmount > 0) { // else delete the second amount if it exists
delete self.latestDrawIndices[_addr];
drawSet(self, latestDrawIndex, 0, _addr);
}
// if the consolidated amount needs to be destroyed
if (remaining == 0) {
delete self.consolidatedDrawIndices[_addr];
drawSet(self, consolidatedDrawIndex, 0, _addr);
} else if (remaining < consolidatedAmount) {
drawSet(self, consolidatedDrawIndex, remaining, _addr);
}
}
/**
* @notice Returns the total balance for an address, including committed balances and the open balance.
*/
function balanceOf(State storage drawState, address _addr) public view returns (uint256) {
return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr));
}
/**
* @notice Returns the total committed balance for an address.
* @param self The DrawManager state
* @param _addr The address whose committed balance should be returned
* @return The total committed balance
*/
function committedBalanceOf(State storage self, address _addr) public view returns (uint256) {
uint256 balance = 0;
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr)));
}
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr))));
}
return balance;
}
/**
* @notice Returns the open balance for an address
* @param self The DrawManager state
* @param _addr The address whose open balance should be returned
* @return The open balance
*/
function openBalanceOf(State storage self, address _addr) public view returns (uint256) {
if (self.openDrawIndex == 0) {
return 0;
} else {
return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr)));
}
}
/**
* @notice Returns the open Draw balance for the DrawManager
* @param self The DrawManager state
* @return The open draw total balance
*/
function openSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(bytes32(self.openDrawIndex));
}
/**
* @notice Returns the committed balance for the DrawManager
* @param self The DrawManager state
* @return The total committed balance
*/
function committedSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(TREE_OF_DRAWS);
}
/**
* @notice Updates the Draw balance for an address.
* @param self The DrawManager state
* @param _drawIndex The Draw index
* @param _amount The new balance
* @param _addr The address whose balance should be updated
*/
function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal {
bytes32 drawId = bytes32(_drawIndex);
bytes32 userId = bytes32(uint256(_addr));
uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId);
if (oldAmount != _amount) {
// If the amount has changed
// Update the Draw's balance for that address
self.sortitionSumTrees.set(drawId, _amount, userId);
// if the draw is committed
if (_drawIndex != self.openDrawIndex) {
// Get the new draw total
uint256 newDrawTotal = self.sortitionSumTrees.total(drawId);
// update the draw in the committed tree
self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId);
}
}
}
/**
* @notice Selects an address by indexing into the committed tokens using the passed token.
* If there is no committed supply, the zero address is returned.
* @param self The DrawManager state
* @param _token The token index to select
* @return The selected address
*/
function draw(State storage self, uint256 _token) public view returns (address) {
// If there is no one to select, just return the zero address
if (committedSupply(self) == 0) {
return address(0);
}
require(_token < committedSupply(self), "Pool/ineligible");
bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token);
uint256 drawSupply = self.sortitionSumTrees.total(drawIndex);
uint256 drawToken = _token % drawSupply;
return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken)));
}
/**
* @notice Selects an address using the entropy as an index into the committed tokens
* The entropy is passed into the UniformRandomNumber library to remove modulo bias.
* @param self The DrawManager state
* @param _entropy The random entropy to use
* @return The selected address
*/
function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) {
uint256 bound = committedSupply(self);
address selected;
if (bound == 0) {
selected = address(0);
} else {
selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound));
}
return selected;
}
modifier requireOpenDraw(State storage self) {
require(self.openDrawIndex > 0, "Pool/no-open");
_;
}
modifier requireCommittedDraw(State storage self) {
require(self.openDrawIndex > 1, "Pool/no-commit");
_;
}
modifier onlyNonZero(address _addr) {
require(_addr != address(0), "Pool/not-zero");
_;
}
}
/**
* @title FixidityLib
* @author Gadi Guy, Alberto Cuesta Canada
* @notice This library provides fixed point arithmetic with protection against
* overflow.
* All operations are done with int256 and the operands must have been created
* with any of the newFrom* functions, which shift the comma digits() to the
* right and check for limits.
* When using this library be sure of using maxNewFixed() as the upper limit for
* creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and
* maxFixedAdd() if you want to be certain that those operations don't
* overflow.
*/
library FixidityLib {
/**
* @notice Number of positions that the comma is shifted to the right.
*/
function digits() public pure returns(uint8) {
return 24;
}
/**
* @notice This is 1 in the fixed point units used in this library.
* @dev Test fixed1() equals 10^digits()
* Hardcoded to 24 digits.
*/
function fixed1() public pure returns(int256) {
return 1000000000000000000000000;
}
/**
* @notice The amount of decimals lost on each multiplication operand.
* @dev Test mulPrecision() equals sqrt(fixed1)
* Hardcoded to 24 digits.
*/
function mulPrecision() public pure returns(int256) {
return 1000000000000;
}
/**
* @notice Maximum value that can be represented in an int256
* @dev Test maxInt256() equals 2^255 -1
*/
function maxInt256() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282019728792003956564819967;
}
/**
* @notice Minimum value that can be represented in an int256
* @dev Test minInt256 equals (2^255) * (-1)
*/
function minInt256() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282019728792003956564819968;
}
/**
* @notice Maximum value that can be converted to fixed point. Optimize for
* @dev deployment.
* Test maxNewFixed() equals maxInt256() / fixed1()
* Hardcoded to 24 digits.
*/
function maxNewFixed() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Minimum value that can be converted to fixed point. Optimize for
* deployment.
* @dev Test minNewFixed() equals -(maxInt256()) / fixed1()
* Hardcoded to 24 digits.
*/
function minNewFixed() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as an addition operator.
* @dev Test maxFixedAdd() equals maxInt256()-1 / 2
* Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd()
* Test add(maxFixedAdd()+1,maxFixedAdd()) throws
* Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd()
* Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws
*/
function maxFixedAdd() public pure returns(int256) {
return 28948022309329048855892746252171976963317496166410141009864396001978282409983;
}
/**
* @notice Maximum negative value that can be safely in a subtraction.
* @dev Test maxFixedSub() equals minInt256() / 2
*/
function maxFixedSub() public pure returns(int256) {
return -28948022309329048855892746252171976963317496166410141009864396001978282409984;
}
/**
* @notice Maximum value that can be safely used as a multiplication operator.
* @dev Calculated as sqrt(maxInt256()*fixed1()).
* Be careful with your sqrt() implementation. I couldn't find a calculator
* that would give the exact square root of maxInt256*fixed1 so this number
* is below the real number by no more than 3*10**28. It is safe to use as
* a limit for your multiplications, although powers of two of numbers over
* this value might still work.
* Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul()
* Test multiply(maxFixedMul(),maxFixedMul()+1) throws
* Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul()
* Test multiply(-maxFixedMul(),maxFixedMul()+1) throws
* Hardcoded to 24 digits.
*/
function maxFixedMul() public pure returns(int256) {
return 240615969168004498257251713877715648331380787511296;
}
/**
* @notice Maximum value that can be safely used as a dividend.
* @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256().
* Test maxFixedDiv() equals maxInt256()/fixed1()
* Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws
* Hardcoded to 24 digits.
*/
function maxFixedDiv() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as a divisor.
* @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2)
* Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1()
* Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws
* Hardcoded to 24 digits.
*/
function maxFixedDivisor() public pure returns(int256) {
return 1000000000000000000000000000000000000000000000000;
}
/**
* @notice Converts an int256 to fixed point units, equivalent to multiplying
* by 10^digits().
* @dev Test newFixed(0) returns 0
* Test newFixed(1) returns fixed1()
* Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1()
* Test newFixed(maxNewFixed()+1) fails
*/
function newFixed(int256 x)
public
pure
returns (int256)
{
require(x <= maxNewFixed());
require(x >= minNewFixed());
return x * fixed1();
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a non decimal. All decimal digits will be truncated.
*/
function fromFixed(int256 x)
public
pure
returns (int256)
{
return x / fixed1();
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to a different fixed precision representation.
* Both the origin and destination precisions must be 38 or less digits.
* Origin values with a precision higher than the destination precision
* will be truncated accordingly.
* @dev
* Test convertFixed(1,0,0) returns 1;
* Test convertFixed(1,1,1) returns 1;
* Test convertFixed(1,1,0) returns 0;
* Test convertFixed(1,0,1) returns 10;
* Test convertFixed(10,1,0) returns 1;
* Test convertFixed(10,0,1) returns 100;
* Test convertFixed(100,1,0) returns 10;
* Test convertFixed(100,0,1) returns 1000;
* Test convertFixed(1000,2,0) returns 10;
* Test convertFixed(1000,0,2) returns 100000;
* Test convertFixed(1000,2,1) returns 100;
* Test convertFixed(1000,1,2) returns 10000;
* Test convertFixed(maxInt256,1,0) returns maxInt256/10;
* Test convertFixed(maxInt256,0,1) throws
* Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38);
* Test convertFixed(1,0,38) returns 10**38;
* Test convertFixed(maxInt256,39,0) throws
* Test convertFixed(1,0,39) throws
*/
function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits)
public
pure
returns (int256)
{
require(_originDigits <= 38 && _destinationDigits <= 38);
uint8 decimalDifference;
if ( _originDigits > _destinationDigits ){
decimalDifference = _originDigits - _destinationDigits;
return x/(uint128(10)**uint128(decimalDifference));
}
else if ( _originDigits < _destinationDigits ){
decimalDifference = _destinationDigits - _originDigits;
// Cast uint8 -> uint128 is safe
// Exponentiation is safe:
// _originDigits and _destinationDigits limited to 38 or less
// decimalDifference = abs(_destinationDigits - _originDigits)
// decimalDifference < 38
// 10**38 < 2**128-1
require(x <= maxInt256()/uint128(10)**uint128(decimalDifference));
require(x >= minInt256()/uint128(10)**uint128(decimalDifference));
return x*(uint128(10)**uint128(decimalDifference));
}
// _originDigits == digits())
return x;
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to that of this library. The _originDigits parameter is the
* precision of x. Values with a precision higher than FixidityLib.digits()
* will be truncated accordingly.
*/
function newFixed(int256 x, uint8 _originDigits)
public
pure
returns (int256)
{
return convertFixed(x, _originDigits, digits());
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a different representation. The _destinationDigits parameter is the
* precision of the output x. Values with a precision below than
* FixidityLib.digits() will be truncated accordingly.
*/
function fromFixed(int256 x, uint8 _destinationDigits)
public
pure
returns (int256)
{
return convertFixed(x, digits(), _destinationDigits);
}
/**
* @notice Converts two int256 representing a fraction to fixed point units,
* equivalent to multiplying dividend and divisor by 10^digits().
* @dev
* Test newFixedFraction(maxFixedDiv()+1,1) fails
* Test newFixedFraction(1,maxFixedDiv()+1) fails
* Test newFixedFraction(1,0) fails
* Test newFixedFraction(0,1) returns 0
* Test newFixedFraction(1,1) returns fixed1()
* Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1()
* Test newFixedFraction(1,fixed1()) returns 1
* Test newFixedFraction(1,fixed1()-1) returns 0
*/
function newFixedFraction(
int256 numerator,
int256 denominator
)
public
pure
returns (int256)
{
require(numerator <= maxNewFixed());
require(denominator <= maxNewFixed());
require(denominator != 0);
int256 convertedNumerator = newFixed(numerator);
int256 convertedDenominator = newFixed(denominator);
return divide(convertedNumerator, convertedDenominator);
}
/**
* @notice Returns the integer part of a fixed point number.
* @dev
* Test integer(0) returns 0
* Test integer(fixed1()) returns fixed1()
* Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test integer(-fixed1()) returns -fixed1()
* Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1()
*/
function integer(int256 x) public pure returns (int256) {
return (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Returns the fractional part of a fixed point number.
* In the case of a negative number the fractional is also negative.
* @dev
* Test fractional(0) returns 0
* Test fractional(fixed1()) returns 0
* Test fractional(fixed1()-1) returns 10^24-1
* Test fractional(-fixed1()) returns 0
* Test fractional(-fixed1()+1) returns -10^24-1
*/
function fractional(int256 x) public pure returns (int256) {
return x - (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Converts to positive if negative.
* Due to int256 having one more negative number than positive numbers
* abs(minInt256) reverts.
* @dev
* Test abs(0) returns 0
* Test abs(fixed1()) returns -fixed1()
* Test abs(-fixed1()) returns fixed1()
* Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1()
*/
function abs(int256 x) public pure returns (int256) {
if (x >= 0) {
return x;
} else {
int256 result = -x;
assert (result > 0);
return result;
}
}
/**
* @notice x+y. If any operator is higher than maxFixedAdd() it
* might overflow.
* In solidity maxInt256 + 1 = minInt256 and viceversa.
* @dev
* Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails
* Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256()
* Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails
* Test add(maxInt256(),maxInt256()) fails
* Test add(minInt256(),minInt256()) fails
*/
function add(int256 x, int256 y) public pure returns (int256) {
int256 z = x + y;
if (x > 0 && y > 0) assert(z > x && z > y);
if (x < 0 && y < 0) assert(z < x && z < y);
return z;
}
/**
* @notice x-y. You can use add(x,-y) instead.
* @dev Tests covered by add(x,y)
*/
function subtract(int256 x, int256 y) public pure returns (int256) {
return add(x,-y);
}
/**
* @notice x*y. If any of the operators is higher than maxFixedMul() it
* might overflow.
* @dev
* Test multiply(0,0) returns 0
* Test multiply(maxFixedMul(),0) returns 0
* Test multiply(0,maxFixedMul()) returns 0
* Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul()
* Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul()
* Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5)
* Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision())
* Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1)
* Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits
* Test multiply(maxFixedMul()+1,maxFixedMul()) fails
* Test multiply(maxFixedMul(),maxFixedMul()+1) fails
*/
function multiply(int256 x, int256 y) public pure returns (int256) {
if (x == 0 || y == 0) return 0;
if (y == fixed1()) return x;
if (x == fixed1()) return y;
// Separate into integer and fractional parts
// x = x1 + x2, y = y1 + y2
int256 x1 = integer(x) / fixed1();
int256 x2 = fractional(x);
int256 y1 = integer(y) / fixed1();
int256 y2 = fractional(y);
// (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2)
int256 x1y1 = x1 * y1;
if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1
// x1y1 needs to be multiplied back by fixed1
// solium-disable-next-line mixedcase
int256 fixed_x1y1 = x1y1 * fixed1();
if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1
x1y1 = fixed_x1y1;
int256 x2y1 = x2 * y1;
if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1
int256 x1y2 = x1 * y2;
if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2
x2 = x2 / mulPrecision();
y2 = y2 / mulPrecision();
int256 x2y2 = x2 * y2;
if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2
// result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1();
int256 result = x1y1;
result = add(result, x2y1); // Add checks for overflow
result = add(result, x1y2); // Add checks for overflow
result = add(result, x2y2); // Add checks for overflow
return result;
}
/**
* @notice 1/x
* @dev
* Test reciprocal(0) fails
* Test reciprocal(fixed1()) returns fixed1()
* Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated
* Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated
*/
function reciprocal(int256 x) public pure returns (int256) {
require(x != 0);
return (fixed1()*fixed1()) / x; // Can't overflow
}
/**
* @notice x/y. If the dividend is higher than maxFixedDiv() it
* might overflow. You can use multiply(x,reciprocal(y)) instead.
* There is a loss of precision on division for the lower mulPrecision() decimals.
* @dev
* Test divide(fixed1(),0) fails
* Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,1) throws
* Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1()
*/
function divide(int256 x, int256 y) public pure returns (int256) {
if (y == fixed1()) return x;
require(y != 0);
require(y <= maxFixedDivisor());
return multiply(x, reciprocal(y));
}
}
/**
* @title Blocklock
* @author Brendan Asselstine
* @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually
* or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires.
*/
library Blocklock {
using SafeMath for uint256;
struct State {
uint256 lockedAt;
uint256 unlockedAt;
uint256 lockDuration;
uint256 cooldownDuration;
}
/**
* @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks.
* @param self The Blocklock state
* @param lockDuration The duration, in blocks, that the lock should last.
*/
function setLockDuration(State storage self, uint256 lockDuration) public {
require(lockDuration > 0, "Blocklock/lock-min");
self.lockDuration = lockDuration;
}
/**
* @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to
* lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually.
* @param self The Blocklock state
* @param cooldownDuration The duration of the cooldown, in blocks.
*/
function setCooldownDuration(State storage self, uint256 cooldownDuration) public {
require(cooldownDuration > 0, "Blocklock/cool-min");
self.cooldownDuration = cooldownDuration;
}
/**
* @notice Returns whether the state is locked at the given block number.
* @param self The Blocklock state
* @param blockNumber The current block number.
*/
function isLocked(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt != 0 &&
blockNumber >= self.lockedAt &&
blockNumber < endAt
);
}
/**
* @notice Locks the state at the given block number.
* @param self The Blocklock state
* @param blockNumber The block number to use as the lock start time
*/
function lock(State storage self, uint256 blockNumber) public {
require(canLock(self, blockNumber), "Blocklock/no-lock");
self.lockedAt = blockNumber;
}
/**
* @notice Manually unlocks the lock.
* @param self The Blocklock state
* @param blockNumber The block number at which the lock is being unlocked.
*/
function unlock(State storage self, uint256 blockNumber) public {
self.unlockedAt = blockNumber;
}
/**
* @notice Returns whether the Blocklock can be locked at the given block number
* @param self The Blocklock state
* @param blockNumber The block number to check against
* @return True if we can lock at the given block number, false otherwise.
*/
function canLock(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt == 0 ||
blockNumber >= endAt.add(self.cooldownDuration)
);
}
function cooldownEndAt(State storage self) internal view returns (uint256) {
return lockEndAt(self).add(self.cooldownDuration);
}
function lockEndAt(State storage self) internal view returns (uint256) {
uint256 endAt = self.lockedAt.add(self.lockDuration);
// if we unlocked early
if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) {
endAt = self.unlockedAt;
}
return endAt;
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destoys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @dev Implementation of the {IERC777} interface.
*
* Largely taken from the OpenZeppelin ERC777 contract.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*
* It is important to note that no Mint events are emitted. Tokens are minted in batches
* by a state change in a tree data structure, so emitting a Mint event for each user
* is not possible.
*
*/
contract PoolToken is Initializable, IERC20, IERC777 {
using SafeMath for uint256;
using Address for address;
/**
* Event emitted when a user or operator redeems tokens
*/
event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// keccak256("ERC777Token")
bytes32 constant internal TOKENS_INTERFACE_HASH =
0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054;
// keccak256("ERC20Token")
bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH =
0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a;
string internal _name;
string internal _symbol;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] internal _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) internal _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) internal _operators;
mapping(address => mapping(address => bool)) internal _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) internal _allowances;
// The Pool that is bound to this token
BasePool internal _pool;
/**
* @notice Initializes the PoolToken.
* @param name The name of the token
* @param symbol The token symbol
* @param defaultOperators The default operators who are allowed to move tokens
*/
function init (
string memory name,
string memory symbol,
address[] memory defaultOperators,
BasePool pool
) public initializer {
require(bytes(name).length != 0, "PoolToken/name");
require(bytes(symbol).length != 0, "PoolToken/symbol");
require(address(pool) != address(0), "PoolToken/pool-zero");
_name = name;
_symbol = symbol;
_pool = pool;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this));
}
/**
* @notice Returns the address of the Pool contract
* @return The address of the pool contract
*/
function pool() public view returns (BasePool) {
return _pool;
}
/**
* @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract.
* @param from The address from which to redeem tokens
* @param amount The amount of tokens to redeem
*/
function poolRedeem(address from, uint256 amount) external onlyPool {
_callTokensToSend(from, from, address(0), amount, '', '');
emit Redeemed(from, from, amount, '', '');
emit Transfer(from, address(0), amount);
}
/**
* @dev See {IERC777-name}.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20Detailed-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public view returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _pool.committedSupply();
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address _addr) external view returns (uint256) {
return _pool.committedBalanceOf(_addr);
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(msg.sender, msg.sender, recipient, amount, data, "");
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/transfer-zero");
address from = msg.sender;
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev Allows a user to withdraw their tokens as the underlying asset.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function redeem(uint256 amount, bytes calldata data) external {
_redeem(msg.sender, msg.sender, amount, data, "");
}
/**
* @dev See {IERC777-burn}. Not currently implemented.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external {
require(msg.sender != operator, "PoolToken/auth-self");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[msg.sender][operator];
} else {
_operators[msg.sender][operator] = true;
}
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external {
require(operator != msg.sender, "PoolToken/revoke-self");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[msg.sender][operator] = true;
} else {
delete _operators[msg.sender][operator];
}
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
)
external
{
require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator");
_send(msg.sender, sender, recipient, amount, data, operatorData);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Currently not supported
*/
function operatorBurn(address, uint256, bytes calldata, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user.
*
* Emits {Redeemed} and {Transfer} events.
*/
function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(msg.sender, account), "PoolToken/not-operator");
_redeem(msg.sender, account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external returns (bool) {
address holder = msg.sender;
_approve(holder, spender, value);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "PoolToken/negative"));
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/to-zero");
require(holder != address(0), "PoolToken/from-zero");
address spender = msg.sender;
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* Called by the associated Pool to emit `Mint` events.
* @param amount The amount that was minted
*/
function poolMint(uint256 amount) external onlyPool {
_mintEvents(address(_pool), address(_pool), amount, '', '');
}
/**
* Emits {Minted} and {IERC20-Transfer} events.
*/
function _mintEvents(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
require(to != address(0), "PoolToken/to-zero");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, false);
}
/**
* @dev Redeems tokens for the underlying asset.
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to redeem
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _redeem(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_pool.withdrawCommittedDepositFrom(from, amount);
emit Redeemed(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
/**
* @notice Moves tokens from one user to another. Emits Sent and Transfer events.
*/
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_pool.moveCommitted(from, to, amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* Approves of a token spend by a spender for a holder.
* @param holder The address from which the tokens are spent
* @param spender The address that is spending the tokens
* @param value The amount of tokens to spend
*/
function _approve(address holder, address spender, uint256 value) private {
require(spender != address(0), "PoolToken/from-zero");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal notLocked
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "PoolToken/no-recip-inter");
}
}
/**
* @notice Requires the sender to be the pool contract
*/
modifier onlyPool() {
require(msg.sender == address(_pool), "PoolToken/only-pool");
_;
}
/**
* @notice Requires the contract to be unlocked
*/
modifier notLocked() {
require(!_pool.isLocked(), "PoolToken/is-locked");
_;
}
}
/**
* @title The Pool contract
* @author Brendan Asselstine
* @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws.
* Funds are immediately deposited and withdrawn from the Compound cToken contract.
* Draws go through three stages: open, committed and rewarded in that order.
* Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance.
* When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated.
* When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being
* proportional to their committed balance vs the total committed balance of all users.
*
*
* With the above in mind, there is always an open draw and possibly a committed draw. The progression is:
*
* Step 1: Draw 1 Open
* Step 2: Draw 2 Open | Draw 1 Committed
* Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded
* Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded
* Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded
* Step X: ...
*/
contract BasePool is Initializable, ReentrancyGuard {
using DrawManager for DrawManager.State;
using SafeMath for uint256;
using Roles for Roles.Role;
using Blocklock for Blocklock.State;
bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1));
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("PoolTogetherRewardListener")
bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH =
0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4;
/**
* Emitted when a user deposits into the Pool.
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event Deposited(address indexed sender, uint256 amount);
/**
* Emitted when a user deposits into the Pool and the deposit is immediately committed
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event DepositedAndCommitted(address indexed sender, uint256 amount);
/**
* Emitted when Sponsors have deposited into the Pool
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event SponsorshipDeposited(address indexed sender, uint256 amount);
/**
* Emitted when an admin has been added to the Pool.
* @param admin The admin that was added
*/
event AdminAdded(address indexed admin);
/**
* Emitted when an admin has been removed from the Pool.
* @param admin The admin that was removed
*/
event AdminRemoved(address indexed admin);
/**
* Emitted when a user withdraws from the pool.
* @param sender The user that is withdrawing from the pool
* @param amount The amount that the user withdrew
*/
event Withdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws their sponsorship and fees from the pool.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their open deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event OpenDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their committed deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event CommittedDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when an address collects a fee
* @param sender The address collecting the fee
* @param amount The fee amount
* @param drawId The draw from which the fee was awarded
*/
event FeeCollected(address indexed sender, uint256 amount, uint256 drawId);
/**
* Emitted when a new draw is opened for deposit.
* @param drawId The draw id
* @param feeBeneficiary The fee beneficiary for this draw
* @param secretHash The committed secret hash
* @param feeFraction The fee fraction of the winnings to be given to the beneficiary
*/
event Opened(
uint256 indexed drawId,
address indexed feeBeneficiary,
bytes32 secretHash,
uint256 feeFraction
);
/**
* Emitted when a draw is committed.
* @param drawId The draw id
*/
event Committed(
uint256 indexed drawId
);
/**
* Emitted when a draw is rewarded.
* @param drawId The draw id
* @param winner The address of the winner
* @param entropy The entropy used to select the winner
* @param winnings The net winnings given to the winner
* @param fee The fee being given to the draw beneficiary
*/
event Rewarded(
uint256 indexed drawId,
address indexed winner,
bytes32 entropy,
uint256 winnings,
uint256 fee
);
/**
* Emitted when a RewardListener call fails
* @param drawId The draw id
* @param winner The address that one the draw
* @param impl The implementation address of the RewardListener
*/
event RewardListenerFailed(
uint256 indexed drawId,
address indexed winner,
address indexed impl
);
/**
* Emitted when the fee fraction is changed. Takes effect on the next draw.
* @param feeFraction The next fee fraction encoded as a fixed point 18 decimal
*/
event NextFeeFractionChanged(uint256 feeFraction);
/**
* Emitted when the next fee beneficiary changes. Takes effect on the next draw.
* @param feeBeneficiary The next fee beneficiary
*/
event NextFeeBeneficiaryChanged(address indexed feeBeneficiary);
/**
* Emitted when an admin pauses the contract
*/
event DepositsPaused(address indexed sender);
/**
* Emitted when an admin unpauses the contract
*/
event DepositsUnpaused(address indexed sender);
/**
* Emitted when the draw is rolled over in the event that the secret is forgotten.
*/
event RolledOver(uint256 indexed drawId);
struct Draw {
uint256 feeFraction; //fixed point 18
address feeBeneficiary;
uint256 openedBlock;
bytes32 secretHash;
bytes32 entropy;
address winner;
uint256 netWinnings;
uint256 fee;
}
/**
* The Compound cToken that this Pool is bound to.
*/
ICErc20 public cToken;
/**
* The fee beneficiary to use for subsequent Draws.
*/
address public nextFeeBeneficiary;
/**
* The fee fraction to use for subsequent Draws.
*/
uint256 public nextFeeFraction;
/**
* The total of all balances
*/
uint256 public accountedBalance;
/**
* The total deposits and winnings for each user.
*/
mapping (address => uint256) internal balances;
/**
* A mapping of draw ids to Draw structures
*/
mapping(uint256 => Draw) internal draws;
/**
* A structure that is used to manage the user's odds of winning.
*/
DrawManager.State internal drawState;
/**
* A structure containing the administrators
*/
Roles.Role internal admins;
/**
* Whether the contract is paused
*/
bool public paused;
Blocklock.State internal blocklock;
PoolToken public poolToken;
/**
* @notice Initializes a new Pool contract.
* @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries.
* @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens.
* @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number.
* @param _feeBeneficiary The address that will receive the fee fraction
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 _lockDuration,
uint256 _cooldownDuration
) public initializer {
require(_owner != address(0), "Pool/owner-zero");
require(_cToken != address(0), "Pool/ctoken-zero");
cToken = ICErc20(_cToken);
_addAdmin(_owner);
_setNextFeeFraction(_feeFraction);
_setNextFeeBeneficiary(_feeBeneficiary);
initBlocklock(_lockDuration, _cooldownDuration);
}
function setPoolToken(PoolToken _poolToken) external onlyAdmin {
require(address(poolToken) == address(0), "Pool/token-was-set");
require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch");
poolToken = _poolToken;
}
function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal {
blocklock.setLockDuration(_lockDuration);
blocklock.setCooldownDuration(_cooldownDuration);
}
/**
* @notice Opens a new Draw.
* @param _secretHash The secret hash to commit to the Draw.
*/
function open(bytes32 _secretHash) internal {
drawState.openNextDraw();
draws[drawState.openDrawIndex] = Draw(
nextFeeFraction,
nextFeeBeneficiary,
block.number,
_secretHash,
bytes32(0),
address(0),
uint256(0),
uint256(0)
);
emit Opened(
drawState.openDrawIndex,
nextFeeBeneficiary,
_secretHash,
nextFeeFraction
);
}
/**
* @notice Emits the Committed event for the current open draw.
*/
function emitCommitted() internal {
uint256 drawId = currentOpenDrawId();
emit Committed(drawId);
if (address(poolToken) != address(0)) {
poolToken.poolMint(openSupply());
}
}
/**
* @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice:
* the first after Pool contract creation and the second immediately after.
* Can only be called by an admin.
* May fire the Committed event, and always fires the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
*/
function openNextDraw(bytes32 nextSecretHash) public onlyAdmin {
if (currentCommittedDrawId() > 0) {
require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward");
}
if (currentOpenDrawId() != 0) {
emitCommitted();
}
open(nextSecretHash);
}
/**
* @notice Ignores the current draw, and opens the next draw.
* @dev This function will be removed once the winner selection has been decentralized.
* @param nextSecretHash The hash to commit for the next draw
*/
function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin {
rollover();
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash.
* Can only be called by an admin.
* Fires the Rewarded event, the Committed event, and the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
* @param lastSecret The secret to reveal to reward the current committed Draw.
* @param _salt The salt that was used to conceal the secret
*/
function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin {
reward(lastSecret, _salt);
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the winner for the current committed Draw using the passed secret.
* The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance.
* A winner is calculated using the revealed secret.
* If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings.
* The draw beneficiary's balance is updated with the fee.
* The accounted balance is updated to include the fee and, if there was a winner, the net winnings.
* Fires the Rewarded event.
* @param _secret The secret to reveal for the current committed Draw
* @param _salt The salt that was used to conceal the secret
*/
function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant {
// require that there is a committed draw
// require that the committed draw has not been rewarded
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret");
// derive entropy from the revealed secret
bytes32 entropy = keccak256(abi.encodePacked(_secret));
_reward(drawId, draw, entropy);
}
function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal {
blocklock.unlock(block.number);
// Select the winner using the hash as entropy
address winningAddress = calculateWinner(entropy);
// Calculate the gross winnings
uint256 underlyingBalance = balance();
uint256 grossWinnings;
// It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance
// due to rounding errors in the Compound contract.
if (underlyingBalance > accountedBalance) {
grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance));
}
// Calculate the beneficiary fee
uint256 fee = calculateFee(draw.feeFraction, grossWinnings);
// Update balance of the beneficiary
balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee);
// Calculate the net winnings
uint256 netWinnings = grossWinnings.sub(fee);
draw.winner = winningAddress;
draw.netWinnings = netWinnings;
draw.fee = fee;
draw.entropy = entropy;
// If there is a winner who is to receive non-zero winnings
if (winningAddress != address(0) && netWinnings != 0) {
// Updated the accounted total
accountedBalance = underlyingBalance;
// Update balance of the winner
balances[winningAddress] = balances[winningAddress].add(netWinnings);
// Enter their winnings into the open draw
drawState.deposit(winningAddress, netWinnings);
callRewarded(winningAddress, netWinnings, drawId);
} else {
// Only account for the fee
accountedBalance = accountedBalance.add(fee);
}
emit Rewarded(
drawId,
winningAddress,
entropy,
netWinnings,
fee
);
emit FeeCollected(draw.feeBeneficiary, fee, drawId);
}
/**
* @notice Calls the reward listener for the winner, if a listener exists.
* @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function.
* The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract.
*
* @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called.
* @param netWinnings The amount that was won.
* @param drawId The draw id that was won.
*/
function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal {
address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH);
if (impl != address(0)) {
(bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId));
if (!success) {
emit RewardListenerFailed(drawId, winner, impl);
}
}
}
/**
* @notice A function that skips the reward for the committed draw id.
* @dev This function will be removed once the entropy is decentralized.
*/
function rollover() public onlyAdmin requireCommittedNoReward {
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER;
emit RolledOver(
drawId
);
emit Rewarded(
drawId,
address(0),
ROLLED_OVER_ENTROPY_MAGIC_NUMBER,
0,
0
);
}
/**
* @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee
* is always less than zero (meaning the FixidityLib.multiply will always make the number smaller)
*/
function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) {
uint256 max = uint256(FixidityLib.maxNewFixed());
if (_grossWinnings > max) {
return max;
}
return _grossWinnings;
}
/**
* @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings.
* @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number.
* @param _grossWinnings The gross winnings to take a fraction of.
*/
function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) {
int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings));
// _feeFraction *must* be less than 1 ether, so it will never overflow
int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18)));
return uint256(FixidityLib.fromFixed(feeFixed));
}
/**
* @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken.
* Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time.
* The deposit will immediately be added to Compound and the interest will contribute to the next draw.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the sponsorship amount
_depositSponsorshipFrom(msg.sender, _amount);
}
/**
* @notice Deposits the token balance for this contract as a sponsorship.
* If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship.
*/
function transferBalanceToSponsorship() public unlessDepositsPaused {
// Deposit the sponsorship amount
_depositSponsorshipFrom(address(this), token().balanceOf(address(this)));
}
/**
* @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken.
* Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning
* proportional to the total committed balance of all users.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the funds
_depositPoolFrom(msg.sender, _amount);
}
/**
* @notice Deposits sponsorship for a user
* @param _spender The user who is sponsoring
* @param _amount The amount they are sponsoring
*/
function _depositSponsorshipFrom(address _spender, uint256 _amount) internal {
// Deposit the funds
_depositFrom(_spender, _amount);
emit SponsorshipDeposited(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed.
* @param _spender The user who is depositing
* @param _amount The amount the user is depositing
*/
function _depositPoolFrom(address _spender, uint256 _amount) internal {
// Update the user's eligibility
drawState.deposit(_spender, _amount);
_depositFrom(_spender, _amount);
emit Deposited(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw
* @param _spender The user who is depositing
* @param _amount The amount to deposit
*/
function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked {
// Update the user's eligibility
drawState.depositCommitted(_spender, _amount);
_depositFrom(_spender, _amount);
emit DepositedAndCommitted(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract.
* @param _spender The user who is depositing
* @param _amount The amount they are depositing
*/
function _depositFrom(address _spender, uint256 _amount) internal {
// Update the user's balance
balances[_spender] = balances[_spender].add(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.add(_amount);
// Deposit into Compound
require(token().approve(address(cToken), _amount), "Pool/approve");
require(cToken.mint(_amount) == 0, "Pool/supply");
}
/**
* Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship,
* then their open deposits, then their committed deposits.
*
* @param amount The amount to withdraw.
*/
function withdraw(uint256 amount) public nonReentrant notLocked {
uint256 remainingAmount = amount;
// first sponsorship
uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender);
if (sponsorshipAndFeesBalance < remainingAmount) {
withdrawSponsorshipAndFee(sponsorshipAndFeesBalance);
remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance);
} else {
withdrawSponsorshipAndFee(remainingAmount);
return;
}
// now pending
uint256 pendingBalance = drawState.openBalanceOf(msg.sender);
if (pendingBalance < remainingAmount) {
_withdrawOpenDeposit(msg.sender, pendingBalance);
remainingAmount = remainingAmount.sub(pendingBalance);
} else {
_withdrawOpenDeposit(msg.sender, remainingAmount);
return;
}
// now committed. remainingAmount should not be greater than committed balance.
_withdrawCommittedDeposit(msg.sender, remainingAmount);
}
/**
* @notice Withdraw the sender's entire balance back to them.
*/
function withdraw() public nonReentrant notLocked {
uint256 committedBalance = drawState.committedBalanceOf(msg.sender);
uint256 balance = balances[msg.sender];
// Update their chances of winning
drawState.withdraw(msg.sender);
_withdraw(msg.sender, balance);
if (address(poolToken) != address(0)) {
poolToken.poolRedeem(msg.sender, committedBalance);
}
emit Withdrawn(msg.sender, balance);
}
/**
* Withdraws only from the sender's sponsorship and fee balances
* @param _amount The amount to withdraw
*/
function withdrawSponsorshipAndFee(uint256 _amount) public {
uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender);
require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee");
_withdraw(msg.sender, _amount);
emit SponsorshipAndFeesWithdrawn(msg.sender, _amount);
}
/**
* Returns the total balance of the user's sponsorship and fees
* @param _sender The user whose balance should be returned
*/
function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) {
return balances[_sender].sub(drawState.balanceOf(_sender));
}
/**
* Withdraws from the user's open deposits
* @param _amount The amount to withdraw
*/
function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked {
_withdrawOpenDeposit(msg.sender, _amount);
}
function _withdrawOpenDeposit(address sender, uint256 _amount) internal {
drawState.withdrawOpen(sender, _amount);
_withdraw(sender, _amount);
emit OpenDepositWithdrawn(sender, _amount);
}
/**
* Withdraws from the user's committed deposits
* @param _amount The amount to withdraw
*/
function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) {
_withdrawCommittedDeposit(msg.sender, _amount);
return true;
}
function _withdrawCommittedDeposit(address sender, uint256 _amount) internal {
_withdrawCommittedDepositAndEmit(sender, _amount);
if (address(poolToken) != address(0)) {
poolToken.poolRedeem(sender, _amount);
}
}
/**
* Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token.
* @param _from The user to withdraw from
* @param _amount The amount to withdraw
*/
function withdrawCommittedDepositFrom(
address _from,
uint256 _amount
) external onlyToken notLocked returns (bool) {
return _withdrawCommittedDepositAndEmit(_from, _amount);
}
/**
* A function that withdraws committed deposits for a user and emits the corresponding events.
* @param _from User to withdraw for
* @param _amount The amount to withdraw
*/
function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) {
drawState.withdrawCommitted(_from, _amount);
_withdraw(_from, _amount);
emit CommittedDepositWithdrawn(_from, _amount);
return true;
}
/**
* @notice Allows the associated PoolToken to move committed tokens from one user to another.
* @param _from The account to move tokens from
* @param _to The account that is receiving the tokens
* @param _amount The amount of tokens to transfer
*/
function moveCommitted(
address _from,
address _to,
uint256 _amount
) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) {
balances[_from] = balances[_from].sub(_amount, "move could not sub amount");
balances[_to] = balances[_to].add(_amount);
drawState.withdrawCommitted(_from, _amount);
drawState.depositCommitted(_to, _amount);
return true;
}
/**
* @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance.
*/
function _withdraw(address _sender, uint256 _amount) internal {
uint256 balance = balances[_sender];
require(_amount <= balance, "Pool/no-funds");
// Update the user's balance
balances[_sender] = balance.sub(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.sub(_amount);
// Withdraw from Compound and transfer
require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem");
require(token().transfer(_sender, _amount), "Pool/transfer");
}
/**
* @notice Returns the id of the current open Draw.
* @return The current open Draw id
*/
function currentOpenDrawId() public view returns (uint256) {
return drawState.openDrawIndex;
}
/**
* @notice Returns the id of the current committed Draw.
* @return The current committed Draw id
*/
function currentCommittedDrawId() public view returns (uint256) {
if (drawState.openDrawIndex > 1) {
return drawState.openDrawIndex - 1;
} else {
return 0;
}
}
/**
* @notice Returns whether the current committed draw has been rewarded
* @return True if the current committed draw has been rewarded, false otherwise
*/
function currentCommittedDrawHasBeenRewarded() internal view returns (bool) {
Draw storage draw = draws[currentCommittedDrawId()];
return draw.entropy != bytes32(0);
}
/**
* @notice Gets information for a given draw.
* @param _drawId The id of the Draw to retrieve info for.
* @return Fields including:
* feeFraction: the fee fraction
* feeBeneficiary: the beneficiary of the fee
* openedBlock: The block at which the draw was opened
* secretHash: The hash of the secret committed to this draw.
* entropy: the entropy used to select the winner
* winner: the address of the winner
* netWinnings: the total winnings less the fee
* fee: the fee taken by the beneficiary
*/
function getDraw(uint256 _drawId) public view returns (
uint256 feeFraction,
address feeBeneficiary,
uint256 openedBlock,
bytes32 secretHash,
bytes32 entropy,
address winner,
uint256 netWinnings,
uint256 fee
) {
Draw storage draw = draws[_drawId];
feeFraction = draw.feeFraction;
feeBeneficiary = draw.feeBeneficiary;
openedBlock = draw.openedBlock;
secretHash = draw.secretHash;
entropy = draw.entropy;
winner = draw.winner;
netWinnings = draw.netWinnings;
fee = draw.fee;
}
/**
* @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning.
* @param _addr The address of the user
* @return The total committed balance for the user
*/
function committedBalanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning.
* @param _addr The address of the user
* @return The total open balance for the user
*/
function openBalanceOf(address _addr) external view returns (uint256) {
return drawState.openBalanceOf(_addr);
}
/**
* @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits.
* @param _addr The address of the user to check.
* @return The user's current balance.
*/
function totalBalanceOf(address _addr) external view returns (uint256) {
return balances[_addr];
}
/**
* @notice Returns a user's committed balance. This is the balance of their Pool tokens.
* @param _addr The address of the user to check.
* @return The user's current balance.
*/
function balanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Calculates a winner using the passed entropy for the current committed balances.
* @param _entropy The entropy to use to select the winner
* @return The winning address
*/
function calculateWinner(bytes32 _entropy) public view returns (address) {
return drawState.drawWithEntropy(_entropy);
}
/**
* @notice Returns the total committed balance. Used to compute an address's chances of winning.
* @return The total committed balance.
*/
function committedSupply() public view returns (uint256) {
return drawState.committedSupply();
}
/**
* @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw.
* @return The total open balance
*/
function openSupply() public view returns (uint256) {
return drawState.openSupply();
}
/**
* @notice Calculates the total estimated interest earned for the given number of blocks
* @param _blocks The number of block that interest accrued for
* @return The total estimated interest as a 18 point fixed decimal.
*/
function estimatedInterestRate(uint256 _blocks) public view returns (uint256) {
return supplyRatePerBlock().mul(_blocks);
}
/**
* @notice Convenience function to return the supplyRatePerBlock value from the money market contract.
* @return The cToken supply rate per block
*/
function supplyRatePerBlock() public view returns (uint256) {
return cToken.supplyRatePerBlock();
}
/**
* @notice Sets the beneficiary fee fraction for subsequent Draws.
* Fires the NextFeeFractionChanged event.
* Can only be called by an admin.
* @param _feeFraction The fee fraction to use.
* Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether).
*/
function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin {
_setNextFeeFraction(_feeFraction);
}
function _setNextFeeFraction(uint256 _feeFraction) internal {
require(_feeFraction <= 1 ether, "Pool/less-1");
nextFeeFraction = _feeFraction;
emit NextFeeFractionChanged(_feeFraction);
}
/**
* @notice Sets the fee beneficiary for subsequent Draws.
* Can only be called by admins.
* @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address.
*/
function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin {
_setNextFeeBeneficiary(_feeBeneficiary);
}
/**
* @notice Sets the fee beneficiary for subsequent Draws.
* @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address.
*/
function _setNextFeeBeneficiary(address _feeBeneficiary) internal {
require(_feeBeneficiary != address(0), "Pool/not-zero");
nextFeeBeneficiary = _feeBeneficiary;
emit NextFeeBeneficiaryChanged(_feeBeneficiary);
}
/**
* @notice Adds an administrator.
* Can only be called by administrators.
* Fires the AdminAdded event.
* @param _admin The address of the admin to add
*/
function addAdmin(address _admin) public onlyAdmin {
_addAdmin(_admin);
}
/**
* @notice Checks whether a given address is an administrator.
* @param _admin The address to check
* @return True if the address is an admin, false otherwise.
*/
function isAdmin(address _admin) public view returns (bool) {
return admins.has(_admin);
}
/**
* @notice Checks whether a given address is an administrator.
* @param _admin The address to check
* @return True if the address is an admin, false otherwise.
*/
function _addAdmin(address _admin) internal {
admins.add(_admin);
emit AdminAdded(_admin);
}
/**
* @notice Removes an administrator
* Can only be called by an admin.
* Admins cannot remove themselves. This ensures there is always one admin.
* @param _admin The address of the admin to remove
*/
function removeAdmin(address _admin) public onlyAdmin {
require(admins.has(_admin), "Pool/no-admin");
require(_admin != msg.sender, "Pool/remove-self");
admins.remove(_admin);
emit AdminRemoved(_admin);
}
/**
* Requires that there is a committed draw that has not been rewarded.
*/
modifier requireCommittedNoReward() {
require(currentCommittedDrawId() > 0, "Pool/committed");
require(!currentCommittedDrawHasBeenRewarded(), "Pool/already");
_;
}
/**
* @notice Returns the token underlying the cToken.
* @return An ERC20 token address
*/
function token() public view returns (IERC20) {
return IERC20(cToken.underlying());
}
/**
* @notice Returns the underlying balance of this contract in the cToken.
* @return The cToken underlying balance for this contract.
*/
function balance() public returns (uint256) {
return cToken.balanceOfUnderlying(address(this));
}
/**
* @notice Locks the movement of tokens (essentially the committed deposits and winnings)
* @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes.
*/
function lockTokens() public onlyAdmin {
blocklock.lock(block.number);
}
/**
* @notice Unlocks the movement of tokens (essentially the committed deposits)
*/
function unlockTokens() public onlyAdmin {
blocklock.unlock(block.number);
}
/**
* Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue
* to collect rewards and withdraw, but eventually the Pool will grow smaller.
*
* emits DepositsPaused
*/
function pauseDeposits() public unlessDepositsPaused onlyAdmin {
paused = true;
emit DepositsPaused(msg.sender);
}
/**
* @notice Unpauses all deposits into the contract
*
* emits DepositsUnpaused
*/
function unpauseDeposits() public whenDepositsPaused onlyAdmin {
paused = false;
emit DepositsUnpaused(msg.sender);
}
/**
* @notice Check if the contract is locked.
* @return True if the contract is locked, false otherwise
*/
function isLocked() public view returns (bool) {
return blocklock.isLocked(block.number);
}
/**
* @notice Returns the block number at which the lock expires
* @return The block number at which the lock expires
*/
function lockEndAt() public view returns (uint256) {
return blocklock.lockEndAt();
}
/**
* @notice Check cooldown end block
* @return The block number at which the cooldown ends and the contract can be re-locked
*/
function cooldownEndAt() public view returns (uint256) {
return blocklock.cooldownEndAt();
}
/**
* @notice Returns whether the contract can be locked
* @return True if the contract can be locked, false otherwise
*/
function canLock() public view returns (bool) {
return blocklock.canLock(block.number);
}
/**
* @notice Duration of the lock
* @return Returns the duration of the lock in blocks.
*/
function lockDuration() public view returns (uint256) {
return blocklock.lockDuration;
}
/**
* @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked.
* The Pool cannot be locked during the cooldown period.
* @return The cooldown duration in blocks
*/
function cooldownDuration() public view returns (uint256) {
return blocklock.cooldownDuration;
}
/**
* @notice requires the pool not to be locked
*/
modifier notLocked() {
require(!blocklock.isLocked(block.number), "Pool/locked");
_;
}
/**
* @notice requires the pool to be locked
*/
modifier onlyLocked() {
require(blocklock.isLocked(block.number), "Pool/unlocked");
_;
}
/**
* @notice requires the caller to be an admin
*/
modifier onlyAdmin() {
require(admins.has(msg.sender), "Pool/admin");
_;
}
/**
* @notice Requires an open draw to exist
*/
modifier requireOpenDraw() {
require(currentOpenDrawId() != 0, "Pool/no-open");
_;
}
/**
* @notice Requires deposits to be paused
*/
modifier whenDepositsPaused() {
require(paused, "Pool/d-not-paused");
_;
}
/**
* @notice Requires deposits not to be paused
*/
modifier unlessDepositsPaused() {
require(!paused, "Pool/d-paused");
_;
}
/**
* @notice Requires the caller to be the pool token
*/
modifier onlyToken() {
require(msg.sender == address(poolToken), "Pool/only-token");
_;
}
/**
* @notice requires the passed user's committed balance to be greater than or equal to the passed amount
* @param _from The user whose committed balance should be checked
* @param _amount The minimum amount they must have
*/
modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) {
uint256 committedBalance = drawState.committedBalanceOf(_from);
require(_amount <= committedBalance, "not enough funds");
_;
}
}
contract ScdMcdMigration {
SaiTubLike public tub;
VatLike public vat;
ManagerLike public cdpManager;
JoinLike public saiJoin;
JoinLike public wethJoin;
JoinLike public daiJoin;
constructor(
address tub_, // SCD tub contract address
address cdpManager_, // MCD manager contract address
address saiJoin_, // MCD SAI collateral adapter contract address
address wethJoin_, // MCD ETH collateral adapter contract address
address daiJoin_ // MCD DAI adapter contract address
) public {
tub = SaiTubLike(tub_);
cdpManager = ManagerLike(cdpManager_);
vat = VatLike(cdpManager.vat());
saiJoin = JoinLike(saiJoin_);
wethJoin = JoinLike(wethJoin_);
daiJoin = JoinLike(daiJoin_);
require(wethJoin.gem() == tub.gem(), "non-matching-weth");
require(saiJoin.gem() == tub.sai(), "non-matching-sai");
tub.gov().approve(address(tub), uint(-1));
tub.skr().approve(address(tub), uint(-1));
tub.sai().approve(address(tub), uint(-1));
tub.sai().approve(address(saiJoin), uint(-1));
wethJoin.gem().approve(address(wethJoin), uint(-1));
daiJoin.dai().approve(address(daiJoin), uint(-1));
vat.hope(address(daiJoin));
}
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
// Function to swap SAI to DAI
// This function is to be used by users that want to get new DAI in exchange of old one (aka SAI)
// wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one)
function swapSaiToDai(
uint wad
) external {
// Get wad amount of SAI from user's wallet:
saiJoin.gem().transferFrom(msg.sender, address(this), wad);
// Join the SAI wad amount to the `vat`:
saiJoin.join(address(this), wad);
// Lock the SAI wad amount to the CDP and generate the same wad amount of DAI
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad));
// Send DAI wad amount as a ERC20 token to the user's wallet
daiJoin.exit(msg.sender, wad);
}
// Function to swap DAI to SAI
// This function is to be used by users that want to get SAI in exchange of DAI
// wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP
function swapDaiToSai(
uint wad
) external {
// Get wad amount of DAI from user's wallet:
daiJoin.dai().transferFrom(msg.sender, address(this), wad);
// Join the DAI wad amount to the vat:
daiJoin.join(address(this), wad);
// Payback the DAI wad amount and unlocks the same value of SAI collateral
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad));
// Send SAI wad amount as a ERC20 token to the user's wallet
saiJoin.exit(msg.sender, wad);
}
// Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage.
// In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio)
function migrate(
bytes32 cup
) external returns (uint cdp) {
// Get values
uint debtAmt = tub.tab(cup); // CDP SAI debt
uint pethAmt = tub.ink(cup); // CDP locked collateral
uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH
// Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio
// This is not actually a problem as this ilk will only be accessed by this migration contract,
// which will make sure to have the amounts balanced out at the end of the execution.
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
-toInt(debtAmt),
0
);
saiJoin.exit(address(this), debtAmt); // SAI is exited as a token
// Shut SAI CDP and gets WETH back
tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call)
tub.exit(pethAmt); // Converts PETH to WETH
// Open future user's CDP in MCD
cdp = cdpManager.open(wethJoin.ilk(), address(this));
// Join WETH to Adapter
wethJoin.join(cdpManager.urns(cdp), ethAmt);
// Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP
(, uint rate,,,) = vat.ilks(wethJoin.ilk());
cdpManager.frob(
cdp,
toInt(ethAmt),
toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt
);
// Move DAI generated to migration contract (to recover the used funds)
cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27));
// Re-balance MCD SAI migration contract's CDP
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
0,
-toInt(debtAmt)
);
// Set ownership of CDP to the user
cdpManager.give(cdp, msg.sender);
}
}
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @title MCDAwarePool
* @author Brendan Asselstine [email protected]
* @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to
* detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai
* and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for
* users to encourage them to migrate to the MCD Pool.
*/
contract MCDAwarePool is BasePool, IERC777Recipient {
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
uint256 internal constant DEFAULT_LOCK_DURATION = 40;
uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80;
/**
* @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts)
*/
ScdMcdMigration public scdMcdMigration;
/**
* @notice The address of the Sai Pool contract
*/
MCDAwarePool public saiPool;
/**
* @notice Initializes the contract.
* @param _owner The initial administrator of the contract
* @param _cToken The Compound cToken to bind this Pool to
* @param _feeFraction The fraction of the winnings to give to the beneficiary
* @param _feeBeneficiary The beneficiary who receives the fee
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 lockDuration,
uint256 cooldownDuration
) public initializer {
super.init(
_owner,
_cToken,
_feeFraction,
_feeBeneficiary,
lockDuration,
cooldownDuration
);
initRegistry();
initBlocklock(lockDuration, cooldownDuration);
}
/**
* @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock.
*/
function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public {
initRegistry();
if (blocklock.lockDuration == 0) {
initBlocklock(lockDuration, cooldownDuration);
}
}
function initRegistry() internal {
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin {
_initMigration(_scdMcdMigration, _saiPool);
}
function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal {
require(address(scdMcdMigration) == address(0), "Pool/init");
require(address(_scdMcdMigration) != address(0), "Pool/mig-def");
scdMcdMigration = _scdMcdMigration;
saiPool = _saiPool; // may be null
}
/**
* @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool
* and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of
* the sender. It will reject all other tokens.
*
* If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the
* open prize. This is to encourage migration.
*
* @param from The sender
* @param amount The amount they are transferring
*/
function tokensReceived(
address, // operator
address from,
address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface
uint256 amount,
bytes calldata,
bytes calldata
) external unlessDepositsPaused {
require(msg.sender == address(saiPoolToken()), "Pool/sai-only");
require(address(token()) == address(daiToken()), "Pool/not-dai");
// cash out of the Pool. This call transfers sai to this contract
saiPoolToken().redeem(amount, '');
// approve of the transfer to the migration contract
saiToken().approve(address(scdMcdMigration), amount);
// migrate the sai to dai. The contract now has dai
scdMcdMigration.swapSaiToDai(amount);
if (currentCommittedDrawId() > 0) {
// now deposit the dai as tickets
_depositPoolFromCommitted(from, amount);
} else {
_depositPoolFrom(from, amount);
}
}
/**
* @notice Returns the address of the PoolSai pool token contract
* @return The address of the Sai PoolToken contract
*/
function saiPoolToken() internal view returns (PoolToken) {
if (address(saiPool) != address(0)) {
return saiPool.poolToken();
} else {
return PoolToken(0);
}
}
/**
* @notice Returns the address of the Sai token
* @return The address of the sai token
*/
function saiToken() public returns (GemLike) {
return scdMcdMigration.saiJoin().gem();
}
/**
* @notice Returns the address of the Dai token
* @return The address of the Dai token.
*/
function daiToken() public returns (GemLike) {
return scdMcdMigration.daiJoin().dai();
}
} | * @dev Redeems tokens for the underlying asset. @param operator address operator requesting the operation @param from address token holder address @param amount uint256 amount of tokens to redeem @param data bytes extra information provided by the token holder @param operatorData bytes extra information provided by the operator (if any)/ | function _redeem(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_pool.withdrawCommittedDepositFrom(from, amount);
emit Redeemed(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
| 8,015,357 | [
1,
426,
323,
7424,
2430,
364,
326,
6808,
3310,
18,
225,
3726,
1758,
3726,
18709,
326,
1674,
225,
628,
1758,
1147,
10438,
1758,
225,
3844,
2254,
5034,
3844,
434,
2430,
358,
283,
24903,
225,
501,
1731,
2870,
1779,
2112,
635,
326,
1147,
10438,
225,
3726,
751,
1731,
2870,
1779,
2112,
635,
326,
3726,
261,
430,
1281,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
266,
24903,
12,
203,
1377,
1758,
3726,
16,
203,
1377,
1758,
628,
16,
203,
1377,
2254,
5034,
3844,
16,
203,
1377,
1731,
3778,
501,
16,
203,
1377,
1731,
3778,
3726,
751,
203,
225,
262,
203,
1377,
3238,
203,
225,
288,
203,
1377,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
2864,
1345,
19,
2080,
17,
7124,
8863,
203,
203,
1377,
389,
1991,
5157,
28878,
12,
9497,
16,
628,
16,
1758,
12,
20,
3631,
3844,
16,
501,
16,
3726,
751,
1769,
203,
203,
1377,
389,
6011,
18,
1918,
9446,
27813,
758,
1724,
1265,
12,
2080,
16,
3844,
1769,
203,
203,
1377,
3626,
868,
24903,
329,
12,
9497,
16,
628,
16,
3844,
16,
501,
16,
3726,
751,
1769,
203,
1377,
3626,
12279,
12,
2080,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/1149/0x8A270C025F4350ae59E9878910063f45f1F403Fa/sources/Projects/Plex-F/TokenLogic/contracts/OwnableUpgradable.sol | * @dev Initializes the contract setting the deployer as the initial owner./ | function _Ownable_init () internal {
_transferOwnership(_msgSender());
}
| 4,664,602 | [
1,
9685,
326,
6835,
3637,
326,
7286,
264,
487,
326,
2172,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5460,
429,
67,
2738,
1832,
2713,
288,
203,
202,
67,
13866,
5460,
12565,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xfD6E4978ECf03fc98bB7bDAB75ecE0F9b57ddC6B/sources/PutinKaput.sol | * @dev Throws if called by any account other than the owner./ | modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
| 3,883,853 | [
1,
21845,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
9606,
1338,
5541,
1435,
288,
203,
1850,
2583,
24899,
8443,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
1850,
389,
31,
203,
1377,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "./BackedToken.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title BackingContract
* @author Rosco Kalis <[email protected]>
*/
contract BackingContract {
using SafeMath for uint256;
BackedToken public backedToken;
uint256 public balanceForBacking;
modifier onlyBackedToken() {
require(msg.sender == address(backedToken), "Can only be called by the backed token contract");
_;
}
/**
* @dev Fallback payable function, adding the new funds to balanceForBacking.
*/
function() external payable {
balanceForBacking = balanceForBacking.add(msg.value);
}
/**
* @notice Sets the backed token and backs it.
* @param backedTokenAddress The address of the deployed backed token.
*/
constructor(address payable backedTokenAddress) public {
backedToken = BackedToken(backedTokenAddress);
backedToken.back(address(this));
}
/**
* @notice Allows the backed token to deposit funds into the contract.
* @dev Funds are added to balanceForBacking as well.
*/
function deposit() external payable onlyBackedToken {
balanceForBacking = balanceForBacking.add(msg.value);
}
/**
* @notice Allows the backed token to withdraw funds from the contract.
* @dev Funds are removed from balanceForBacking as well.
* @param ethAmount The amount of eth to withdraw.
*/
function withdraw(uint256 ethAmount) external onlyBackedToken {
require(ethAmount <= address(this).balance, "Can not withdraw more than balance");
require(ethAmount <= balanceForBacking, "Can not withdraw more than balance for backing");
balanceForBacking = balanceForBacking.sub(ethAmount);
backedToken.deposit.value(ethAmount)();
}
}
| * @notice Sets the backed token and backs it. @param backedTokenAddress The address of the deployed backed token./ | constructor(address payable backedTokenAddress) public {
backedToken = BackedToken(backedTokenAddress);
backedToken.back(address(this));
}
| 12,948,904 | [
1,
2785,
326,
20732,
1147,
471,
1473,
87,
518,
18,
225,
20732,
1345,
1887,
1021,
1758,
434,
326,
19357,
20732,
1147,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
8843,
429,
20732,
1345,
1887,
13,
1071,
288,
203,
3639,
20732,
1345,
273,
4297,
329,
1345,
12,
823,
329,
1345,
1887,
1769,
203,
3639,
20732,
1345,
18,
823,
12,
2867,
12,
2211,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./uniswapv2/interfaces/IUniswapV2ERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
// This contract trades tokens collected from fees for BAMBOO, and sends them to BambooField and BambooVault
// As specified in the whitepaper, this contract collects 0.1% of fees and divides 0.06% for BambooVault and 0.04 for BambooField, that rewards past and present liquidity providers
contract BambooFarmer {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IUniswapV2Factory public factory;
address public field;
address public bamboo;
address public weth;
// The only dev address
address public vaultSetter;
address public vault;
constructor(IUniswapV2Factory _factory, address _field, address _bamboo, address _weth, address _vaultSetter) {
factory = _factory;
bamboo = _bamboo;
field = _field;
weth = _weth;
vaultSetter = _vaultSetter;
}
modifier onlyEOA() {
// Try to make flash-loan exploit harder to do by only allowing externally owned addresses.
require(msg.sender == tx.origin, "must use EOA");
_;
}
function convert(address token0, address token1) public onlyEOA{
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));
uint256 pairBalance = pair.balanceOf(address(this));
if (vault != address(0)) {
// If vault is set, send 60 to vault 40 to BambooField
uint256 amountDev = pairBalance.mul(60).div(100);
pairBalance = pairBalance.sub(amountDev);
_safeTransfer(address(pair), vault, amountDev);
}
// Convert the rest to the original tokens
pair.transfer(address(pair), pairBalance);
pair.burn(address(this));
// First we convert everything to WETH
uint256 wethAmount = _toWETH(token0) + _toWETH(token1);
// Then we convert the WETH to Bamboo
_toBAMBOO(wethAmount);
}
// Converts token passed as an argument to WETH
function _toWETH(address token) internal returns (uint256) {
// If the passed token is Bamboo, don't convert anything
if (token == bamboo) {
uint amount = IERC20(token).balanceOf(address(this));
_safeTransfer(token, field, amount);
return 0;
}
// If the passed token is WETH, don't convert anything
if (token == weth) {
uint amount = IERC20(token).balanceOf(address(this));
_safeTransfer(token, factory.getPair(weth, bamboo), amount);
return amount;
}
// If the target pair doesn't exist, don't convert anything
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token, weth));
if (address(pair) == address(0)) {
return 0;
}
// Choose the correct reserve to swap from
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0);
// Calculate information required to swap
uint amountIn = IERC20(token).balanceOf(address(this));
uint amountInWithFee = amountIn.mul(1000-pair.fee());
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
uint amountOut = numerator / denominator;
(uint amount0Out, uint amount1Out) = token0 == token ? (uint(0), amountOut) : (amountOut, uint(0));
// Swap the token for WETH
_safeTransfer(token, address(pair), amountIn);
pair.swap(amount0Out, amount1Out, factory.getPair(weth, bamboo), new bytes(0));
return amountOut;
}
// Converts WETH to Bamboo
function _toBAMBOO(uint256 amountIn) internal {
if(amountIn == 0) {
return;
}
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(weth, bamboo));
// Choose WETH as input token
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == weth ? (reserve0, reserve1) : (reserve1, reserve0);
// Calculate information required to swap
uint amountInWithFee = amountIn.mul(1000-pair.fee());
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
uint amountOut = numerator / denominator;
(uint amount0Out, uint amount1Out) = token0 == weth ? (uint(0), amountOut) : (amountOut, uint(0));
// Swap WETH for Bamboo
pair.swap(amount0Out, amount1Out, field, new bytes(0));
}
// Wrapper for safeTransfer
function _safeTransfer(address token, address to, uint256 amount) internal {
IERC20(token).safeTransfer(to, amount);
}
function setVault(address _vault) external {
require(msg.sender == vaultSetter, 'setVault: FORBIDDEN');
vault = _vault;
}
function setVaultSetter(address _vaultSetter) external {
require(msg.sender == vaultSetter, 'setVault: FORBIDDEN');
vaultSetter = _vaultSetter;
}
} | Convert the rest to the original tokens | pair.transfer(address(pair), pairBalance);
| 13,019,140 | [
1,
2723,
326,
3127,
358,
326,
2282,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3082,
18,
13866,
12,
2867,
12,
6017,
3631,
3082,
13937,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.9;
import { FixedPoint128 } from '@uniswap/v3-core-0.8-support/contracts/libraries/FixedPoint128.sol';
import { SafeCast } from '@uniswap/v3-core-0.8-support/contracts/libraries/SafeCast.sol';
import { FullMath } from '@uniswap/v3-core-0.8-support/contracts/libraries/FullMath.sol';
import { Account } from './Account.sol';
import { AddressHelper } from './AddressHelper.sol';
import { LiquidityPosition } from './LiquidityPosition.sol';
import { LiquidityPositionSet } from './LiquidityPositionSet.sol';
import { Protocol } from './Protocol.sol';
import { PriceMath } from './PriceMath.sol';
import { SignedFullMath } from './SignedFullMath.sol';
import { SignedMath } from './SignedMath.sol';
import { VTokenPosition } from './VTokenPosition.sol';
import { Uint32L8ArrayLib } from './Uint32L8Array.sol';
import { IClearingHouseStructures } from '../interfaces/clearinghouse/IClearingHouseStructures.sol';
import { IVPoolWrapper } from '../interfaces/IVPoolWrapper.sol';
import { IVToken } from '../interfaces/IVToken.sol';
/// @title VToken position set functions
library VTokenPositionSet {
using AddressHelper for address;
using FullMath for uint256;
using PriceMath for uint256;
using SafeCast for uint256;
using SignedFullMath for int256;
using SignedMath for int256;
using Uint32L8ArrayLib for uint32[8];
using LiquidityPositionSet for LiquidityPosition.Set;
using Protocol for Protocol.Info;
using VTokenPosition for VTokenPosition.Info;
using VTokenPositionSet for VTokenPosition.Set;
error VPS_IncorrectUpdate();
error VPS_DeactivationFailed(uint32 poolId);
error VPS_TokenInactive(uint32 poolId);
/**
* Internal methods
*/
/// @notice activates token with address 'vToken' if not already active
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
function activate(VTokenPosition.Set storage set, uint32 poolId) internal {
set.active.include(poolId);
}
/// @notice deactivates token with address 'vToken'
/// @dev ensures that the balance is 0 and there are not range positions active otherwise throws an error
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
function deactivate(VTokenPosition.Set storage set, uint32 poolId) internal {
if (set.positions[poolId].balance != 0 || !set.positions[poolId].liquidityPositions.isEmpty()) {
revert VPS_DeactivationFailed(poolId);
}
set.active.exclude(poolId);
}
/// @notice updates token balance, net trader position and vQuote balance
/// @dev realizes funding payment to vQuote balance
/// @dev activates the token if not already active
/// @dev deactivates the token if the balance = 0 and there are no range positions active
/// @dev IMP: ensure that the global states are updated using zeroSwap or directly through some interaction with pool wrapper
/// @param set VTokenPositionSet
/// @param balanceAdjustments platform constants
/// @param poolId id of the rage trade pool
/// @param accountId account identifier, used for emitting event
/// @param protocol platform constants
function update(
VTokenPosition.Set storage set,
uint256 accountId,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
uint32 poolId,
Protocol.Info storage protocol
) internal {
set.realizeFundingPayment(accountId, poolId, protocol);
set.active.include(poolId);
VTokenPosition.Info storage _VTokenPosition = set.positions[poolId];
_VTokenPosition.balance += balanceAdjustments.vTokenIncrease;
_VTokenPosition.netTraderPosition += balanceAdjustments.traderPositionIncrease;
set.vQuoteBalance += balanceAdjustments.vQuoteIncrease;
if (_VTokenPosition.balance == 0 && _VTokenPosition.liquidityPositions.active[0] == 0) {
set.deactivate(poolId);
}
}
/// @notice realizes funding payment to vQuote balance
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param accountId account identifier, used for emitting event
/// @param protocol platform constants
function realizeFundingPayment(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
Protocol.Info storage protocol
) internal {
set.realizeFundingPayment(accountId, poolId, protocol.pools[poolId].vPoolWrapper);
}
/// @notice realizes funding payment to vQuote balance
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param accountId account identifier, used for emitting event
/// @param wrapper VPoolWrapper to override the set wrapper
function realizeFundingPayment(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IVPoolWrapper wrapper
) internal {
VTokenPosition.Info storage position = set.positions[poolId];
int256 extrapolatedSumAX128 = wrapper.getSumAX128();
int256 fundingPayment = position.unrealizedFundingPayment(wrapper);
set.vQuoteBalance += fundingPayment;
position.sumALastX128 = extrapolatedSumAX128;
emit Account.TokenPositionFundingPaymentRealized(accountId, poolId, fundingPayment, extrapolatedSumAX128);
}
/// @notice swaps tokens (Long and Short) with input in token amount / vQuote amount
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param swapParams parameters for swap
/// @param protocol platform constants
/// @return vTokenAmountOut - token amount coming out of pool
/// @return vQuoteAmountOut - vQuote amount coming out of pool
function swapToken(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.SwapParams memory swapParams,
Protocol.Info storage protocol
) internal returns (int256 vTokenAmountOut, int256 vQuoteAmountOut) {
return set.swapToken(accountId, poolId, swapParams, protocol.vPoolWrapper(poolId), protocol);
}
/// @notice swaps tokens (Long and Short) with input in token amount
/// @dev activates inactive vToe
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param vTokenAmount amount of the token
/// @param protocol platform constants
/// @return vTokenAmountOut - token amount coming out of pool
/// @return vQuoteAmountOut - vQuote amount coming out of pool
function swapTokenAmount(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
int256 vTokenAmount,
Protocol.Info storage protocol
) internal returns (int256 vTokenAmountOut, int256 vQuoteAmountOut) {
return
set.swapToken(
accountId,
poolId,
/// @dev 0 means no price limit and false means amount mentioned is token amount
IClearingHouseStructures.SwapParams({
amount: vTokenAmount,
sqrtPriceLimit: 0,
isNotional: false,
isPartialAllowed: false,
settleProfit: false
}),
protocol.vPoolWrapper(poolId),
protocol
);
}
/// @notice swaps tokens (Long and Short) with input in token amount / vQuote amount
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param swapParams parameters for swap
/// @param wrapper VPoolWrapper to override the set wrapper
/// @param protocol platform constants
/// @return vTokenAmountOut - token amount coming out of pool
/// @return vQuoteAmountOut - vQuote amount coming out of pool
function swapToken(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.SwapParams memory swapParams,
IVPoolWrapper wrapper,
Protocol.Info storage protocol
) internal returns (int256 vTokenAmountOut, int256 vQuoteAmountOut) {
IVPoolWrapper.SwapResult memory swapResult = wrapper.swap(
swapParams.amount < 0,
swapParams.isNotional ? swapParams.amount : -swapParams.amount,
swapParams.sqrtPriceLimit
);
// change direction basis uniswap to balance increase
vTokenAmountOut = -swapResult.vTokenIn;
vQuoteAmountOut = -swapResult.vQuoteIn;
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments = IClearingHouseStructures
.BalanceAdjustments(vQuoteAmountOut, vTokenAmountOut, vTokenAmountOut);
set.update(accountId, balanceAdjustments, poolId, protocol);
emit Account.TokenPositionChanged(
accountId,
poolId,
vTokenAmountOut,
vQuoteAmountOut,
swapResult.sqrtPriceX96Start,
swapResult.sqrtPriceX96End
);
}
/// @notice function to liquidate all liquidity positions
/// @param set VTokenPositionSet
/// @param protocol platform constants
/// @return notionalAmountClosed - value of net token position coming out (in notional) of all the ranges closed
function liquidateLiquidityPositions(
VTokenPosition.Set storage set,
uint256 accountId,
Protocol.Info storage protocol
) internal returns (uint256 notionalAmountClosed) {
for (uint8 i = 0; i < set.active.length; i++) {
uint32 truncated = set.active[i];
if (truncated == 0) break;
notionalAmountClosed += set.liquidateLiquidityPositions(accountId, set.active[i], protocol);
}
}
/// @notice function to liquidate liquidity positions for a particular token
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param protocol platform constants
/// @return notionalAmountClosed - value of net token position coming out (in notional) of all the ranges closed
function liquidateLiquidityPositions(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
Protocol.Info storage protocol
) internal returns (uint256 notionalAmountClosed) {
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments;
set.getTokenPosition(poolId, false).liquidityPositions.closeAllLiquidityPositions(
accountId,
poolId,
balanceAdjustments,
protocol
);
set.update(accountId, balanceAdjustments, poolId, protocol);
// returns notional value of token position closed
return protocol.getNotionalValue(poolId, balanceAdjustments.traderPositionIncrease);
}
/// @notice function for liquidity add/remove
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param liquidityChangeParams includes tickLower, tickUpper, liquidityDelta, limitOrderType
/// @return vTokenAmountOut amount of tokens that account received (positive) or paid (negative)
/// @return vQuoteAmountOut amount of vQuote tokens that account received (positive) or paid (negative)
function liquidityChange(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.LiquidityChangeParams memory liquidityChangeParams,
Protocol.Info storage protocol
) internal returns (int256 vTokenAmountOut, int256 vQuoteAmountOut) {
VTokenPosition.Info storage vTokenPosition = set.getTokenPosition(poolId, true);
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments;
vTokenPosition.liquidityPositions.liquidityChange(
accountId,
poolId,
liquidityChangeParams,
balanceAdjustments,
protocol
);
set.update(accountId, balanceAdjustments, poolId, protocol);
if (liquidityChangeParams.closeTokenPosition) {
set.swapTokenAmount(accountId, poolId, -balanceAdjustments.traderPositionIncrease, protocol);
}
return (balanceAdjustments.vTokenIncrease, balanceAdjustments.vQuoteIncrease);
}
/// @notice function to remove an eligible limit order
/// @dev checks whether the current price is on the correct side of the range based on the type of limit order (None, Low, High)
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param tickLower lower tick index for the range
/// @param tickUpper upper tick index for the range
/// @param protocol platform constants
function removeLimitOrder(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
int24 tickLower,
int24 tickUpper,
Protocol.Info storage protocol
) internal {
VTokenPosition.Info storage vTokenPosition = set.getTokenPosition(poolId, false);
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments;
int24 currentTick = protocol.getVirtualCurrentTick(poolId);
vTokenPosition.liquidityPositions.removeLimitOrder(
accountId,
poolId,
currentTick,
tickLower,
tickUpper,
balanceAdjustments,
protocol
);
set.update(accountId, balanceAdjustments, poolId, protocol);
}
/**
* Internal view methods
*/
/// @notice returns account market value of active positions
/// @param set VTokenPositionSet
/// @param protocol platform constants
/// @return accountMarketValue
function getAccountMarketValue(VTokenPosition.Set storage set, Protocol.Info storage protocol)
internal
view
returns (int256 accountMarketValue)
{
for (uint8 i = 0; i < set.active.length; i++) {
uint32 poolId = set.active[i];
if (poolId == 0) break;
// IVToken vToken = protocol[poolId].vToken;
VTokenPosition.Info storage position = set.positions[poolId];
(, uint256 virtualPriceX128) = protocol.getTwapPricesWithDeviationCheck(poolId);
uint160 virtualSqrtPriceX96 = virtualPriceX128.toSqrtPriceX96();
//Value of token position for current vToken
accountMarketValue += position.marketValue(poolId, virtualPriceX128, protocol);
//Value of all active range position for the current vToken
accountMarketValue += position.liquidityPositions.marketValue(virtualSqrtPriceX96, poolId, protocol);
}
// Value of the vQuote token balance
accountMarketValue += set.vQuoteBalance;
}
function getInfo(VTokenPosition.Set storage set)
internal
view
returns (int256 vQuoteBalance, IClearingHouseStructures.VTokenPositionView[] memory vTokenPositions)
{
vQuoteBalance = set.vQuoteBalance;
uint256 numberOfTokenPositions = set.active.numberOfNonZeroElements();
vTokenPositions = new IClearingHouseStructures.VTokenPositionView[](numberOfTokenPositions);
for (uint256 i = 0; i < numberOfTokenPositions; i++) {
vTokenPositions[i].poolId = set.active[i];
vTokenPositions[i].balance = set.positions[set.active[i]].balance;
vTokenPositions[i].netTraderPosition = set.positions[set.active[i]].netTraderPosition;
vTokenPositions[i].sumALastX128 = set.positions[set.active[i]].sumALastX128;
vTokenPositions[i].liquidityPositions = set.positions[set.active[i]].liquidityPositions.getInfo();
}
}
/// @notice returns the long and short side risk for range positions of a particular token
/// @param set VTokenPositionSet
/// @param isInitialMargin specifies to use initial margin factor (true) or maintainance margin factor (false)
/// @param poolId id of the rage trade pool
/// @param protocol platform constants
/// @return longSideRisk - risk if the token price goes down
/// @return shortSideRisk - risk if the token price goes up
function getLongShortSideRisk(
VTokenPosition.Set storage set,
bool isInitialMargin,
uint32 poolId,
Protocol.Info storage protocol
) internal view returns (int256 longSideRisk, int256 shortSideRisk) {
VTokenPosition.Info storage position = set.positions[poolId];
(, uint256 virtualPriceX128) = protocol.getTwapPricesWithDeviationCheck(poolId);
uint160 virtualSqrtPriceX96 = virtualPriceX128.toSqrtPriceX96();
uint16 marginRatio = protocol.getMarginRatioBps(poolId, isInitialMargin);
int256 tokenPosition = position.balance;
int256 longSideRiskRanges = position.liquidityPositions.longSideRisk(virtualSqrtPriceX96).toInt256();
longSideRisk = SignedMath
.max(position.netTraderPosition.mulDiv(virtualPriceX128, FixedPoint128.Q128) + longSideRiskRanges, 0)
.mulDiv(marginRatio, 1e4);
shortSideRisk = SignedMath.max(-tokenPosition, 0).mulDiv(virtualPriceX128, FixedPoint128.Q128).mulDiv(
marginRatio,
1e4
);
return (longSideRisk, shortSideRisk);
}
function getNetPosition(
VTokenPosition.Set storage set,
uint32 poolId,
Protocol.Info storage protocol
) internal view returns (int256 netPosition) {
if (!set.active.exists(poolId)) return 0;
VTokenPosition.Info storage tokenPosition = set.positions[poolId];
return tokenPosition.getNetPosition(poolId, protocol);
}
/// @notice returns the long and short side risk for range positions of a particular token
/// @param set VTokenPositionSet
/// @param isInitialMargin specifies to use initial margin factor (true) or maintainance margin factor (false)
/// @param protocol platform constants
/// @return requiredMargin - required margin value based on the current active positions
function getRequiredMargin(
VTokenPosition.Set storage set,
bool isInitialMargin,
Protocol.Info storage protocol
) internal view returns (int256 requiredMargin) {
int256 longSideRiskTotal;
int256 shortSideRiskTotal;
int256 longSideRisk;
int256 shortSideRisk;
for (uint8 i = 0; i < set.active.length; i++) {
if (set.active[i] == 0) break;
uint32 poolId = set.active[i];
(longSideRisk, shortSideRisk) = set.getLongShortSideRisk(isInitialMargin, poolId, protocol);
if (protocol.isPoolCrossMargined(poolId)) {
longSideRiskTotal += longSideRisk;
shortSideRiskTotal += shortSideRisk;
} else {
requiredMargin += SignedMath.max(longSideRisk, shortSideRisk);
}
}
requiredMargin += SignedMath.max(longSideRiskTotal, shortSideRiskTotal);
}
/// @notice get or create token position
/// @dev activates inactive vToken if isCreateNew is true else reverts
/// @param set VTokenPositionSet
/// @param poolId id of the rage trade pool
/// @param createNew if 'vToken' is inactive then activates (true) else reverts with TokenInactive(false)
/// @return position - VTokenPosition corresponding to 'vToken'
function getTokenPosition(
VTokenPosition.Set storage set,
uint32 poolId,
bool createNew
) internal returns (VTokenPosition.Info storage position) {
if (createNew) {
set.activate(poolId);
} else if (!set.active.exists(poolId)) {
revert VPS_TokenInactive(poolId);
}
position = set.positions[poolId];
}
/// @notice returns true if the set does not have any token position active
/// @param set VTokenPositionSet
/// @return True if there are no active positions
function isEmpty(VTokenPosition.Set storage set) internal view returns (bool) {
return set.active.isEmpty();
}
/// @notice returns true if range position is active for 'vToken'
/// @param set VTokenPositionSet
/// @param poolId poolId of the vToken
/// @return isRangeActive
function isTokenRangeActive(VTokenPosition.Set storage set, uint32 poolId) internal returns (bool isRangeActive) {
VTokenPosition.Info storage vTokenPosition = set.getTokenPosition(poolId, false);
isRangeActive = !vTokenPosition.liquidityPositions.isEmpty();
}
}
| @notice swaps tokens (Long and Short) with input in token amount / vQuote amount @param set VTokenPositionSet @param poolId id of the rage trade pool @param swapParams parameters for swap @param wrapper VPoolWrapper to override the set wrapper @param protocol platform constants @return vTokenAmountOut - token amount coming out of pool @return vQuoteAmountOut - vQuote amount coming out of pool change direction basis uniswap to balance increase | function swapToken(
VTokenPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.SwapParams memory swapParams,
IVPoolWrapper wrapper,
Protocol.Info storage protocol
) internal returns (int256 vTokenAmountOut, int256 vQuoteAmountOut) {
IVPoolWrapper.SwapResult memory swapResult = wrapper.swap(
swapParams.amount < 0,
swapParams.isNotional ? swapParams.amount : -swapParams.amount,
swapParams.sqrtPriceLimit
);
vTokenAmountOut = -swapResult.vTokenIn;
vQuoteAmountOut = -swapResult.vQuoteIn;
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments = IClearingHouseStructures
.BalanceAdjustments(vQuoteAmountOut, vTokenAmountOut, vTokenAmountOut);
set.update(accountId, balanceAdjustments, poolId, protocol);
emit Account.TokenPositionChanged(
accountId,
poolId,
vTokenAmountOut,
vQuoteAmountOut,
swapResult.sqrtPriceX96Start,
swapResult.sqrtPriceX96End
);
}
| 14,079,356 | [
1,
5328,
6679,
2430,
261,
3708,
471,
7925,
13,
598,
810,
316,
1147,
3844,
342,
331,
10257,
3844,
225,
444,
776,
1345,
2555,
694,
225,
2845,
548,
612,
434,
326,
436,
410,
18542,
2845,
225,
7720,
1370,
1472,
364,
7720,
225,
4053,
776,
2864,
3611,
358,
3849,
326,
444,
4053,
225,
1771,
4072,
6810,
327,
331,
1345,
6275,
1182,
300,
1147,
3844,
19283,
596,
434,
2845,
327,
331,
10257,
6275,
1182,
300,
331,
10257,
3844,
19283,
596,
434,
2845,
2549,
4068,
10853,
640,
291,
91,
438,
358,
11013,
10929,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7720,
1345,
12,
203,
3639,
776,
1345,
2555,
18,
694,
2502,
444,
16,
203,
3639,
2254,
5034,
17398,
16,
203,
3639,
2254,
1578,
2845,
548,
16,
203,
3639,
467,
4756,
5968,
44,
3793,
3823,
1823,
18,
12521,
1370,
3778,
7720,
1370,
16,
203,
3639,
21602,
2864,
3611,
4053,
16,
203,
3639,
4547,
18,
966,
2502,
1771,
203,
565,
262,
2713,
1135,
261,
474,
5034,
331,
1345,
6275,
1182,
16,
509,
5034,
331,
10257,
6275,
1182,
13,
288,
203,
3639,
21602,
2864,
3611,
18,
12521,
1253,
3778,
7720,
1253,
273,
4053,
18,
22270,
12,
203,
5411,
7720,
1370,
18,
8949,
411,
374,
16,
203,
5411,
7720,
1370,
18,
291,
1248,
285,
287,
692,
7720,
1370,
18,
8949,
294,
300,
22270,
1370,
18,
8949,
16,
203,
5411,
7720,
1370,
18,
24492,
5147,
3039,
203,
3639,
11272,
203,
203,
3639,
331,
1345,
6275,
1182,
273,
300,
22270,
1253,
18,
90,
1345,
382,
31,
203,
3639,
331,
10257,
6275,
1182,
273,
300,
22270,
1253,
18,
90,
10257,
382,
31,
203,
203,
3639,
467,
4756,
5968,
44,
3793,
3823,
1823,
18,
13937,
10952,
1346,
3778,
11013,
10952,
1346,
273,
467,
4756,
5968,
44,
3793,
3823,
1823,
203,
5411,
263,
13937,
10952,
1346,
12,
90,
10257,
6275,
1182,
16,
331,
1345,
6275,
1182,
16,
331,
1345,
6275,
1182,
1769,
203,
203,
3639,
444,
18,
2725,
12,
25701,
16,
11013,
10952,
1346,
16,
2845,
548,
16,
1771,
1769,
203,
203,
3639,
3626,
6590,
18,
1345,
2555,
5033,
12,
203,
5411,
17398,
16,
203,
5411,
2845,
548,
16,
203,
5411,
2
] |
pragma solidity >=0.4.22 <0.7.0;
contract CReg {
// Contract creator address i.e the commissioner
address commissioner;
// Candidate information. This contains the name, mobile, nid,
// partyId(which contains all the party information) and the votes he/she gains.
struct Candidate {
bool isRegistered;
uint16 partyId;
bytes16 mobile;
bytes20 nid;
bytes20 region;
bytes32 name;
uint votes;
}
// Store the condidates to the nid => Candidate mapping.
mapping(bytes20 => Candidate) candidates;
// Store the nids for easy access.
bytes20[] nids;
constructor() public {
commissioner = msg.sender;
}
// Create modifier for election Commissioner only
modifier commissionerOnly {
require(commissioner == msg.sender, "This task only be done by election commissioner");
_;
}
// Check if the candidate is already registered.
function isAlreadyRegistered (bytes20 _nid) public view returns(bool) {
return candidates[_nid].isRegistered;
}
// Register a candidate. And this could be done only by commissioner.
function registerCandidate(bytes32 _name, bytes16 _mobile, bytes20 _nid, bytes20 _region, uint16 _partyId) public commissionerOnly{
require(!isAlreadyRegistered(_nid), "This candidate has already been registered!");
nids.push(_nid);
candidates[_nid] = Candidate({
name: _name,
mobile: _mobile,
nid: _nid,
region: _region,
partyId: _partyId,
isRegistered: true,
votes: 0
});
}
// Get all the candidates
function getCandidates() public view returns(bytes20[] memory) {
return nids;
}
// Get a specific candidate by NID.
function getCandidate(bytes20 _nid) public view returns(bytes32, bytes16, bytes20, uint16, uint) {
Candidate memory c = candidates[_nid];
return (c.name, c.mobile, c.region, c.partyId, c.votes);
}
function addVotesToTheAccount(bytes20[] memory _nids) public commissionerOnly {
for (uint i = 0; i < _nids.length; i++) {
candidates[_nids[i]].votes++;
}
}
function getCandidatesByRegion(bytes20 _region) public view returns(bytes20[] memory) {
bytes20[] memory can = new bytes20[](nids.length);
uint index = 0;
for (uint i = 0; i < nids.length; i++) {
if (candidates[nids[i]].region == _region) {
can[index] = nids[i];
index++;
}
}
return can;
}
} | Get all the candidates | function getCandidates() public view returns(bytes20[] memory) {
return nids;
}
| 14,123,610 | [
1,
967,
777,
326,
7965,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
1927,
12794,
1435,
1071,
1476,
1135,
12,
3890,
3462,
8526,
3778,
13,
288,
203,
3639,
327,
290,
2232,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x7D0E69c4Dc9463241281Ac8FABA245E1E6fDe53B/sources/SHIB2NFTS.sol | Minting Checks Minting Mint for caller Split cost | function mint(uint256 _mintAmount) public payable {
require(!paused, "Minting has not started yet");
require(_mintAmount > 0, "You have to mint at least one");
require(
_mintAmount <= maxMintAmount,
"You can only mint 10 at a time"
);
require(
lastSupply >= _mintAmount,
"Sold Out!"
);
if (msg.sender != owner()) {
require(
msg.value >= cost * _mintAmount,
"Cost Doesnt Match"
);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_randomMint(msg.sender);
handleMintReward(msg.value / _mintAmount);
}
}
| 3,599,750 | [
1,
49,
474,
310,
13074,
490,
474,
310,
490,
474,
364,
4894,
5385,
6991,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
312,
474,
12,
11890,
5034,
389,
81,
474,
6275,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
5,
8774,
3668,
16,
315,
49,
474,
310,
711,
486,
5746,
4671,
8863,
203,
3639,
2583,
24899,
81,
474,
6275,
405,
374,
16,
315,
6225,
1240,
358,
312,
474,
622,
4520,
1245,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
81,
474,
6275,
1648,
943,
49,
474,
6275,
16,
203,
5411,
315,
6225,
848,
1338,
312,
474,
1728,
622,
279,
813,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
1142,
3088,
1283,
1545,
389,
81,
474,
6275,
16,
203,
5411,
315,
55,
1673,
2976,
4442,
203,
3639,
11272,
203,
3639,
309,
261,
3576,
18,
15330,
480,
3410,
10756,
288,
203,
5411,
2583,
12,
203,
7734,
1234,
18,
1132,
1545,
6991,
380,
389,
81,
474,
6275,
16,
203,
7734,
315,
8018,
9637,
496,
4639,
6,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
364,
261,
11890,
5034,
277,
273,
404,
31,
277,
1648,
389,
81,
474,
6275,
31,
277,
27245,
288,
203,
5411,
389,
9188,
49,
474,
12,
3576,
18,
15330,
1769,
203,
5411,
1640,
49,
474,
17631,
1060,
12,
3576,
18,
1132,
342,
389,
81,
474,
6275,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xa46E47fB2847927a695e3110D5a0C88F1860422B/sources/contracts/coinexchange.sol | address public admin_address; | contract CoinExchange is Ownable {
mapping(address => bool) public whitelist;
event Exchange(address _user, uint256 _amount);
address _admin_address
pragma solidity ^0.8.9;
) {
admin_address = _admin_address;
}*/
function inCoins(address coin_contract, uint256 _amount) external {
IERC20 incoin = IERC20(coin_contract);
bool success = incoin.transferFrom(msg.sender, address(this), _amount);
require(success, "You need approve first!");
}
function setWhiteList(address white) external onlyOwner {
whitelist[white] = true;
}
function outCoins(address coin_contract, uint256 _amount) external {
require(whitelist[msg.sender] == true, "Your are bad guy!");
IERC20 outcoin = IERC20(coin_contract);
bool success = outcoin.transferFrom(address(this), msg.sender, _amount);
require(success, "You need approve first!");
}
event Received(address Sender, uint Value);
receive() external payable {
emit Received(msg.sender, msg.value);
}
} | 860,964 | [
1,
2867,
1071,
3981,
67,
2867,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
28932,
11688,
353,
14223,
6914,
288,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
10734,
31,
203,
203,
565,
871,
18903,
12,
2867,
389,
1355,
16,
2254,
5034,
389,
8949,
1769,
203,
203,
3639,
1758,
389,
3666,
67,
2867,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
565,
262,
288,
203,
3639,
3981,
67,
2867,
273,
389,
3666,
67,
2867,
31,
203,
565,
289,
5549,
203,
203,
565,
445,
14743,
9896,
12,
2867,
13170,
67,
16351,
16,
2254,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
467,
654,
39,
3462,
225,
7290,
885,
273,
467,
654,
39,
3462,
12,
12645,
67,
16351,
1769,
203,
3639,
1426,
2216,
273,
7290,
885,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
3639,
2583,
12,
4768,
16,
315,
6225,
1608,
6617,
537,
1122,
4442,
1769,
203,
565,
289,
203,
203,
565,
445,
444,
13407,
682,
12,
2867,
9578,
13,
3903,
1338,
5541,
288,
203,
3639,
10734,
63,
14739,
65,
273,
638,
31,
203,
565,
289,
203,
377,
203,
565,
445,
596,
39,
9896,
12,
2867,
13170,
67,
16351,
16,
2254,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
2583,
12,
20409,
63,
3576,
18,
15330,
65,
422,
638,
16,
315,
15446,
854,
5570,
3058,
93,
4442,
1769,
203,
203,
3639,
467,
654,
39,
3462,
225,
596,
12645,
273,
467,
654,
39,
3462,
12,
12645,
67,
16351,
1769,
203,
3639,
1426,
2216,
273,
596,
12645,
18,
13866,
1265,
12,
2867,
12,
2211,
2
] |
./full_match/1/0x57eFab8d8b62c890FBC56087D28240fe9549E42B/sources/contracts/BabylonCore.sol | listing ids start from 1st, not 0 collection address -> tokenId -> id of a listing id of a listing -> a listing info id of a listing -> a listing restrictions id of a listing -> participant address -> num of mint passes | contract BabylonCore is Initializable, IBabylonCore, OwnableUpgradeable, ReentrancyGuardUpgradeable {
ITokensController internal _tokensController;
IRandomProvider internal _randomProvider;
IEditionsExtension internal _editionsExtension;
string internal _mintPassBaseURI;
uint256 internal _lastListingId;
uint256 internal _maxListingDuration;
address internal _treasury;
mapping(address => mapping(uint256 => uint256)) internal _ids;
mapping(uint256 => ListingInfo) internal _listingInfos;
mapping(uint256 => ListingRestrictions) internal _listingRestrictions;
mapping(uint256 => mapping(address => uint256)) internal _participations;
uint256 public constant BASIS_POINTS = 10000;
event NewParticipant(uint256 listingId, address participant, uint256 ticketsAmount);
event ListingStarted(uint256 listingId, address creator, address token, uint256 tokenId, address mintPass);
event ListingResolving(uint256 listingId, uint256 randomRequestId);
event ListingSuccessful(uint256 listingId, address claimer);
event ListingCanceled(uint256 listingId);
event ListingFinalized(uint256 listingId);
event ListingRestrictionsUpdated(
uint256 indexed listingId,
bytes32 allowlistRoot,
uint256 reserved,
uint256 mintedFromReserve,
uint256 maxPerAddress
);
function initialize(
ITokensController tokensController,
IRandomProvider randomProvider,
IEditionsExtension editionsExtension,
address treasury
pragma solidity ^0.8.0;
) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
_tokensController = tokensController;
_randomProvider = randomProvider;
_editionsExtension = editionsExtension;
_maxListingDuration = 7 days;
_treasury = treasury;
transferOwnership(msg.sender);
}
function startListing(
ListingItem calldata item,
IEditionsExtension.EditionInfo calldata edition,
ListingRestrictions calldata restrictions,
uint256 timeStart,
uint256 price,
uint256 totalTickets,
uint256 donationBps
) external {
uint256 listingId = _ids[item.token][item.identifier];
if (listingId != 0) {
require(
_listingInfos[listingId].state != ListingState.Active &&
_listingInfos[listingId].state != ListingState.Resolving,
"BabylonCore: Active listing for this token already exists"
);
}
require(
_tokensController.checkApproval(msg.sender, item),
"BabylonCore: Token should be owned and approved to the controller"
);
require(totalTickets > 0, "BabylonCore: Number of tickets is too low");
require(donationBps <= BASIS_POINTS, "BabylonCore: Donation out of range");
require(
restrictions.reserved <= totalTickets &&
restrictions.maxPerAddress <= totalTickets,
"BabylonCore: Incorrect restrictions"
);
listingId = _lastListingId + 1;
address mintPass = _tokensController.createMintPass(listingId);
_editionsExtension.registerEdition(edition, msg.sender, listingId);
_ids[item.token][item.identifier] = listingId;
ListingInfo storage listing = _listingInfos[listingId];
listing.item = item;
listing.state = ListingState.Active;
listing.creator = msg.sender;
listing.mintPass = mintPass;
listing.price = price;
listing.timeStart = timeStart > block.timestamp ? timeStart : block.timestamp;
listing.totalTickets = totalTickets;
listing.donationBps = donationBps;
listing.creationTimestamp = block.timestamp;
ListingRestrictions storage listingRestrictions = _listingRestrictions[listingId];
listingRestrictions.allowlistRoot = restrictions.allowlistRoot;
listingRestrictions.reserved = restrictions.reserved;
listingRestrictions.maxPerAddress = restrictions.maxPerAddress;
_lastListingId = listingId;
emit ListingStarted(listingId, msg.sender, item.token, item.identifier, mintPass);
emit ListingRestrictionsUpdated(
listingId,
restrictions.allowlistRoot,
restrictions.reserved,
0,
restrictions.maxPerAddress
);
}
function startListing(
ListingItem calldata item,
IEditionsExtension.EditionInfo calldata edition,
ListingRestrictions calldata restrictions,
uint256 timeStart,
uint256 price,
uint256 totalTickets,
uint256 donationBps
) external {
uint256 listingId = _ids[item.token][item.identifier];
if (listingId != 0) {
require(
_listingInfos[listingId].state != ListingState.Active &&
_listingInfos[listingId].state != ListingState.Resolving,
"BabylonCore: Active listing for this token already exists"
);
}
require(
_tokensController.checkApproval(msg.sender, item),
"BabylonCore: Token should be owned and approved to the controller"
);
require(totalTickets > 0, "BabylonCore: Number of tickets is too low");
require(donationBps <= BASIS_POINTS, "BabylonCore: Donation out of range");
require(
restrictions.reserved <= totalTickets &&
restrictions.maxPerAddress <= totalTickets,
"BabylonCore: Incorrect restrictions"
);
listingId = _lastListingId + 1;
address mintPass = _tokensController.createMintPass(listingId);
_editionsExtension.registerEdition(edition, msg.sender, listingId);
_ids[item.token][item.identifier] = listingId;
ListingInfo storage listing = _listingInfos[listingId];
listing.item = item;
listing.state = ListingState.Active;
listing.creator = msg.sender;
listing.mintPass = mintPass;
listing.price = price;
listing.timeStart = timeStart > block.timestamp ? timeStart : block.timestamp;
listing.totalTickets = totalTickets;
listing.donationBps = donationBps;
listing.creationTimestamp = block.timestamp;
ListingRestrictions storage listingRestrictions = _listingRestrictions[listingId];
listingRestrictions.allowlistRoot = restrictions.allowlistRoot;
listingRestrictions.reserved = restrictions.reserved;
listingRestrictions.maxPerAddress = restrictions.maxPerAddress;
_lastListingId = listingId;
emit ListingStarted(listingId, msg.sender, item.token, item.identifier, mintPass);
emit ListingRestrictionsUpdated(
listingId,
restrictions.allowlistRoot,
restrictions.reserved,
0,
restrictions.maxPerAddress
);
}
function participate(
uint256 id,
uint256 tickets,
bytes32[] calldata allowlistProof
) external payable nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(
_tokensController.checkApproval(listing.creator, listing.item),
"BabylonCore: Token is no longer owned or approved to the controller"
);
require(block.timestamp >= listing.timeStart, "BabylonCore: Too early to participate");
uint256 current = listing.currentTickets;
require(current + tickets <= listing.totalTickets, "BabylonCore: No available tickets");
uint256 totalPrice = listing.price * tickets;
require(msg.value == totalPrice, "BabylonCore: msg.value doesn't match price for tickets");
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 participations = _participations[id][msg.sender] + tickets;
require(participations <= restrictions.maxPerAddress, "BabylonCore: Tickets exceed maxPerAddress");
_participations[id][msg.sender] = participations;
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
if (MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
uint256 allowlistLeft = restrictions.reserved - restrictions.mintedFromReserve;
if (allowlistLeft > 0) {
if (allowlistLeft <= tickets) {
restrictions.mintedFromReserve = restrictions.reserved;
restrictions.mintedFromReserve += tickets;
}
emit ListingRestrictionsUpdated(
id,
restrictions.allowlistRoot,
restrictions.reserved,
restrictions.mintedFromReserve,
restrictions.maxPerAddress
);
}
uint256 available = (listing.totalTickets + restrictions.mintedFromReserve) - current - restrictions.reserved;
require((available >= tickets), "BabylonCore: No available tickets outside the allowlist");
}
IBabylonMintPass(listing.mintPass).mint(msg.sender, tickets);
listing.currentTickets = current + tickets;
emit NewParticipant(id, msg.sender, tickets);
if (listing.currentTickets == listing.totalTickets) {
listing.randomRequestId = _randomProvider.requestRandom(id);
listing.state = ListingState.Resolving;
emit ListingResolving(id, listing.randomRequestId);
}
}
function participate(
uint256 id,
uint256 tickets,
bytes32[] calldata allowlistProof
) external payable nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(
_tokensController.checkApproval(listing.creator, listing.item),
"BabylonCore: Token is no longer owned or approved to the controller"
);
require(block.timestamp >= listing.timeStart, "BabylonCore: Too early to participate");
uint256 current = listing.currentTickets;
require(current + tickets <= listing.totalTickets, "BabylonCore: No available tickets");
uint256 totalPrice = listing.price * tickets;
require(msg.value == totalPrice, "BabylonCore: msg.value doesn't match price for tickets");
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 participations = _participations[id][msg.sender] + tickets;
require(participations <= restrictions.maxPerAddress, "BabylonCore: Tickets exceed maxPerAddress");
_participations[id][msg.sender] = participations;
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
if (MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
uint256 allowlistLeft = restrictions.reserved - restrictions.mintedFromReserve;
if (allowlistLeft > 0) {
if (allowlistLeft <= tickets) {
restrictions.mintedFromReserve = restrictions.reserved;
restrictions.mintedFromReserve += tickets;
}
emit ListingRestrictionsUpdated(
id,
restrictions.allowlistRoot,
restrictions.reserved,
restrictions.mintedFromReserve,
restrictions.maxPerAddress
);
}
uint256 available = (listing.totalTickets + restrictions.mintedFromReserve) - current - restrictions.reserved;
require((available >= tickets), "BabylonCore: No available tickets outside the allowlist");
}
IBabylonMintPass(listing.mintPass).mint(msg.sender, tickets);
listing.currentTickets = current + tickets;
emit NewParticipant(id, msg.sender, tickets);
if (listing.currentTickets == listing.totalTickets) {
listing.randomRequestId = _randomProvider.requestRandom(id);
listing.state = ListingState.Resolving;
emit ListingResolving(id, listing.randomRequestId);
}
}
function participate(
uint256 id,
uint256 tickets,
bytes32[] calldata allowlistProof
) external payable nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(
_tokensController.checkApproval(listing.creator, listing.item),
"BabylonCore: Token is no longer owned or approved to the controller"
);
require(block.timestamp >= listing.timeStart, "BabylonCore: Too early to participate");
uint256 current = listing.currentTickets;
require(current + tickets <= listing.totalTickets, "BabylonCore: No available tickets");
uint256 totalPrice = listing.price * tickets;
require(msg.value == totalPrice, "BabylonCore: msg.value doesn't match price for tickets");
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 participations = _participations[id][msg.sender] + tickets;
require(participations <= restrictions.maxPerAddress, "BabylonCore: Tickets exceed maxPerAddress");
_participations[id][msg.sender] = participations;
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
if (MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
uint256 allowlistLeft = restrictions.reserved - restrictions.mintedFromReserve;
if (allowlistLeft > 0) {
if (allowlistLeft <= tickets) {
restrictions.mintedFromReserve = restrictions.reserved;
restrictions.mintedFromReserve += tickets;
}
emit ListingRestrictionsUpdated(
id,
restrictions.allowlistRoot,
restrictions.reserved,
restrictions.mintedFromReserve,
restrictions.maxPerAddress
);
}
uint256 available = (listing.totalTickets + restrictions.mintedFromReserve) - current - restrictions.reserved;
require((available >= tickets), "BabylonCore: No available tickets outside the allowlist");
}
IBabylonMintPass(listing.mintPass).mint(msg.sender, tickets);
listing.currentTickets = current + tickets;
emit NewParticipant(id, msg.sender, tickets);
if (listing.currentTickets == listing.totalTickets) {
listing.randomRequestId = _randomProvider.requestRandom(id);
listing.state = ListingState.Resolving;
emit ListingResolving(id, listing.randomRequestId);
}
}
function participate(
uint256 id,
uint256 tickets,
bytes32[] calldata allowlistProof
) external payable nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(
_tokensController.checkApproval(listing.creator, listing.item),
"BabylonCore: Token is no longer owned or approved to the controller"
);
require(block.timestamp >= listing.timeStart, "BabylonCore: Too early to participate");
uint256 current = listing.currentTickets;
require(current + tickets <= listing.totalTickets, "BabylonCore: No available tickets");
uint256 totalPrice = listing.price * tickets;
require(msg.value == totalPrice, "BabylonCore: msg.value doesn't match price for tickets");
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 participations = _participations[id][msg.sender] + tickets;
require(participations <= restrictions.maxPerAddress, "BabylonCore: Tickets exceed maxPerAddress");
_participations[id][msg.sender] = participations;
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
if (MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
uint256 allowlistLeft = restrictions.reserved - restrictions.mintedFromReserve;
if (allowlistLeft > 0) {
if (allowlistLeft <= tickets) {
restrictions.mintedFromReserve = restrictions.reserved;
restrictions.mintedFromReserve += tickets;
}
emit ListingRestrictionsUpdated(
id,
restrictions.allowlistRoot,
restrictions.reserved,
restrictions.mintedFromReserve,
restrictions.maxPerAddress
);
}
uint256 available = (listing.totalTickets + restrictions.mintedFromReserve) - current - restrictions.reserved;
require((available >= tickets), "BabylonCore: No available tickets outside the allowlist");
}
IBabylonMintPass(listing.mintPass).mint(msg.sender, tickets);
listing.currentTickets = current + tickets;
emit NewParticipant(id, msg.sender, tickets);
if (listing.currentTickets == listing.totalTickets) {
listing.randomRequestId = _randomProvider.requestRandom(id);
listing.state = ListingState.Resolving;
emit ListingResolving(id, listing.randomRequestId);
}
}
} else {
} else {
function participate(
uint256 id,
uint256 tickets,
bytes32[] calldata allowlistProof
) external payable nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(
_tokensController.checkApproval(listing.creator, listing.item),
"BabylonCore: Token is no longer owned or approved to the controller"
);
require(block.timestamp >= listing.timeStart, "BabylonCore: Too early to participate");
uint256 current = listing.currentTickets;
require(current + tickets <= listing.totalTickets, "BabylonCore: No available tickets");
uint256 totalPrice = listing.price * tickets;
require(msg.value == totalPrice, "BabylonCore: msg.value doesn't match price for tickets");
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 participations = _participations[id][msg.sender] + tickets;
require(participations <= restrictions.maxPerAddress, "BabylonCore: Tickets exceed maxPerAddress");
_participations[id][msg.sender] = participations;
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
if (MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
uint256 allowlistLeft = restrictions.reserved - restrictions.mintedFromReserve;
if (allowlistLeft > 0) {
if (allowlistLeft <= tickets) {
restrictions.mintedFromReserve = restrictions.reserved;
restrictions.mintedFromReserve += tickets;
}
emit ListingRestrictionsUpdated(
id,
restrictions.allowlistRoot,
restrictions.reserved,
restrictions.mintedFromReserve,
restrictions.maxPerAddress
);
}
uint256 available = (listing.totalTickets + restrictions.mintedFromReserve) - current - restrictions.reserved;
require((available >= tickets), "BabylonCore: No available tickets outside the allowlist");
}
IBabylonMintPass(listing.mintPass).mint(msg.sender, tickets);
listing.currentTickets = current + tickets;
emit NewParticipant(id, msg.sender, tickets);
if (listing.currentTickets == listing.totalTickets) {
listing.randomRequestId = _randomProvider.requestRandom(id);
listing.state = ListingState.Resolving;
emit ListingResolving(id, listing.randomRequestId);
}
}
function updateListingRestrictions(uint256 id, ListingRestrictions calldata newRestrictions) external {
ListingInfo storage listing = _listingInfos[id];
uint256 totalTickets = listing.totalTickets;
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(msg.sender == listing.creator, "BabylonCore: Only the creator can update the restrictions");
ListingRestrictions storage restrictions = _listingRestrictions[id];
restrictions.allowlistRoot = newRestrictions.allowlistRoot;
uint256 reserveFloor = restrictions.mintedFromReserve;
uint256 reserveCeiling = (totalTickets - listing.currentTickets + restrictions.mintedFromReserve);
if (newRestrictions.reserved <= reserveCeiling) {
restrictions.reserved = newRestrictions.reserved <= reserveFloor ? reserveFloor : newRestrictions.reserved;
restrictions.reserved = reserveCeiling;
}
restrictions.maxPerAddress = newRestrictions.maxPerAddress >= totalTickets ?
totalTickets : newRestrictions.maxPerAddress;
emit ListingRestrictionsUpdated(
id,
restrictions.allowlistRoot,
restrictions.reserved,
restrictions.mintedFromReserve,
restrictions.maxPerAddress
);
}
function updateListingRestrictions(uint256 id, ListingRestrictions calldata newRestrictions) external {
ListingInfo storage listing = _listingInfos[id];
uint256 totalTickets = listing.totalTickets;
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(msg.sender == listing.creator, "BabylonCore: Only the creator can update the restrictions");
ListingRestrictions storage restrictions = _listingRestrictions[id];
restrictions.allowlistRoot = newRestrictions.allowlistRoot;
uint256 reserveFloor = restrictions.mintedFromReserve;
uint256 reserveCeiling = (totalTickets - listing.currentTickets + restrictions.mintedFromReserve);
if (newRestrictions.reserved <= reserveCeiling) {
restrictions.reserved = newRestrictions.reserved <= reserveFloor ? reserveFloor : newRestrictions.reserved;
restrictions.reserved = reserveCeiling;
}
restrictions.maxPerAddress = newRestrictions.maxPerAddress >= totalTickets ?
totalTickets : newRestrictions.maxPerAddress;
emit ListingRestrictionsUpdated(
id,
restrictions.allowlistRoot,
restrictions.reserved,
restrictions.mintedFromReserve,
restrictions.maxPerAddress
);
}
} else {
function settleListing(uint256 id) external {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(msg.sender == listing.creator, "BabylonCore: Only listing creator can settle listing");
require(listing.currentTickets > 0, "BabylonCore: Too few tickets to settle");
listing.randomRequestId = _randomProvider.requestRandom(id);
listing.state = ListingState.Resolving;
emit ListingResolving(id, listing.randomRequestId);
}
function cancelListing(uint256 id) external {
ListingInfo storage listing = _listingInfos[id];
if (listing.state == ListingState.Resolving) {
require(_randomProvider.isRequestOverdue(listing.randomRequestId), "BabylonCore: Random is not overdue");
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(msg.sender == listing.creator, "BabylonCore: Only listing creator can cancel active listing");
}
listing.state = ListingState.Canceled;
emit ListingCanceled(id);
}
function cancelListing(uint256 id) external {
ListingInfo storage listing = _listingInfos[id];
if (listing.state == ListingState.Resolving) {
require(_randomProvider.isRequestOverdue(listing.randomRequestId), "BabylonCore: Random is not overdue");
require(listing.state == ListingState.Active, "BabylonCore: Listing state should be active");
require(msg.sender == listing.creator, "BabylonCore: Only listing creator can cancel active listing");
}
listing.state = ListingState.Canceled;
emit ListingCanceled(id);
}
} else {
function transferETHToCreator(uint256 id) external nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Successful, "BabylonCore: Listing state should be successful");
bool sent;
uint256 creatorPayout = listing.currentTickets * listing.price;
uint256 donation = creatorPayout * listing.donationBps / BASIS_POINTS;
if (donation > 0) {
creatorPayout -= donation;
require(sent, "BabylonCore: Unable to send donation to the treasury");
}
if (creatorPayout > 0) {
require(sent, "BabylonCore: Unable to send ETH to the creator");
}
listing.state = ListingState.Finalized;
emit ListingFinalized(id);
}
function transferETHToCreator(uint256 id) external nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Successful, "BabylonCore: Listing state should be successful");
bool sent;
uint256 creatorPayout = listing.currentTickets * listing.price;
uint256 donation = creatorPayout * listing.donationBps / BASIS_POINTS;
if (donation > 0) {
creatorPayout -= donation;
require(sent, "BabylonCore: Unable to send donation to the treasury");
}
if (creatorPayout > 0) {
require(sent, "BabylonCore: Unable to send ETH to the creator");
}
listing.state = ListingState.Finalized;
emit ListingFinalized(id);
}
(sent, ) = payable(_treasury).call{value: donation}("");
function transferETHToCreator(uint256 id) external nonReentrant {
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Successful, "BabylonCore: Listing state should be successful");
bool sent;
uint256 creatorPayout = listing.currentTickets * listing.price;
uint256 donation = creatorPayout * listing.donationBps / BASIS_POINTS;
if (donation > 0) {
creatorPayout -= donation;
require(sent, "BabylonCore: Unable to send donation to the treasury");
}
if (creatorPayout > 0) {
require(sent, "BabylonCore: Unable to send ETH to the creator");
}
listing.state = ListingState.Finalized;
emit ListingFinalized(id);
}
(sent, ) = payable(listing.creator).call{value: creatorPayout}("");
function refund(uint256 id) external nonReentrant {
ListingInfo storage listing = _listingInfos[id];
if (
(
(listing.state == ListingState.Active || listing.state == ListingState.Resolving) &&
!_tokensController.checkApproval(listing.creator, listing.item)
) ||
(
listing.state == ListingState.Active &&
(listing.timeStart + _maxListingDuration <= block.timestamp)
)
) {
listing.state = ListingState.Canceled;
emit ListingCanceled(id);
}
require(listing.state == ListingState.Canceled, "BabylonCore: Listing state should be canceled to refund");
uint256 tickets = IBabylonMintPass(listing.mintPass).burn(msg.sender);
uint256 amount = tickets * listing.price;
require(sent, "BabylonCore: Unable to refund ETH");
}
function refund(uint256 id) external nonReentrant {
ListingInfo storage listing = _listingInfos[id];
if (
(
(listing.state == ListingState.Active || listing.state == ListingState.Resolving) &&
!_tokensController.checkApproval(listing.creator, listing.item)
) ||
(
listing.state == ListingState.Active &&
(listing.timeStart + _maxListingDuration <= block.timestamp)
)
) {
listing.state = ListingState.Canceled;
emit ListingCanceled(id);
}
require(listing.state == ListingState.Canceled, "BabylonCore: Listing state should be canceled to refund");
uint256 tickets = IBabylonMintPass(listing.mintPass).burn(msg.sender);
uint256 amount = tickets * listing.price;
require(sent, "BabylonCore: Unable to refund ETH");
}
(bool sent, ) = payable(msg.sender).call{value: amount}("");
function mintEdition(uint256 id) external {
ListingInfo storage listing = _listingInfos[id];
require(
listing.state == ListingState.Successful ||
listing.state == ListingState.Finalized,
"BabylonCore: Listing should be successful"
);
uint256 tickets = IBabylonMintPass(listing.mintPass).burn(msg.sender);
_editionsExtension.mintEdition(id, msg.sender, tickets);
}
function resolveClaimer(
uint256 id,
uint256 random
) external override {
require(msg.sender == address(_randomProvider), "BabylonCore: msg.sender is not the Random Provider");
ListingInfo storage listing = _listingInfos[id];
require(listing.state == ListingState.Resolving, "BabylonCore: Listing state should be resolving");
uint256 claimerIndex = random % listing.currentTickets;
address claimer = IBabylonMintPass(listing.mintPass).ownerOf(claimerIndex);
listing.claimer = claimer;
listing.state = ListingState.Successful;
_tokensController.sendItem(listing.item, listing.creator, claimer);
emit ListingSuccessful(id, claimer);
}
function setMaxListingDuration(uint256 maxListingDuration) external onlyOwner {
_maxListingDuration = maxListingDuration;
}
function setMintPassBaseURI(string calldata mintPassBaseURI) external onlyOwner {
_mintPassBaseURI = mintPassBaseURI;
}
function setTreasury(address treasury) external onlyOwner {
_treasury = treasury;
}
function getAvailableToParticipate(
uint256 id,
address user,
bytes32[] calldata allowlistProof
) external view returns (uint256) {
ListingInfo storage listing = _listingInfos[id];
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 current = listing.currentTickets;
uint256 total = listing.totalTickets;
uint256 available = total - current;
if (
(listing.state == ListingState.Active) &&
_tokensController.checkApproval(listing.creator, listing.item) &&
(block.timestamp >= listing.timeStart) &&
(available > 0) &&
(restrictions.maxPerAddress > _participations[id][user])
) {
uint256 leftForAddress = restrictions.maxPerAddress - _participations[id][user];
bytes32 leaf = keccak256(abi.encodePacked(user));
if (!MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
available = (total + restrictions.mintedFromReserve) - current - restrictions.reserved;
}
return available >= leftForAddress ? leftForAddress : available;
}
return 0;
}
function getAvailableToParticipate(
uint256 id,
address user,
bytes32[] calldata allowlistProof
) external view returns (uint256) {
ListingInfo storage listing = _listingInfos[id];
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 current = listing.currentTickets;
uint256 total = listing.totalTickets;
uint256 available = total - current;
if (
(listing.state == ListingState.Active) &&
_tokensController.checkApproval(listing.creator, listing.item) &&
(block.timestamp >= listing.timeStart) &&
(available > 0) &&
(restrictions.maxPerAddress > _participations[id][user])
) {
uint256 leftForAddress = restrictions.maxPerAddress - _participations[id][user];
bytes32 leaf = keccak256(abi.encodePacked(user));
if (!MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
available = (total + restrictions.mintedFromReserve) - current - restrictions.reserved;
}
return available >= leftForAddress ? leftForAddress : available;
}
return 0;
}
function getAvailableToParticipate(
uint256 id,
address user,
bytes32[] calldata allowlistProof
) external view returns (uint256) {
ListingInfo storage listing = _listingInfos[id];
ListingRestrictions storage restrictions = _listingRestrictions[id];
uint256 current = listing.currentTickets;
uint256 total = listing.totalTickets;
uint256 available = total - current;
if (
(listing.state == ListingState.Active) &&
_tokensController.checkApproval(listing.creator, listing.item) &&
(block.timestamp >= listing.timeStart) &&
(available > 0) &&
(restrictions.maxPerAddress > _participations[id][user])
) {
uint256 leftForAddress = restrictions.maxPerAddress - _participations[id][user];
bytes32 leaf = keccak256(abi.encodePacked(user));
if (!MerkleProof.verify(allowlistProof, restrictions.allowlistRoot, leaf)) {
available = (total + restrictions.mintedFromReserve) - current - restrictions.reserved;
}
return available >= leftForAddress ? leftForAddress : available;
}
return 0;
}
function getLastListingId() external view returns (uint256) {
return _lastListingId;
}
function getTreasury() external view returns (address) {
return _treasury;
}
function getListingId(address token, uint256 tokenId) external view returns (uint256) {
return _ids[token][tokenId];
}
function getListingInfo(uint256 id) external view returns (ListingInfo memory) {
return _listingInfos[id];
}
function getListingParticipations(uint256 id, address user) external view returns (uint256) {
return _participations[id][user];
}
function getListingRestrictions(uint256 id) external view returns (ListingRestrictions memory) {
return _listingRestrictions[id];
}
function getTokensController() external view returns (ITokensController) {
return _tokensController;
}
function getRandomProvider() external view returns (IRandomProvider) {
return _randomProvider;
}
function getEditionsExtension() external view returns (IEditionsExtension) {
return _editionsExtension;
}
function getMaxListingDuration() external view returns (uint256) {
return _maxListingDuration;
}
function getMintPassBaseURI() external view returns (string memory) {
return _mintPassBaseURI;
}
}
| 16,479,213 | [
1,
21228,
3258,
787,
628,
404,
334,
16,
486,
374,
1849,
1758,
317,
1147,
548,
317,
612,
434,
279,
11591,
612,
434,
279,
11591,
317,
279,
11591,
1123,
612,
434,
279,
11591,
317,
279,
11591,
17499,
612,
434,
279,
11591,
317,
14188,
1758,
317,
818,
434,
312,
474,
11656,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
605,
24383,
9379,
4670,
353,
10188,
6934,
16,
23450,
24383,
9379,
4670,
16,
14223,
6914,
10784,
429,
16,
868,
8230,
12514,
16709,
10784,
429,
288,
203,
565,
467,
5157,
2933,
2713,
389,
7860,
2933,
31,
203,
565,
467,
8529,
2249,
2713,
389,
9188,
2249,
31,
203,
565,
10897,
1460,
87,
3625,
2713,
389,
329,
5029,
3625,
31,
203,
565,
533,
2713,
389,
81,
474,
6433,
2171,
3098,
31,
203,
565,
2254,
5034,
2713,
389,
2722,
19081,
548,
31,
203,
565,
2254,
5034,
2713,
389,
1896,
19081,
5326,
31,
203,
203,
565,
1758,
2713,
389,
27427,
345,
22498,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
2713,
389,
2232,
31,
203,
565,
2874,
12,
11890,
5034,
516,
987,
27562,
13,
2713,
389,
21228,
7655,
31,
203,
565,
2874,
12,
11890,
5034,
516,
987,
310,
26175,
13,
2713,
389,
21228,
26175,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
2713,
389,
2680,
24629,
1012,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
28143,
15664,
67,
8941,
55,
273,
12619,
31,
203,
203,
565,
871,
1166,
22540,
12,
11890,
5034,
11591,
548,
16,
1758,
14188,
16,
2254,
5034,
24475,
6275,
1769,
203,
565,
871,
987,
310,
9217,
12,
11890,
5034,
11591,
548,
16,
1758,
11784,
16,
1758,
1147,
16,
2254,
5034,
1147,
548,
16,
1758,
312,
474,
6433,
1769,
203,
565,
871,
987,
310,
2903,
6282,
12,
11890,
5034,
11591,
548,
16,
2254,
5034,
2744,
15493,
1769,
203,
565,
871,
987,
2
] |
./partial_match/1/0xcFaa739f30a82041664C72569f4eFfC812dadd44/sources/RollToken.sol | Approve the max amount for the Dice Game contract
| _approve(user, diceGameAddress, type(uint256).max); | 15,498,095 | [
1,
12053,
537,
326,
943,
3844,
364,
326,
463,
1812,
14121,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
389,
12908,
537,
12,
1355,
16,
302,
1812,
12496,
1887,
16,
618,
12,
11890,
5034,
2934,
1896,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.7.0 <0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT;
contract SupplyChain {
uint256 pid = 0;
// SRUCTS
// Participant Struct
struct Participant {
string username;
string password;
string fullname;
string role;
string rating;
}
// Trace Struct
struct Trace {
string time;
string location;
string senderId;
string receiverId;
string encProperties;
}
// Product Struct
struct Product {
string productName;
string encProdProps;
int256[] parentId;
uint256[] childrenId;
string currentOwnerId;
string owner;
}
event childAdded(uint256 _child);
mapping(string => Participant) participant; // userId -> User Object
string[] participantIds;
mapping(string => string) loginDetails; // username -> hashed password mapping
mapping(string => uint256[]) productsOwned; // ParticipantId -> current products
mapping(uint256 => Trace[]) productTrace; // productId -> Trace array
mapping(uint256 => string[]) productError; // productId -> Error array
mapping(uint256 => Product) products; // productId -> Product Object
// UTILITY FUNCTIONS
function compareStrings(string memory a, string memory b)
public
pure
returns (bool)
{
return (keccak256(abi.encodePacked((a))) ==
keccak256(abi.encodePacked((b))));
}
modifier onlyOwner(string memory _senderId, uint256 _productId) {
// require(products[_productId].currentOwnerId == _senderId, "Its not yours");
require(
compareStrings(products[_productId].currentOwnerId, _senderId),
"You dont own this product"
);
_;
}
// VIEW FUNCTIONS
function getErrors(uint _pid) public view returns(string[] memory) {
return productError[_pid];
}
function getProductsOwned(string memory _id)
public
view
returns (uint256[] memory)
{
return (productsOwned[_id]);
}
function getLoginDetails(string memory _username)
public
view
returns (string memory)
{
return (loginDetails[_username]);
}
function getParticipant(string memory _id)
public
view
returns (Participant memory)
{
return (participant[_id]);
}
function getProduct(uint256 _pid) public view returns (Product memory) {
return (products[_pid]);
}
function isOwner (string memory _senderId, uint256 _productId) public view returns(bool) {
if(compareStrings(products[_productId].currentOwnerId, _senderId) == true){
return true;
}
else{
return false;
}
}
function getTrace(uint _pid) public view returns(Trace[] memory) {
return productTrace[_pid];
}
function getAllParticipants() public view returns(Participant[] memory){
Participant[] memory allParticipants = new Participant[](participantIds.length);
for (uint256 j = 0; j< participantIds.length; j++){
allParticipants[j]=participant[participantIds[j]];
}
return allParticipants;
}
// IMPORTANT FUNCTIONS
function addParticipant(
string memory _username,
string memory _password,
string memory _fullname,
string memory _role,
string memory hashedId
) public returns (string memory) {
Participant memory p = Participant(
_username,
_password,
_fullname,
_role,
"0#0"
);
string memory uid = hashedId;
participant[uid] = p;
participantIds.push(uid);
loginDetails[_username] = _password;
return (uid);
}
function addProduct(
string memory _productName,
int256[] memory _parentId,
uint256[] memory _childrenId,
string memory _currentOwnerId,
string memory _encProdProps // encoded product properties
) public returns (uint256) {
Product memory p;
p.productName = _productName;
p.parentId = _parentId;
p.childrenId = _childrenId;
p.currentOwnerId = _currentOwnerId;
p.encProdProps = _encProdProps;
// productTrace[pid+1].push(Trace(_time, _location, _currentOwnerId, _newOwnerId));
for (uint256 j = 0; j < _parentId.length; j++) {
if (_parentId[j] != -1) {
// require(products[uint(_parentId[j])].currentOwnerId == _currentOwnerId, "You dont own this product");
require(
compareStrings(
products[uint256(_parentId[j])].currentOwnerId,
_currentOwnerId
),
"You dont own this product"
);
products[uint256(_parentId[j])].childrenId.push(pid + 1);
}
}
productsOwned[_currentOwnerId].push(pid + 1);
products[++pid] = p;
emit childAdded(pid);
return pid;
}
function setError(uint _productId, string memory _errors) public {
productError[_productId].push(_errors);
}
function setEncProps(uint _productId, string memory _encProductProps) public {
Product memory p = getProduct(_productId);
p.encProdProps = _encProductProps;
products[_productId] = p;
}
function setRating(string memory _username, string memory _newRating) public {
Participant memory p = getParticipant(_username);
p.rating = _newRating;
participant[_username] = p;
}
function TransferOwnership(
string memory _senderId,
string memory _receiverId,
uint256 _productId,
string memory _location,
string memory _time,
string memory _encProps
) public onlyOwner(_senderId, _productId) {
// Update Trace array
productTrace[_productId].push(
Trace(_time, _location, _senderId, _receiverId, _encProps)
);
// update products owned
removeFromOwner(_senderId, _productId);
productsOwned[_receiverId].push(_productId);
// Change owner
products[_productId].currentOwnerId = _receiverId;
}
function deleteProducts(
uint256[] memory _childrenIds,
string memory _ownerId
) public {
for (uint256 i = 0; i < _childrenIds.length; i++) {
// remove from productsOwned
removeFromOwner(_ownerId, _childrenIds[i]);
//remove from parents
for (
uint256 j = 0;
j < products[_childrenIds[i]].parentId.length;
j++
) {
// maybe change later
bool flag = false;
Product memory p = products[uint256(
products[_childrenIds[i]].parentId[j]
)];
for (uint256 k = 0; k < p.childrenId.length - 1; k++) {
if (p.childrenId[k] == _childrenIds[i]) {
flag = true;
}
if (flag) {
p.childrenId[k] = p.childrenId[k + 1];
}
}
products[uint256(products[_childrenIds[i]].parentId[j])] = p;
products[uint256(products[_childrenIds[i]].parentId[j])]
.childrenId
.pop();
}
//remove from products
delete products[_childrenIds[i]];
}
}
function addToOwner(uint256 _parentId, string memory _ownerId) public {
//where is this used??
// require(products[_parentId].currentOwnerId == _ownerId, "The old product was not yours");
require(
compareStrings(products[_parentId].currentOwnerId, _ownerId),
"The old product was not yours"
);
productsOwned[_ownerId].push(_parentId);
}
function removeFromOwner(string memory _ownerId, uint256 _productId)
public
onlyOwner(_ownerId, _productId)
{
bool flag = false;
for (uint256 i = 0; i < productsOwned[_ownerId].length - 1; i++) {
if (productsOwned[_ownerId][i] == _productId) {
flag = true;
}
if (flag) {
productsOwned[_ownerId][i] = productsOwned[_ownerId][i + 1];
}
}
productsOwned[_ownerId].pop();
}
}
| productId -> Trace array
| mapping(uint256 => Trace[]) productTrace; | 12,635,265 | [
1,
5896,
548,
317,
2677,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
5034,
516,
2677,
63,
5717,
3017,
3448,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
abstract contract BaseERC721 is ERC721Enumerable, ERC721Pausable, Ownable, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string private __baseURI;
string private _contractURI;
uint256 public mintLimit;
uint256 public numberMinted;
string constant MINT_LIMIT_REACHED = ""; // "mint limit reacted";
string constant SENDER_MUST_BE_MINTER = ""; // "Caller not minter";
constructor (
string memory name,
string memory symbol,
uint256 __mintLimit,
string memory baseURI,
string memory __contractURI
) ERC721(name, symbol) {
_setupRole(MINTER_ROLE, msg.sender);
mintLimit = __mintLimit;
__baseURI = baseURI;
_contractURI = __contractURI;
}
// Opensea custom method
function contractURI() public view returns (string memory) {
return _contractURI;
}
function _baseURI() internal view override(ERC721) returns (string memory) {
return __baseURI;
}
modifier onlyMinter {
require(_isMinter(), SENDER_MUST_BE_MINTER);
_;
}
function _isMinter() internal view returns(bool) {
return hasRole(MINTER_ROLE, msg.sender);
}
function _isOwner(uint256 _tokenId) internal view returns(bool) {
return msg.sender == ownerOf(_tokenId);
}
function _mint() internal virtual onlyMinter returns (uint256) {
require(numberMinted < mintLimit, MINT_LIMIT_REACHED);
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
ERC721._safeMint(msg.sender, tokenId);
numberMinted++;
return tokenId;
}
function _buy(uint256 tokenId) internal {
ERC721._approve(msg.sender, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual
override(ERC721, ERC721Enumerable, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
| "Caller not minter";
| string constant SENDER_MUST_BE_MINTER = ""; | 6,439,849 | [
1,
6,
11095,
486,
1131,
387,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
533,
5381,
348,
22457,
67,
49,
5996,
67,
5948,
67,
6236,
2560,
273,
1408,
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
] |
pragma solidity 0.6.6;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@kyber.network/utils-sc/contracts/Utils.sol";
import "../IKyberFeeHandler.sol";
import "../IKyberDao.sol";
import "./WithdrawableNoModifiers.sol";
import "./IKyberNetwork.sol";
import "./IKyberReserve.sol";
import "./IKyberMatchingEngine.sol";
import "./IKyberStorage.sol";
import "./IGasHelper.sol";
/**
* @title kyberNetwork main contract
* Interacts with contracts:
* kyberDao: to retrieve fee data
* kyberFeeHandler: accumulates and distributes trade fees
* kyberMatchingEngine: parse user hint and run reserve matching algorithm
* kyberStorage: store / access reserves, token listings and contract addresses
* kyberReserve(s): query rate and trade
*/
contract KyberNetwork is WithdrawableNoModifiers, Utils, IKyberNetwork, ReentrancyGuard {
using SafeERC20 for IERC20Ext;
struct NetworkFeeData {
uint64 expiryTimestamp;
uint16 feeBps;
}
/// @notice Stores work data for reserves (either for token -> eth, or eth -> token)
/// @dev Variables are in-place, ie. reserve with addresses[i] has id of ids[i], offers rate of rates[i], etc.
/// @param addresses List of reserve addresses selected for the trade
/// @param ids List of reserve ids, to be used for KyberTrade event
/// @param rates List of rates that were offered by the reserves
/// @param isFeeAccountedFlags List of reserves requiring users to pay network fee
/// @param isEntitledRebateFlags List of reserves eligible for rebates
/// @param splitsBps List of proportions of trade amount allocated to the reserves.
/// If there is only 1 reserve, then it should have a value of 10000 bps
/// @param srcAmounts Source amount per reserve.
/// @param decimals Token decimals. Src decimals when for src -> eth, dest decimals when eth -> dest
struct ReservesData {
IKyberReserve[] addresses;
bytes32[] ids;
uint256[] rates;
bool[] isFeeAccountedFlags;
bool[] isEntitledRebateFlags;
uint256[] splitsBps;
uint256[] srcAmounts;
uint256 decimals;
}
/// @notice Main trade data structure, is initialised and used for the entire trade flow
/// @param input Initialised when initTradeInput is called. Stores basic trade info
/// @param tokenToEth Stores information about reserves that were selected for src -> eth side of trade
/// @param ethToToken Stores information about reserves that were selected for eth -> dest side of trade
/// @param tradeWei Trade amount in ether wei, before deducting fees.
/// @param networkFeeWei Network fee in ether wei. For t2t trades, it can go up to 200% of networkFeeBps
/// @param platformFeeWei Platform fee in ether wei
/// @param networkFeeBps Network fee bps determined by kyberDao, or default value
/// @param numEntitledRebateReserves No. of reserves that are eligible for rebates
/// @param feeAccountedBps Proportion of this trade that fee is accounted to, in BPS. Up to 2 * BPS
struct TradeData {
TradeInput input;
ReservesData tokenToEth;
ReservesData ethToToken;
uint256 tradeWei;
uint256 networkFeeWei;
uint256 platformFeeWei;
uint256 networkFeeBps;
uint256 numEntitledRebateReserves;
uint256 feeAccountedBps; // what part of this trade is fee paying. for token -> token - up to 200%
}
struct TradeInput {
address payable trader;
IERC20Ext src;
uint256 srcAmount;
IERC20Ext dest;
address payable destAddress;
uint256 maxDestAmount;
uint256 minConversionRate;
address platformWallet;
uint256 platformFeeBps;
}
uint256 internal constant PERM_HINT_GET_RATE = 1 << 255; // for backwards compatibility
uint256 internal constant DEFAULT_NETWORK_FEE_BPS = 25; // till we read value from kyberDao
uint256 internal constant MAX_APPROVED_PROXIES = 2; // limit number of proxies that can trade here
IKyberFeeHandler internal kyberFeeHandler;
IKyberDao internal kyberDao;
IKyberMatchingEngine internal kyberMatchingEngine;
IKyberStorage internal kyberStorage;
IGasHelper internal gasHelper;
NetworkFeeData internal networkFeeData; // data is feeBps and expiry timestamp
uint256 internal maxGasPriceValue = 50 * 1000 * 1000 * 1000; // 50 gwei
bool internal isEnabled = false; // is network enabled
mapping(address => bool) internal kyberProxyContracts;
event EtherReceival(address indexed sender, uint256 amount);
event KyberFeeHandlerUpdated(IKyberFeeHandler newKyberFeeHandler);
event KyberMatchingEngineUpdated(IKyberMatchingEngine newKyberMatchingEngine);
event GasHelperUpdated(IGasHelper newGasHelper);
event KyberDaoUpdated(IKyberDao newKyberDao);
event KyberNetworkParamsSet(uint256 maxGasPrice, uint256 negligibleRateDiffBps);
event KyberNetworkSetEnable(bool isEnabled);
event KyberProxyAdded(address kyberProxy);
event KyberProxyRemoved(address kyberProxy);
event ListedReservesForToken(
IERC20Ext indexed token,
address[] reserves,
bool add
);
constructor(address _admin, IKyberStorage _kyberStorage)
public
WithdrawableNoModifiers(_admin)
{
updateNetworkFee(now, DEFAULT_NETWORK_FEE_BPS);
kyberStorage = _kyberStorage;
}
receive() external payable {
emit EtherReceival(msg.sender, msg.value);
}
/// @notice Backward compatible function
/// @notice Use token address ETH_TOKEN_ADDRESS for ether
/// @dev Trade from src to dest token and sends dest token to destAddress
/// @param trader Address of the taker side of this trade
/// @param src Source token
/// @param srcAmount Amount of src tokens in twei
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens in twei
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts
/// @param walletId Platform wallet address for receiving fees
/// @param hint Advanced instructions for running the trade
/// @return destAmount Amount of actual dest tokens in twei
function tradeWithHint(
address payable trader,
IERC20Ext src,
uint256 srcAmount,
IERC20Ext dest,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable walletId,
bytes calldata hint
) external payable returns (uint256 destAmount) {
TradeData memory tradeData = initTradeInput({
trader: trader,
src: src,
dest: dest,
srcAmount: srcAmount,
destAddress: destAddress,
maxDestAmount: maxDestAmount,
minConversionRate: minConversionRate,
platformWallet: walletId,
platformFeeBps: 0
});
return trade(tradeData, hint);
}
/// @notice Use token address ETH_TOKEN_ADDRESS for ether
/// @dev Trade from src to dest token and sends dest token to destAddress
/// @param trader Address of the taker side of this trade
/// @param src Source token
/// @param srcAmount Amount of src tokens in twei
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens in twei
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts
/// @param platformWallet Platform wallet address for receiving fees
/// @param platformFeeBps Part of the trade that is allocated as fee to platform wallet. Ex: 1000 = 10%
/// @param hint Advanced instructions for running the trade
/// @return destAmount Amount of actual dest tokens in twei
function tradeWithHintAndFee(
address payable trader,
IERC20Ext src,
uint256 srcAmount,
IERC20Ext dest,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable platformWallet,
uint256 platformFeeBps,
bytes calldata hint
) external payable override returns (uint256 destAmount) {
TradeData memory tradeData = initTradeInput({
trader: trader,
src: src,
dest: dest,
srcAmount: srcAmount,
destAddress: destAddress,
maxDestAmount: maxDestAmount,
minConversionRate: minConversionRate,
platformWallet: platformWallet,
platformFeeBps: platformFeeBps
});
return trade(tradeData, hint);
}
/// @notice Can be called only by kyberStorage
/// @dev Allow or prevent to trade token -> eth for a reserve
/// @param reserve The reserve address
/// @param token Token address
/// @param add If true, then give reserve token allowance, otherwise set zero allowance
function listTokenForReserve(
address reserve,
IERC20Ext token,
bool add
) external override {
require(msg.sender == address(kyberStorage), "only kyberStorage");
if (add) {
token.safeApprove(reserve, MAX_ALLOWANCE);
getSetDecimals(token);
} else {
token.safeApprove(reserve, 0);
}
}
/// @notice Can be called only by operator
/// @dev Allow or prevent to trade token -> eth for list of reserves
/// Useful for migration to new network contract
/// Call storage to get list of reserves supporting token -> eth
/// @param token Token address
/// @param startIndex start index in reserves list
/// @param endIndex end index in reserves list (can be larger)
/// @param add If true, then give reserve token allowance, otherwise set zero allowance
function listReservesForToken(
IERC20Ext token,
uint256 startIndex,
uint256 endIndex,
bool add
) external {
onlyOperator();
if (startIndex > endIndex) {
// no need to do anything
return;
}
address[] memory reserves = kyberStorage.getReserveAddressesPerTokenSrc(
token, startIndex, endIndex
);
if (reserves.length == 0) {
// no need to do anything
return;
}
for(uint i = 0; i < reserves.length; i++) {
if (add) {
token.safeApprove(reserves[i], MAX_ALLOWANCE);
getSetDecimals(token);
} else {
token.safeApprove(reserves[i], 0);
}
}
emit ListedReservesForToken(token, reserves, add);
}
function setContracts(
IKyberFeeHandler _kyberFeeHandler,
IKyberMatchingEngine _kyberMatchingEngine,
IGasHelper _gasHelper
) external virtual {
onlyAdmin();
if (kyberFeeHandler != _kyberFeeHandler) {
kyberFeeHandler = _kyberFeeHandler;
emit KyberFeeHandlerUpdated(_kyberFeeHandler);
}
if (kyberMatchingEngine != _kyberMatchingEngine) {
kyberMatchingEngine = _kyberMatchingEngine;
emit KyberMatchingEngineUpdated(_kyberMatchingEngine);
}
if ((_gasHelper != IGasHelper(0)) && (_gasHelper != gasHelper)) {
gasHelper = _gasHelper;
emit GasHelperUpdated(_gasHelper);
}
kyberStorage.setContracts(address(_kyberFeeHandler), address(_kyberMatchingEngine));
require(_kyberFeeHandler != IKyberFeeHandler(0));
require(_kyberMatchingEngine != IKyberMatchingEngine(0));
}
function setKyberDaoContract(IKyberDao _kyberDao) external {
// enable setting null kyberDao address
onlyAdmin();
if (kyberDao != _kyberDao) {
kyberDao = _kyberDao;
kyberStorage.setKyberDaoContract(address(_kyberDao));
emit KyberDaoUpdated(_kyberDao);
}
}
function setParams(uint256 _maxGasPrice, uint256 _negligibleRateDiffBps) external {
onlyAdmin();
maxGasPriceValue = _maxGasPrice;
kyberMatchingEngine.setNegligibleRateDiffBps(_negligibleRateDiffBps);
emit KyberNetworkParamsSet(maxGasPriceValue, _negligibleRateDiffBps);
}
function setEnable(bool enable) external {
onlyAdmin();
if (enable) {
require(kyberFeeHandler != IKyberFeeHandler(0));
require(kyberMatchingEngine != IKyberMatchingEngine(0));
require(kyberStorage.isKyberProxyAdded());
}
isEnabled = enable;
emit KyberNetworkSetEnable(isEnabled);
}
/// @dev No. of kyberProxies is capped
function addKyberProxy(address kyberProxy) external virtual {
onlyAdmin();
kyberStorage.addKyberProxy(kyberProxy, MAX_APPROVED_PROXIES);
require(kyberProxy != address(0));
require(!kyberProxyContracts[kyberProxy]);
kyberProxyContracts[kyberProxy] = true;
emit KyberProxyAdded(kyberProxy);
}
function removeKyberProxy(address kyberProxy) external virtual {
onlyAdmin();
kyberStorage.removeKyberProxy(kyberProxy);
require(kyberProxyContracts[kyberProxy]);
kyberProxyContracts[kyberProxy] = false;
emit KyberProxyRemoved(kyberProxy);
}
/// @dev gets the expected rates when trading src -> dest token, with / without fees
/// @param src Source token
/// @param dest Destination token
/// @param srcQty Amount of src tokens in twei
/// @param platformFeeBps Part of the trade that is allocated as fee to platform wallet. Ex: 1000 = 10%
/// @param hint Advanced instructions for running the trade
/// @return rateWithNetworkFee Rate after deducting network fee but excluding platform fee
/// @return rateWithAllFees = actual rate. Rate after accounting for both network and platform fees
function getExpectedRateWithHintAndFee(
IERC20Ext src,
IERC20Ext dest,
uint256 srcQty,
uint256 platformFeeBps,
bytes calldata hint
)
external
view
override
returns (
uint256 rateWithNetworkFee,
uint256 rateWithAllFees
)
{
if (src == dest) return (0, 0);
TradeData memory tradeData = initTradeInput({
trader: payable(address(0)),
src: src,
dest: dest,
srcAmount: (srcQty == 0) ? 1 : srcQty,
destAddress: payable(address(0)),
maxDestAmount: 2**255,
minConversionRate: 0,
platformWallet: payable(address(0)),
platformFeeBps: platformFeeBps
});
tradeData.networkFeeBps = getNetworkFee();
uint256 destAmount;
(destAmount, rateWithNetworkFee) = calcRatesAndAmounts(tradeData, hint);
rateWithAllFees = calcRateFromQty(
tradeData.input.srcAmount,
destAmount,
tradeData.tokenToEth.decimals,
tradeData.ethToToken.decimals
);
}
/// @notice Backward compatible API
/// @dev Gets the expected and slippage rate for exchanging src -> dest token
/// @dev worstRate is hardcoded to be 3% lower of expectedRate
/// @param src Source token
/// @param dest Destination token
/// @param srcQty Amount of src tokens in twei
/// @return expectedRate for a trade after deducting network fee.
/// @return worstRate for a trade. Calculated to be expectedRate * 97 / 100
function getExpectedRate(
IERC20Ext src,
IERC20Ext dest,
uint256 srcQty
) external view returns (uint256 expectedRate, uint256 worstRate) {
if (src == dest) return (0, 0);
uint256 qty = srcQty & ~PERM_HINT_GET_RATE;
TradeData memory tradeData = initTradeInput({
trader: payable(address(0)),
src: src,
dest: dest,
srcAmount: (qty == 0) ? 1 : qty,
destAddress: payable(address(0)),
maxDestAmount: 2**255,
minConversionRate: 0,
platformWallet: payable(address(0)),
platformFeeBps: 0
});
tradeData.networkFeeBps = getNetworkFee();
(, expectedRate) = calcRatesAndAmounts(tradeData, "");
worstRate = (expectedRate * 97) / 100; // backward compatible formula
}
/// @notice Returns some data about the network
/// @param negligibleDiffBps Negligible rate difference (in basis pts) when searching best rate
/// @param networkFeeBps Network fees to be charged (in basis pts)
/// @param expiryTimestamp Timestamp for which networkFeeBps will expire,
/// and needs to be updated by calling kyberDao contract / set to default
function getNetworkData()
external
view
override
returns (
uint256 negligibleDiffBps,
uint256 networkFeeBps,
uint256 expiryTimestamp
)
{
(networkFeeBps, expiryTimestamp) = readNetworkFeeData();
negligibleDiffBps = kyberMatchingEngine.getNegligibleRateDiffBps();
return (negligibleDiffBps, networkFeeBps, expiryTimestamp);
}
function getContracts()
external
view
returns (
IKyberFeeHandler kyberFeeHandlerAddress,
IKyberDao kyberDaoAddress,
IKyberMatchingEngine kyberMatchingEngineAddress,
IKyberStorage kyberStorageAddress,
IGasHelper gasHelperAddress,
IKyberNetworkProxy[] memory kyberProxyAddresses
)
{
return (
kyberFeeHandler,
kyberDao,
kyberMatchingEngine,
kyberStorage,
gasHelper,
kyberStorage.getKyberProxies()
);
}
/// @notice returns the max gas price allowable for trades
function maxGasPrice() external view override returns (uint256) {
return maxGasPriceValue;
}
/// @notice returns status of the network. If disabled, trades cannot happen.
function enabled() external view override returns (bool) {
return isEnabled;
}
/// @notice Gets network fee from the kyberDao (or use default).
/// For trade function, so that data can be updated and cached.
/// @dev Note that this function can be triggered by anyone, so that
/// the first trader of a new epoch can avoid incurring extra gas costs
function getAndUpdateNetworkFee() public returns (uint256 networkFeeBps) {
uint256 expiryTimestamp;
(networkFeeBps, expiryTimestamp) = readNetworkFeeData();
if (expiryTimestamp < now && kyberDao != IKyberDao(0)) {
(networkFeeBps, expiryTimestamp) = kyberDao.getLatestNetworkFeeDataWithCache();
updateNetworkFee(expiryTimestamp, networkFeeBps);
}
}
/// @notice Calculates platform fee and reserve rebate percentages for the trade.
/// Transfers eth and rebate wallet data to kyberFeeHandler
function handleFees(TradeData memory tradeData) internal {
uint256 sentFee = tradeData.networkFeeWei + tradeData.platformFeeWei;
//no need to handle fees if total fee is zero
if (sentFee == 0)
return;
// update reserve eligibility and rebate percentages
(
address[] memory rebateWallets,
uint256[] memory rebatePercentBps
) = calculateRebates(tradeData);
// send total fee amount to fee handler with reserve data
kyberFeeHandler.handleFees{value: sentFee}(
ETH_TOKEN_ADDRESS,
rebateWallets,
rebatePercentBps,
tradeData.input.platformWallet,
tradeData.platformFeeWei,
tradeData.networkFeeWei
);
}
function updateNetworkFee(uint256 expiryTimestamp, uint256 feeBps) internal {
require(expiryTimestamp < 2**64, "expiry overflow");
require(feeBps < BPS / 2, "fees exceed BPS");
networkFeeData.expiryTimestamp = uint64(expiryTimestamp);
networkFeeData.feeBps = uint16(feeBps);
}
/// @notice Use token address ETH_TOKEN_ADDRESS for ether
/// @dev Do one trade with each reserve in reservesData, verifying network balance
/// as expected to ensure reserves take correct src amount
/// @param src Source token
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reservesData reservesData to trade
/// @param expectedDestAmount Amount to be transferred to destAddress
/// @param srcDecimals Decimals of source token
/// @param destDecimals Decimals of destination token
function doReserveTrades(
IERC20Ext src,
IERC20Ext dest,
address payable destAddress,
ReservesData memory reservesData,
uint256 expectedDestAmount,
uint256 srcDecimals,
uint256 destDecimals
) internal virtual {
if (src == dest) {
// eth -> eth, need not do anything except for token -> eth: transfer eth to destAddress
if (destAddress != (address(this))) {
(bool success, ) = destAddress.call{value: expectedDestAmount}("");
require(success, "send dest qty failed");
}
return;
}
tradeAndVerifyNetworkBalance(
reservesData,
src,
dest,
srcDecimals,
destDecimals
);
if (destAddress != address(this)) {
// for eth -> token / token -> token, transfer tokens to destAddress
dest.safeTransfer(destAddress, expectedDestAmount);
}
}
/// @dev call trade from reserves and verify balances
/// @param reservesData reservesData to trade
/// @param src Source token of trade
/// @param dest Destination token of trade
/// @param srcDecimals Decimals of source token
/// @param destDecimals Decimals of destination token
function tradeAndVerifyNetworkBalance(
ReservesData memory reservesData,
IERC20Ext src,
IERC20Ext dest,
uint256 srcDecimals,
uint256 destDecimals
) internal
{
// only need to verify src balance if src is not eth
uint256 srcBalanceBefore = (src == ETH_TOKEN_ADDRESS) ? 0 : getBalance(src, address(this));
uint256 destBalanceBefore = getBalance(dest, address(this));
for(uint256 i = 0; i < reservesData.addresses.length; i++) {
uint256 callValue = (src == ETH_TOKEN_ADDRESS) ? reservesData.srcAmounts[i] : 0;
require(
reservesData.addresses[i].trade{value: callValue}(
src,
reservesData.srcAmounts[i],
dest,
address(this),
reservesData.rates[i],
true
),
"reserve trade failed"
);
uint256 balanceAfter;
if (src != ETH_TOKEN_ADDRESS) {
// verify src balance only if it is not eth
balanceAfter = getBalance(src, address(this));
// verify correct src amount is taken
if (srcBalanceBefore >= balanceAfter && srcBalanceBefore - balanceAfter > reservesData.srcAmounts[i]) {
revert("reserve takes high amount");
}
srcBalanceBefore = balanceAfter;
}
// verify correct dest amount is received
uint256 expectedDestAmount = calcDstQty(
reservesData.srcAmounts[i],
srcDecimals,
destDecimals,
reservesData.rates[i]
);
balanceAfter = getBalance(dest, address(this));
if (balanceAfter < destBalanceBefore || balanceAfter - destBalanceBefore < expectedDestAmount) {
revert("reserve returns low amount");
}
destBalanceBefore = balanceAfter;
}
}
/// @notice Use token address ETH_TOKEN_ADDRESS for ether
/// @dev Trade API for kyberNetwork
/// @param tradeData Main trade data object for trade info to be stored
function trade(TradeData memory tradeData, bytes memory hint)
internal
virtual
nonReentrant
returns (uint256 destAmount)
{
tradeData.networkFeeBps = getAndUpdateNetworkFee();
validateTradeInput(tradeData.input);
uint256 rateWithNetworkFee;
(destAmount, rateWithNetworkFee) = calcRatesAndAmounts(tradeData, hint);
require(rateWithNetworkFee > 0, "trade invalid, if hint involved, try parseHint API");
require(rateWithNetworkFee < MAX_RATE, "rate > MAX_RATE");
require(rateWithNetworkFee >= tradeData.input.minConversionRate, "rate < min rate");
uint256 actualSrcAmount;
if (destAmount > tradeData.input.maxDestAmount) {
// notice tradeData passed by reference and updated
destAmount = tradeData.input.maxDestAmount;
actualSrcAmount = calcTradeSrcAmountFromDest(tradeData);
} else {
actualSrcAmount = tradeData.input.srcAmount;
}
// token -> eth
doReserveTrades(
tradeData.input.src,
ETH_TOKEN_ADDRESS,
address(this),
tradeData.tokenToEth,
tradeData.tradeWei,
tradeData.tokenToEth.decimals,
ETH_DECIMALS
);
// eth -> token
doReserveTrades(
ETH_TOKEN_ADDRESS,
tradeData.input.dest,
tradeData.input.destAddress,
tradeData.ethToToken,
destAmount,
ETH_DECIMALS,
tradeData.ethToToken.decimals
);
handleChange(
tradeData.input.src,
tradeData.input.srcAmount,
actualSrcAmount,
tradeData.input.trader
);
handleFees(tradeData);
emit KyberTrade({
src: tradeData.input.src,
dest: tradeData.input.dest,
ethWeiValue: tradeData.tradeWei,
networkFeeWei: tradeData.networkFeeWei,
customPlatformFeeWei: tradeData.platformFeeWei,
t2eIds: tradeData.tokenToEth.ids,
e2tIds: tradeData.ethToToken.ids,
t2eSrcAmounts: tradeData.tokenToEth.srcAmounts,
e2tSrcAmounts: tradeData.ethToToken.srcAmounts,
t2eRates: tradeData.tokenToEth.rates,
e2tRates: tradeData.ethToToken.rates
});
if (gasHelper != IGasHelper(0)) {
(bool success, ) = address(gasHelper).call(
abi.encodeWithSignature(
"freeGas(address,address,address,uint256,bytes32[],bytes32[])",
tradeData.input.platformWallet,
tradeData.input.src,
tradeData.input.dest,
tradeData.tradeWei,
tradeData.tokenToEth.ids,
tradeData.ethToToken.ids
)
);
// remove compilation warning
success;
}
return (destAmount);
}
/// @notice If user maxDestAmount < actual dest amount, actualSrcAmount will be < srcAmount
/// Calculate the change, and send it back to the user
function handleChange(
IERC20Ext src,
uint256 srcAmount,
uint256 requiredSrcAmount,
address payable trader
) internal {
if (requiredSrcAmount < srcAmount) {
// if there is "change" send back to trader
if (src == ETH_TOKEN_ADDRESS) {
(bool success, ) = trader.call{value: (srcAmount - requiredSrcAmount)}("");
require(success, "Send change failed");
} else {
src.safeTransfer(trader, (srcAmount - requiredSrcAmount));
}
}
}
function initTradeInput(
address payable trader,
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable platformWallet,
uint256 platformFeeBps
) internal view returns (TradeData memory tradeData) {
tradeData.input.trader = trader;
tradeData.input.src = src;
tradeData.input.srcAmount = srcAmount;
tradeData.input.dest = dest;
tradeData.input.destAddress = destAddress;
tradeData.input.maxDestAmount = maxDestAmount;
tradeData.input.minConversionRate = minConversionRate;
tradeData.input.platformWallet = platformWallet;
tradeData.input.platformFeeBps = platformFeeBps;
tradeData.tokenToEth.decimals = getDecimals(src);
tradeData.ethToToken.decimals = getDecimals(dest);
}
/// @notice This function does all calculations to find trade dest amount without accounting
/// for maxDestAmount. Part of this process includes:
/// - Call kyberMatchingEngine to parse hint and get an optional reserve list to trade.
/// - Query reserve rates and call kyberMatchingEngine to use best reserve.
/// - Calculate trade values and fee values.
/// This function should set all TradeData information so that it can be later used without
/// any ambiguity
/// @param tradeData Main trade data object for trade info to be stored
/// @param hint Advanced user instructions for the trade
function calcRatesAndAmounts(TradeData memory tradeData, bytes memory hint)
internal
view
returns (uint256 destAmount, uint256 rateWithNetworkFee)
{
validateFeeInput(tradeData.input, tradeData.networkFeeBps);
// token -> eth: find best reserves match and calculate wei amount
tradeData.tradeWei = calcDestQtyAndMatchReserves(
tradeData.input.src,
ETH_TOKEN_ADDRESS,
tradeData.input.srcAmount,
tradeData,
tradeData.tokenToEth,
hint
);
require(tradeData.tradeWei <= MAX_QTY, "Trade wei > MAX_QTY");
if (tradeData.tradeWei == 0) {
return (0, 0);
}
// calculate fees
tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS;
tradeData.networkFeeWei =
(((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /
BPS;
assert(tradeData.tradeWei >= (tradeData.networkFeeWei + tradeData.platformFeeWei));
// eth -> token: find best reserves match and calculate trade dest amount
uint256 actualSrcWei = tradeData.tradeWei -
tradeData.networkFeeWei -
tradeData.platformFeeWei;
destAmount = calcDestQtyAndMatchReserves(
ETH_TOKEN_ADDRESS,
tradeData.input.dest,
actualSrcWei,
tradeData,
tradeData.ethToToken,
hint
);
tradeData.networkFeeWei =
(((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /
BPS;
rateWithNetworkFee = calcRateFromQty(
tradeData.input.srcAmount * (BPS - tradeData.input.platformFeeBps) / BPS,
destAmount,
tradeData.tokenToEth.decimals,
tradeData.ethToToken.decimals
);
}
/// @notice Get trading reserves, source amounts, and calculate dest qty
/// Store information into tradeData
function calcDestQtyAndMatchReserves(
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
TradeData memory tradeData,
ReservesData memory reservesData,
bytes memory hint
) internal view returns (uint256 destAmount) {
if (src == dest) {
return srcAmount;
}
IKyberMatchingEngine.ProcessWithRate processWithRate;
// get reserve list from kyberMatchingEngine
(reservesData.ids, reservesData.splitsBps, processWithRate) =
kyberMatchingEngine.getTradingReserves(
src,
dest,
(tradeData.input.src != ETH_TOKEN_ADDRESS) && (tradeData.input.dest != ETH_TOKEN_ADDRESS),
hint
);
bool areAllReservesListed;
(areAllReservesListed, reservesData.isFeeAccountedFlags, reservesData.isEntitledRebateFlags, reservesData.addresses)
= kyberStorage.getReservesData(reservesData.ids, src, dest);
if(!areAllReservesListed) {
return 0;
}
require(reservesData.ids.length == reservesData.splitsBps.length, "bad split array");
require(reservesData.ids.length == reservesData.isFeeAccountedFlags.length, "bad fee array");
require(reservesData.ids.length == reservesData.isEntitledRebateFlags.length, "bad rebate array");
require(reservesData.ids.length == reservesData.addresses.length, "bad addresses array");
// calculate src trade amount per reserve and query rates
// set data in reservesData struct
uint256[] memory feesAccountedDestBps = calcSrcAmountsAndGetRates(
reservesData,
src,
dest,
srcAmount,
tradeData
);
// if matching engine requires processing with rate data. call doMatch and update reserve list
if (processWithRate == IKyberMatchingEngine.ProcessWithRate.Required) {
uint256[] memory selectedIndexes = kyberMatchingEngine.doMatch(
src,
dest,
reservesData.srcAmounts,
feesAccountedDestBps,
reservesData.rates
);
updateReservesList(reservesData, selectedIndexes);
}
// calculate dest amount and fee paying data of this part (t2e or e2t)
destAmount = validateTradeCalcDestQtyAndFeeData(src, reservesData, tradeData);
}
/// @notice Calculates source amounts per reserve. Does get rate call
function calcSrcAmountsAndGetRates(
ReservesData memory reservesData,
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
TradeData memory tradeData
) internal view returns (uint256[] memory feesAccountedDestBps) {
uint256 numReserves = reservesData.ids.length;
uint256 srcAmountAfterFee;
uint256 destAmountFeeBps;
if (src == ETH_TOKEN_ADDRESS) {
// @notice srcAmount is after deducting fees from tradeWei
// @notice using tradeWei to calculate fee so eth -> token symmetric to token -> eth
srcAmountAfterFee = srcAmount -
(tradeData.tradeWei * tradeData.networkFeeBps / BPS);
} else {
srcAmountAfterFee = srcAmount;
destAmountFeeBps = tradeData.networkFeeBps;
}
reservesData.srcAmounts = new uint256[](numReserves);
reservesData.rates = new uint256[](numReserves);
feesAccountedDestBps = new uint256[](numReserves);
// iterate reserve list. validate data. calculate srcAmount according to splits and fee data.
for (uint256 i = 0; i < numReserves; i++) {
require(
reservesData.splitsBps[i] > 0 && reservesData.splitsBps[i] <= BPS,
"invalid split bps"
);
if (reservesData.isFeeAccountedFlags[i]) {
reservesData.srcAmounts[i] = srcAmountAfterFee * reservesData.splitsBps[i] / BPS;
feesAccountedDestBps[i] = destAmountFeeBps;
} else {
reservesData.srcAmounts[i] = (srcAmount * reservesData.splitsBps[i]) / BPS;
}
// get rate with calculated src amount
reservesData.rates[i] = reservesData.addresses[i].getConversionRate(
src,
dest,
reservesData.srcAmounts[i],
block.number
);
}
}
function calculateRebates(TradeData memory tradeData)
internal
view
returns (address[] memory rebateWallets, uint256[] memory rebatePercentBps)
{
rebateWallets = new address[](tradeData.numEntitledRebateReserves);
rebatePercentBps = new uint256[](tradeData.numEntitledRebateReserves);
if (tradeData.numEntitledRebateReserves == 0) {
return (rebateWallets, rebatePercentBps);
}
uint256 index;
bytes32[] memory rebateReserveIds = new bytes32[](tradeData.numEntitledRebateReserves);
// token -> eth
index = createRebateEntitledList(
rebateReserveIds,
rebatePercentBps,
tradeData.tokenToEth,
index,
tradeData.feeAccountedBps
);
// eth -> token
createRebateEntitledList(
rebateReserveIds,
rebatePercentBps,
tradeData.ethToToken,
index,
tradeData.feeAccountedBps
);
rebateWallets = kyberStorage.getRebateWalletsFromIds(rebateReserveIds);
}
function createRebateEntitledList(
bytes32[] memory rebateReserveIds,
uint256[] memory rebatePercentBps,
ReservesData memory reservesData,
uint256 index,
uint256 feeAccountedBps
) internal pure returns (uint256) {
uint256 _index = index;
for (uint256 i = 0; i < reservesData.isEntitledRebateFlags.length; i++) {
if (reservesData.isEntitledRebateFlags[i]) {
rebateReserveIds[_index] = reservesData.ids[i];
rebatePercentBps[_index] = (reservesData.splitsBps[i] * BPS) / feeAccountedBps;
_index++;
}
}
return _index;
}
/// @dev Checks a trade input validity, including correct src amounts
/// @param input Trade input structure
function validateTradeInput(TradeInput memory input) internal view
{
require(isEnabled, "network disabled");
require(kyberProxyContracts[msg.sender], "bad sender");
require(tx.gasprice <= maxGasPriceValue, "gas price");
require(input.srcAmount <= MAX_QTY, "srcAmt > MAX_QTY");
require(input.srcAmount != 0, "0 srcAmt");
require(input.destAddress != address(0), "dest add 0");
require(input.src != input.dest, "src = dest");
if (input.src == ETH_TOKEN_ADDRESS) {
require(msg.value == input.srcAmount); // kyberProxy issues message here
} else {
require(msg.value == 0); // kyberProxy issues message here
// funds should have been moved to this contract already.
require(input.src.balanceOf(address(this)) >= input.srcAmount, "no tokens");
}
}
/// @notice Gets the network fee from kyberDao (or use default). View function for getExpectedRate
function getNetworkFee() internal view returns (uint256 networkFeeBps) {
uint256 expiryTimestamp;
(networkFeeBps, expiryTimestamp) = readNetworkFeeData();
if (expiryTimestamp < now && kyberDao != IKyberDao(0)) {
(networkFeeBps, expiryTimestamp) = kyberDao.getLatestNetworkFeeData();
}
}
function readNetworkFeeData() internal view returns (uint256 feeBps, uint256 expiryTimestamp) {
feeBps = uint256(networkFeeData.feeBps);
expiryTimestamp = uint256(networkFeeData.expiryTimestamp);
}
/// @dev Checks fee input validity, including correct src amounts
/// @param input Trade input structure
/// @param networkFeeBps Network fee in bps.
function validateFeeInput(TradeInput memory input, uint256 networkFeeBps) internal pure {
require(input.platformFeeBps < BPS, "platformFee high");
require(input.platformFeeBps + networkFeeBps + networkFeeBps < BPS, "fees high");
}
/// @notice Update reserve data with selected reserves from kyberMatchingEngine
function updateReservesList(ReservesData memory reservesData, uint256[] memory selectedIndexes)
internal
pure
{
uint256 numReserves = selectedIndexes.length;
require(numReserves <= reservesData.addresses.length, "doMatch: too many reserves");
IKyberReserve[] memory reserveAddresses = new IKyberReserve[](numReserves);
bytes32[] memory reserveIds = new bytes32[](numReserves);
uint256[] memory splitsBps = new uint256[](numReserves);
bool[] memory isFeeAccountedFlags = new bool[](numReserves);
bool[] memory isEntitledRebateFlags = new bool[](numReserves);
uint256[] memory srcAmounts = new uint256[](numReserves);
uint256[] memory rates = new uint256[](numReserves);
// update participating resevres and all data (rates, srcAmounts, feeAcounted etc.)
for (uint256 i = 0; i < numReserves; i++) {
reserveAddresses[i] = reservesData.addresses[selectedIndexes[i]];
reserveIds[i] = reservesData.ids[selectedIndexes[i]];
splitsBps[i] = reservesData.splitsBps[selectedIndexes[i]];
isFeeAccountedFlags[i] = reservesData.isFeeAccountedFlags[selectedIndexes[i]];
isEntitledRebateFlags[i] = reservesData.isEntitledRebateFlags[selectedIndexes[i]];
srcAmounts[i] = reservesData.srcAmounts[selectedIndexes[i]];
rates[i] = reservesData.rates[selectedIndexes[i]];
}
// update values
reservesData.addresses = reserveAddresses;
reservesData.ids = reserveIds;
reservesData.splitsBps = splitsBps;
reservesData.isFeeAccountedFlags = isFeeAccountedFlags;
reservesData.isEntitledRebateFlags = isEntitledRebateFlags;
reservesData.rates = rates;
reservesData.srcAmounts = srcAmounts;
}
/// @notice Verify split values bps and reserve ids,
/// then calculate the destQty from srcAmounts and rates
/// @dev Each split bps must be in range (0, BPS]
/// @dev Total split bps must be 100%
/// @dev Reserve ids must be increasing
function validateTradeCalcDestQtyAndFeeData(
IERC20Ext src,
ReservesData memory reservesData,
TradeData memory tradeData
) internal pure returns (uint256 totalDestAmount) {
uint256 totalBps;
uint256 srcDecimals = (src == ETH_TOKEN_ADDRESS) ? ETH_DECIMALS : reservesData.decimals;
uint256 destDecimals = (src == ETH_TOKEN_ADDRESS) ? reservesData.decimals : ETH_DECIMALS;
for (uint256 i = 0; i < reservesData.addresses.length; i++) {
if (i > 0 && (uint256(reservesData.ids[i]) <= uint256(reservesData.ids[i - 1]))) {
return 0; // ids are not in increasing order
}
totalBps += reservesData.splitsBps[i];
uint256 destAmount = calcDstQty(
reservesData.srcAmounts[i],
srcDecimals,
destDecimals,
reservesData.rates[i]
);
if (destAmount == 0) {
return 0;
}
totalDestAmount += destAmount;
if (reservesData.isFeeAccountedFlags[i]) {
tradeData.feeAccountedBps += reservesData.splitsBps[i];
if (reservesData.isEntitledRebateFlags[i]) {
tradeData.numEntitledRebateReserves++;
}
}
}
if (totalBps != BPS) {
return 0;
}
}
/// @notice Recalculates tradeWei, network and platform fees, and actual source amount needed for the trade
/// in the event actualDestAmount > maxDestAmount
function calcTradeSrcAmountFromDest(TradeData memory tradeData)
internal
pure
virtual
returns (uint256 actualSrcAmount)
{
uint256 weiAfterDeductingFees;
if (tradeData.input.dest != ETH_TOKEN_ADDRESS) {
weiAfterDeductingFees = calcTradeSrcAmount(
tradeData.tradeWei - tradeData.platformFeeWei - tradeData.networkFeeWei,
ETH_DECIMALS,
tradeData.ethToToken.decimals,
tradeData.input.maxDestAmount,
tradeData.ethToToken
);
} else {
weiAfterDeductingFees = tradeData.input.maxDestAmount;
}
// reverse calculation, because we are working backwards
uint256 newTradeWei =
(weiAfterDeductingFees * BPS * BPS) /
((BPS * BPS) -
(tradeData.networkFeeBps *
tradeData.feeAccountedBps +
tradeData.input.platformFeeBps *
BPS));
tradeData.tradeWei = minOf(newTradeWei, tradeData.tradeWei);
// recalculate network and platform fees based on tradeWei
tradeData.networkFeeWei =
(((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /
BPS;
tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS;
if (tradeData.input.src != ETH_TOKEN_ADDRESS) {
actualSrcAmount = calcTradeSrcAmount(
tradeData.input.srcAmount,
tradeData.tokenToEth.decimals,
ETH_DECIMALS,
tradeData.tradeWei,
tradeData.tokenToEth
);
} else {
actualSrcAmount = tradeData.tradeWei;
}
assert(actualSrcAmount <= tradeData.input.srcAmount);
}
/// @notice Recalculates srcAmounts and stores into tradingReserves, given the new destAmount.
/// Uses the original proportion of srcAmounts and rates to determine new split destAmounts,
/// then calculate the respective srcAmounts
/// @dev Due to small rounding errors, will fallback to current src amounts if new src amount is greater
function calcTradeSrcAmount(
uint256 srcAmount,
uint256 srcDecimals,
uint256 destDecimals,
uint256 destAmount,
ReservesData memory reservesData
) internal pure returns (uint256 newSrcAmount) {
uint256 totalWeightedDestAmount;
for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) {
totalWeightedDestAmount += reservesData.srcAmounts[i] * reservesData.rates[i];
}
uint256[] memory newSrcAmounts = new uint256[](reservesData.srcAmounts.length);
uint256 destAmountSoFar;
uint256 currentSrcAmount;
uint256 destAmountSplit;
for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) {
currentSrcAmount = reservesData.srcAmounts[i];
require(destAmount * currentSrcAmount * reservesData.rates[i] / destAmount ==
currentSrcAmount * reservesData.rates[i],
"multiplication overflow");
destAmountSplit = i == (reservesData.srcAmounts.length - 1)
? (destAmount - destAmountSoFar)
: (destAmount * currentSrcAmount * reservesData.rates[i]) /
totalWeightedDestAmount;
destAmountSoFar += destAmountSplit;
newSrcAmounts[i] = calcSrcQty(
destAmountSplit,
srcDecimals,
destDecimals,
reservesData.rates[i]
);
if (newSrcAmounts[i] > currentSrcAmount) {
// revert back to use current src amounts
return srcAmount;
}
newSrcAmount += newSrcAmounts[i];
}
// new src amounts are used only when all of them aren't greater then current srcAmounts
reservesData.srcAmounts = newSrcAmounts;
}
}
| new src amounts are used only when all of them aren't greater then current srcAmounts | reservesData.srcAmounts = newSrcAmounts;
| 5,532,836 | [
1,
2704,
1705,
30980,
854,
1399,
1338,
1347,
777,
434,
2182,
11526,
1404,
6802,
1508,
783,
1705,
6275,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
400,
264,
3324,
751,
18,
4816,
6275,
87,
273,
394,
7740,
6275,
87,
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
] |
/*
Copyright 2020 Freq Set Dollar <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Setters.sol";
import "../external/Require.sol";
contract Comptroller is Setters {
using SafeMath for uint256;
bytes32 private constant FILE = "Comptroller";
function mintToAccount(address account, uint256 amount) internal {
dollar().mint(account, amount);
if (!bootstrappingAt(epoch())) {
increaseDebt(amount);
}
balanceCheck();
}
function burnFromAccount(address account, uint256 amount) internal {
dollar().transferFrom(account, address(this), amount);
dollar().burn(amount);
decrementTotalDebt(amount, "Comptroller: not enough outstanding debt");
balanceCheck();
}
function redeemToAccount(address account, uint256 amount) internal {
dollar().transfer(account, amount);
decrementTotalRedeemable(amount, "Comptroller: not enough redeemable balance");
balanceCheck();
}
function burnRedeemable(uint256 amount) internal {
dollar().burn(amount);
decrementTotalRedeemable(amount, "Comptroller: not enough redeemable balance");
balanceCheck();
}
function increaseDebt(uint256 amount) internal {
incrementTotalDebt(amount);
resetDebt(Constants.getDebtRatioCap());
balanceCheck();
}
function decreaseDebt(uint256 amount) internal {
decrementTotalDebt(amount, "Comptroller: not enough debt");
balanceCheck();
}
function increaseSupply(uint256 newSupply) internal returns (uint256, uint256, uint256, uint256) {
(uint256 newCouponRedeemable, uint256 lessDebt, uint256 poolReward, uint256 newBondRedeemable) = (0, 0, 0, 0);
//1. Pay out to Pool
poolReward = newSupply.mul(Constants.getOraclePoolRatio()).div(100);
mintToPool(poolReward);
newSupply = newSupply > poolReward ? newSupply.sub(poolReward) : 0;
//2. Pay out to Bond & Coupon
if (totalBondRedeemable() < totalBonds() || totalRedeemable() < totalCoupons()){
newBondRedeemable = totalBondRedeemable() < totalBonds() ? totalBonds().sub(totalBondRedeemable()) : 0;
newCouponRedeemable = totalRedeemable() < totalCoupons() ? totalCoupons().sub(totalRedeemable()) : 0;
uint256 bondSupply = newSupply.mul(Constants.getBondPoolRatio()).div(100); //bondSupply = newSupply * BOND_POOL_SHARE%
uint256 couponSupply = newSupply.mul(SafeMath.sub(100,Constants.getBondPoolRatio())).div(100); //couponSupply = newSupply * (1-BOND_POOL_SHARE%)
// If Bond supply is not enough, redeem coupon first, and all remaining supply go to bond
if (bondSupply < newBondRedeemable) {
if(newCouponRedeemable > 0){
newCouponRedeemable = newCouponRedeemable > couponSupply ? couponSupply : newCouponRedeemable;
mintToRedeemable(newCouponRedeemable);
newSupply = newSupply.sub(newCouponRedeemable);
}
if(newBondRedeemable > 0){
newBondRedeemable = newBondRedeemable > newSupply ? newSupply : newBondRedeemable; // all remaining supply to bond
mintToBondRedeemable(newBondRedeemable);
newSupply = newSupply.sub(newBondRedeemable);
}
// Otherwiase, redeem bond first, and all remaining supply go to coupon
} else {
if(newBondRedeemable > 0){
newBondRedeemable = newBondRedeemable > bondSupply ? bondSupply : newBondRedeemable;
mintToBondRedeemable(newBondRedeemable);
newSupply = newSupply.sub(newBondRedeemable);
}
if(newCouponRedeemable > 0){
newCouponRedeemable = newCouponRedeemable > newSupply ? newSupply : newCouponRedeemable; // all remaining supply to coupon
mintToRedeemable(newCouponRedeemable);
newSupply = newSupply.sub(newCouponRedeemable);
}
}
}
//4. Payout to Dao
if (totalBonded() == 0) {
newSupply = 0;
}
if (newSupply > 0) {
mintToDAO(newSupply);
}
return (newCouponRedeemable, lessDebt, newSupply.add(poolReward), newBondRedeemable);
}
function resetDebt(Decimal.D256 memory targetDebtRatio) internal {
uint256 targetDebt = targetDebtRatio.mul(dollar().totalSupply()).asUint256();
uint256 currentDebt = totalDebt();
if (currentDebt > targetDebt) {
uint256 lessDebt = currentDebt.sub(targetDebt);
decreaseDebt(lessDebt);
}
}
function balanceCheck() internal {
Require.that(
dollar().balanceOf(address(this)) >= totalBonded().add(totalStaged()).add(totalRedeemable()).add(totalBondRedeemable()),
FILE,
"Inconsistent balances"
);
}
function mintToBonded(uint256 amount) private {
Require.that(
totalBonded() > 0,
FILE,
"Cant mint to empty pool"
);
uint256 poolAmount = amount.mul(Constants.getOraclePoolRatio()).div(100);
uint256 daoAmount = amount > poolAmount ? amount.sub(poolAmount) : 0;
mintToPool(poolAmount);
mintToDAO(daoAmount);
balanceCheck();
}
function mintToDAO(uint256 amount) private {
if (amount > 0) {
dollar().mint(address(this), amount);
incrementTotalBonded(amount);
}
}
function mintToPool(uint256 amount) private {
if (amount > 0) {
dollar().mint(pool(), amount);
}
}
function mintToRedeemable(uint256 amount) private {
dollar().mint(address(this), amount);
incrementTotalRedeemable(amount);
balanceCheck();
}
// bonds logic
function mintToBondRedeemable(uint256 amount) private {
dollar().mint(address(this), amount);
incrementTotalBondRedeemable(amount);
balanceCheck();
}
}
| all remaining supply to bond
| newBondRedeemable = newBondRedeemable > newSupply ? newSupply : newBondRedeemable; | 981,007 | [
1,
454,
4463,
14467,
358,
8427,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10792,
394,
9807,
426,
24903,
429,
273,
394,
9807,
426,
24903,
429,
405,
394,
3088,
1283,
692,
394,
3088,
1283,
294,
394,
9807,
426,
24903,
429,
31,
6647,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
pragma experimental ABIEncoderV2;
interface IUniswap {
// To convert DAI to ETH
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
// To convert ETH to YELD and burn it
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);
}
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);
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address payable private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address payable) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public 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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
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 _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function 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;
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
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 != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Compound {
function mint ( uint256 mintAmount ) external returns ( uint256 );
function redeem(uint256 redeemTokens) external returns (uint256);
function exchangeRateStored() external view returns (uint);
}
interface Fulcrum {
function mint(address receiver, uint256 amount) external payable returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid);
function assetBalanceOf(address _owner) external view returns (uint256 balance);
}
interface ILendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}
interface Aave {
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external;
}
interface AToken {
function redeem(uint256 amount) external;
}
interface IIEarnManager {
function recommend(address _token) external view returns (
string memory choice,
uint256 capr,
uint256 iapr,
uint256 aapr,
uint256 dapr
);
}
contract Structs {
struct Val {
uint256 value;
}
enum ActionType {
Deposit, // supply tokens
Withdraw // borrow tokens
}
enum AssetDenomination {
Wei // the amount is denominated in wei
}
enum AssetReference {
Delta // the amount is given as a delta from the current value
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
contract DyDx is Structs {
function getAccountWei(Info memory account, uint256 marketId) public view returns (Wei memory);
function operate(Info[] memory, ActionArgs[] memory) public;
}
interface LendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getLendingPoolCore() external view returns (address);
}
contract yDAI is ERC20, ERC20Detailed, ReentrancyGuard, Structs, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
uint256 public pool;
address public token;
address public compound;
address public fulcrum;
address public aave;
address public aavePool;
address public aaveToken;
address public dydx;
uint256 public dToken;
address public apr;
address public chai;
// Add other tokens if implemented for another stablecoin
address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public retirementYeldTreasury;
IERC20 public yeldToken;
uint256 public maximumTokensToBurn = 50000 * 1e18;
// When you stake say 1000 DAI for a day that will be your maximum
// if you stake the next time 300 DAI your maximum will stay the same
// if you stake 2000 at once it will increase to 2000 DAI
mapping(bytes32 => uint256) public numberOfParticipants;
mapping(address => uint256) public depositBlockStarts;
uint256 public constant oneDayInBlocks = 6500;
uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility
uint256 public constant oneMillion = 1e6;
enum Lender {
NONE,
DYDX,
COMPOUND,
AAVE,
FULCRUM
}
Lender public provider = Lender.NONE;
constructor (address _yeldToken, address payable _retirementYeldTreasury) public payable ERC20Detailed("yearn DAI", "yDAI", 18) {
token = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8);
dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
aavePool = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3);
fulcrum = address(0x493C57C4763932315A328269E1ADaD09653B9081);
aaveToken = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
compound = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
chai = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
dToken = 3;
yeldToken = IERC20(_yeldToken);
retirementYeldTreasury = _retirementYeldTreasury;
approveToken();
}
// To receive ETH after converting it from DAI
function () external payable {}
function setRetirementYeldTreasury(address payable _treasury) public onlyOwner {
retirementYeldTreasury = _treasury;
}
// In case a new uniswap router version is released
function setUniswapRouter(address _uniswapRouter) public onlyOwner {
uniswapRouter = _uniswapRouter;
}
function extractTokensIfStuck(address _token, uint256 _amount) public onlyOwner {
IERC20(_token).transfer(msg.sender, _amount);
}
function extractETHIfStuck() public onlyOwner {
owner().transfer(address(this).balance);
}
function changeYeldToRewardPerDay(uint256 _amount) public onlyOwner {
yeldToRewardPerDay = _amount;
}
function getGeneratedYelds() public view returns(uint256) {
uint256 blocksPassed;
if (depositBlockStarts[msg.sender] > 0) {
blocksPassed = block.number.sub(depositBlockStarts[msg.sender]);
} else {
return 0;
}
// This will work because amount is a token with 18 decimals
// Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1
// That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day
// your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since
// we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding
// For USDC and Tether gotta multiply by 1e12 since they have 6 decimals to get the proper result of YELD
uint256 ibalance = balanceOf(msg.sender); // Balance of yTokens
uint256 accomulatedStablecoins;
if (_totalSupply <= 0) {
accomulatedStablecoins = 0;
} else {
accomulatedStablecoins = (calcPoolValueInToken().mul(ibalance)).div(_totalSupply);
}
uint256 generatedYelds = accomulatedStablecoins.div(oneMillion).mul(yeldToRewardPerDay.div(1e18)).mul(blocksPassed).div(oneDayInBlocks);
return generatedYelds;
}
function extractYELDEarningsWhileKeepingDeposit() public {
uint256 ibalance = balanceOf(msg.sender);
uint256 accomulatedStablecoins = (calcPoolValueInToken().mul(ibalance)).div(_totalSupply);
require(depositBlockStarts[msg.sender] > 0 && accomulatedStablecoins > 0, 'Must have deposited stablecoins beforehand');
uint256 generatedYelds = getGeneratedYelds();
depositBlockStarts[msg.sender] = block.number;
yeldToken.transfer(msg.sender, generatedYelds);
}
function deposit(uint256 _amount)
external
nonReentrant
{
require(_amount > 0, "deposit must be greater than 0");
pool = calcPoolValueInToken();
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
// Yeld
if (getGeneratedYelds() > 0) extractYELDEarningsWhileKeepingDeposit();
depositBlockStarts[msg.sender] = block.number;
// Yeld
// Calculate pool shares
uint256 shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.mul(_totalSupply)).div(pool);
}
pool = calcPoolValueInToken();
_mint(msg.sender, shares);
rebalance();
}
// Converts DAI to ETH and returns how much ETH has been received from Uniswap
function daiToETH(uint256 _amount) internal returns(uint256) {
IERC20(dai).safeApprove(uniswapRouter, 0);
IERC20(dai).safeApprove(uniswapRouter, _amount);
address[] memory path = new address[](2);
path[0] = dai;
path[1] = weth;
// swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
// 'amounts' is an array where [0] is input DAI amount and [1] is the resulting ETH after the conversion
// even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uint[] memory amounts = IUniswap(uniswapRouter).swapExactTokensForETH(_amount, uint(0), path, address(this), now.add(1800));
return amounts[1];
}
// Buys YELD tokens paying in ETH on Uniswap and removes them from circulation
// Returns how many YELD tokens have been burned
function buyNBurn(uint256 _ethToSwap) internal returns(uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(yeldToken);
// Burns the tokens by taking them out of circulation, sending them to the 0x0 address
uint[] memory amounts = IUniswap(uniswapRouter).swapExactETHForTokens.value(_ethToSwap)(uint(0), path, address(0), now.add(1800));
return amounts[1];
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 _shares)
external
nonReentrant
{
require(_shares > 0, "withdraw must be greater than 0");
uint256 ibalance = balanceOf(msg.sender);
require(_shares <= ibalance, "insufficient balance");
pool = calcPoolValueInToken();
// Yeld
uint256 generatedYelds = getGeneratedYelds();
// Yeld
uint256 stablecoinsToWithdraw = (pool.mul(_shares)).div(_totalSupply);
_balances[msg.sender] = _balances[msg.sender].sub(_shares, "redeem amount exceeds balance");
_totalSupply = _totalSupply.sub(_shares, '#1 Total supply sub error');
emit Transfer(msg.sender, address(0), _shares);
uint256 b = IERC20(token).balanceOf(address(this));
if (b < stablecoinsToWithdraw) {
_withdrawSome(stablecoinsToWithdraw.sub(b, '#2 Withdraw some sub error'));
}
// Yeld
// Take 1% of the amount to withdraw
uint256 onePercent = stablecoinsToWithdraw.div(100);
depositBlockStarts[msg.sender] = block.number;
yeldToken.transfer(msg.sender, generatedYelds);
// Take a portion of the profits for the buy and burn and retirement yeld
// Convert half the DAI earned into ETH for the protocol algorithms
uint256 stakingProfits = daiToETH(onePercent);
uint256 tokensAlreadyBurned = yeldToken.balanceOf(address(0));
if (tokensAlreadyBurned < maximumTokensToBurn) {
// 98% is the 49% doubled since we already took the 50%
uint256 ethToSwap = stakingProfits.mul(98).div(100);
// Buy and burn only applies up to 50k tokens burned
buyNBurn(ethToSwap);
// 1% for the Retirement Yield
uint256 retirementYeld = stakingProfits.mul(2).div(100);
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
} else {
// If we've reached the maximum burn point, send half the profits to the treasury to reward holders
uint256 retirementYeld = stakingProfits;
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
}
IERC20(token).safeTransfer(msg.sender, stablecoinsToWithdraw.sub(onePercent));
// Yeld
pool = calcPoolValueInToken();
rebalance();
}
function recommend() public view returns (Lender) {
(,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).recommend(token);
uint256 max = 0;
if (capr > max) {
max = capr;
}
if (iapr > max) {
max = iapr;
}
if (aapr > max) {
max = aapr;
}
if (dapr > max) {
max = dapr;
}
Lender newProvider = Lender.NONE;
if (max == capr) {
newProvider = Lender.COMPOUND;
} else if (max == iapr) {
newProvider = Lender.FULCRUM;
} else if (max == aapr) {
newProvider = Lender.AAVE;
} else if (max == dapr) {
newProvider = Lender.DYDX;
}
return newProvider;
}
function getAave() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPool();
}
function getAaveCore() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPoolCore();
}
function approveToken() public {
IERC20(token).safeApprove(compound, uint(-1));
IERC20(token).safeApprove(dydx, uint(-1));
IERC20(token).safeApprove(getAaveCore(), uint(-1));
IERC20(token).safeApprove(fulcrum, uint(-1));
}
function balance() public view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function balanceDydxAvailable() public view returns (uint256) {
return IERC20(token).balanceOf(dydx);
}
function balanceDydx() public view returns (uint256) {
Wei memory bal = DyDx(dydx).getAccountWei(Info(address(this), 0), dToken);
return bal.value;
}
function balanceCompound() public view returns (uint256) {
return IERC20(compound).balanceOf(address(this));
}
function balanceCompoundInToken() public view returns (uint256) {
// Mantisa 1e18 to decimals
uint256 b = balanceCompound();
if (b > 0) {
b = b.mul(Compound(compound).exchangeRateStored()).div(1e18);
}
return b;
}
function balanceFulcrumAvailable() public view returns (uint256) {
return IERC20(chai).balanceOf(fulcrum);
}
function balanceFulcrumInToken() public view returns (uint256) {
uint256 b = balanceFulcrum();
if (b > 0) {
b = Fulcrum(fulcrum).assetBalanceOf(address(this));
}
return b;
}
function balanceFulcrum() public view returns (uint256) {
return IERC20(fulcrum).balanceOf(address(this));
}
function balanceAaveAvailable() public view returns (uint256) {
return IERC20(token).balanceOf(aavePool);
}
function balanceAave() public view returns (uint256) {
return IERC20(aaveToken).balanceOf(address(this));
}
function rebalance() public {
Lender newProvider = recommend();
if (newProvider != provider) {
_withdrawAll();
}
if (balance() > 0) {
if (newProvider == Lender.DYDX) {
_supplyDydx(balance());
} else if (newProvider == Lender.FULCRUM) {
_supplyFulcrum(balance());
} else if (newProvider == Lender.COMPOUND) {
_supplyCompound(balance());
} else if (newProvider == Lender.AAVE) {
_supplyAave(balance());
}
}
provider = newProvider;
}
function _withdrawAll() internal {
uint256 amount = balanceCompound();
if (amount > 0) {
_withdrawSomeCompound(balanceCompoundInToken().sub(1));
}
amount = balanceDydx();
if (amount > 0) {
if (amount > balanceDydxAvailable()) {
amount = balanceDydxAvailable();
}
_withdrawDydx(amount);
}
amount = balanceFulcrum();
if (amount > 0) {
if (amount > balanceFulcrumAvailable().sub(1)) {
amount = balanceFulcrumAvailable().sub(1);
}
_withdrawSomeFulcrum(amount);
}
amount = balanceAave();
if (amount > 0) {
if (amount > balanceAaveAvailable()) {
amount = balanceAaveAvailable();
}
_withdrawAave(amount);
}
}
function _withdrawSomeCompound(uint256 _amount) internal {
uint256 b = balanceCompound();
uint256 bT = balanceCompoundInToken();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount)).div(bT).add(1);
_withdrawCompound(amount);
}
function _withdrawSomeFulcrum(uint256 _amount) internal {
uint256 b = balanceFulcrum();
uint256 bT = balanceFulcrumInToken();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount)).div(bT).add(1);
_withdrawFulcrum(amount);
}
function _withdrawSome(uint256 _amount) internal returns (bool) {
uint256 origAmount = _amount;
uint256 amount = balanceCompound();
if (amount > 0) {
if (_amount > balanceCompoundInToken().sub(1)) {
_withdrawSomeCompound(balanceCompoundInToken().sub(1));
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawSomeCompound(_amount);
return true;
}
}
amount = balanceDydx();
if (amount > 0) {
if (_amount > balanceDydxAvailable()) {
_withdrawDydx(balanceDydxAvailable());
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawDydx(_amount);
return true;
}
}
amount = balanceFulcrum();
if (amount > 0) {
if (_amount > balanceFulcrumAvailable().sub(1)) {
amount = balanceFulcrumAvailable().sub(1);
_withdrawSomeFulcrum(balanceFulcrumAvailable().sub(1));
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawSomeFulcrum(amount);
return true;
}
}
amount = balanceAave();
if (amount > 0) {
if (_amount > balanceAaveAvailable()) {
_withdrawAave(balanceAaveAvailable());
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawAave(_amount);
return true;
}
}
return true;
}
function _supplyDydx(uint256 amount) internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Deposit;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).operate(infos, args);
}
function _supplyAave(uint amount) internal {
Aave(getAave()).deposit(token, amount, 0);
}
function _supplyFulcrum(uint amount) internal {
require(Fulcrum(fulcrum).mint(address(this), amount) > 0, "FULCRUM: supply failed");
}
function _supplyCompound(uint amount) internal {
require(Compound(compound).mint(amount) == 0, "COMPOUND: supply failed");
}
function _withdrawAave(uint amount) internal {
AToken(aaveToken).redeem(amount);
}
function _withdrawFulcrum(uint amount) internal {
require(Fulcrum(fulcrum).burn(address(this), amount) > 0, "FULCRUM: withdraw failed");
}
function _withdrawCompound(uint amount) internal {
require(Compound(compound).redeem(amount) == 0, "COMPOUND: withdraw failed");
}
function _withdrawDydx(uint256 amount) internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Withdraw;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).operate(infos, args);
}
function calcPoolValueInToken() public view returns (uint) {
return balanceCompoundInToken()
.add(balanceFulcrumInToken())
.add(balanceDydx())
.add(balanceAave())
.add(balance());
}
function getPricePerFullShare() public view returns (uint) {
uint _pool = calcPoolValueInToken();
return _pool.mul(1e18).div(_totalSupply);
}
} | Take a portion of the profits for the buy and burn and retirement yeld Convert half the DAI earned into ETH for the protocol algorithms | uint256 stakingProfits = daiToETH(onePercent);
| 5,949,602 | [
1,
13391,
279,
14769,
434,
326,
9214,
1282,
364,
326,
30143,
471,
18305,
471,
325,
577,
475,
677,
488,
4037,
8816,
326,
463,
18194,
425,
1303,
329,
1368,
512,
2455,
364,
326,
1771,
20032,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
2254,
5034,
384,
6159,
626,
18352,
273,
5248,
77,
774,
1584,
44,
12,
476,
8410,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x46d81377EDA197f24ea58C636336569216b58D1f/sources/contracts/POPS_teamWallet_shares.sol | Flag the address as a shareholder
| isShareholder[newShareholder]=true; | 16,033,984 | [
1,
4678,
326,
1758,
487,
279,
7433,
4505,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
353,
9535,
4505,
63,
2704,
9535,
4505,
65,
33,
3767,
31,
4766,
21821,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42220/0xf6b5F7a885CBc57d739aDBEe76E52A70Bc04D795/sources/project_/contracts/token/ERC677.sol | * @dev transfer token to a contract address with additional data if the recipient is a contact. @param _to The address to transfer to. @param _value The amount to be transferred. @param _data The extra data to be passed to the receiving contract. @return true if transfer is successful/ | ) internal returns (bool) {
bool res = transfer(_to, _value);
emit Transfer(msg.sender, _to, _value, _data);
if (isContract(_to)) {
require(contractFallback(_to, _value, _data), "Contract fallback failed");
}
return res;
}
| 3,497,443 | [
1,
13866,
1147,
358,
279,
6835,
1758,
598,
3312,
501,
309,
326,
8027,
353,
279,
5388,
18,
225,
389,
869,
1021,
1758,
358,
7412,
358,
18,
225,
389,
1132,
1021,
3844,
358,
506,
906,
4193,
18,
225,
389,
892,
1021,
2870,
501,
358,
506,
2275,
358,
326,
15847,
6835,
18,
327,
638,
309,
7412,
353,
6873,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
13,
2713,
1135,
261,
6430,
13,
288,
203,
202,
202,
6430,
400,
273,
7412,
24899,
869,
16,
389,
1132,
1769,
203,
202,
202,
18356,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
16,
389,
892,
1769,
203,
203,
202,
202,
430,
261,
291,
8924,
24899,
869,
3719,
288,
203,
1082,
202,
6528,
12,
16351,
12355,
24899,
869,
16,
389,
1132,
16,
389,
892,
3631,
315,
8924,
5922,
2535,
8863,
203,
202,
202,
97,
203,
202,
202,
2463,
400,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "./libs/SafeERC20.sol";
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
AddressUpgradeable
} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {BoringOwnable} from "./libs/BoringOwnable.sol";
import {
MulticallUpgradeable
} from "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import {MoneyMarket} from "./moneymarkets/MoneyMarket.sol";
import {IFeeModel} from "./models/fee/IFeeModel.sol";
import {IInterestModel} from "./models/interest/IInterestModel.sol";
import {NFT} from "./tokens/NFT.sol";
import {FundingMultitoken} from "./tokens/FundingMultitoken.sol";
import {MPHMinter} from "./rewards/MPHMinter.sol";
import {IInterestOracle} from "./models/interest-oracle/IInterestOracle.sol";
import {PRBMathUD60x18} from "prb-math/contracts/PRBMathUD60x18.sol";
import {Rescuable} from "./libs/Rescuable.sol";
import {console} from "hardhat/console.sol";
/**
@title DeLorean Interest -- It's coming back from the future!
@author Zefram Lou
@notice The main pool contract for fixed-rate deposits
@dev The contract to interact with for most actions
*/
contract DInterest is
ReentrancyGuardUpgradeable,
BoringOwnable,
Rescuable,
MulticallUpgradeable
{
using SafeERC20 for ERC20;
using AddressUpgradeable for address;
using PRBMathUD60x18 for uint256;
// Constants
uint256 internal constant PRECISION = 10**18;
/**
@dev used for sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex
*/
uint256 internal constant EXTRA_PRECISION = 10**27;
/**
@dev used for funding.principalPerToken
*/
uint256 internal constant ULTRA_PRECISION = 2**128;
/**
@dev Specifies the threshold for paying out funder interests
*/
uint256 internal constant FUNDER_PAYOUT_THRESHOLD_DIVISOR = 10**10;
// User deposit data
// Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1
struct Deposit {
uint256 virtualTokenTotalSupply; // depositAmount + interestAmount, behaves like a zero coupon bond
uint256 interestRate; // interestAmount = interestRate * depositAmount
uint256 feeRate; // feeAmount = feeRate * depositAmount
uint256 averageRecordedIncomeIndex; // Average income index at time of deposit, used for computing deposit surplus
uint64 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds
uint64 fundingID; // The ID of the associated Funding struct. 0 if not funded.
}
Deposit[] internal deposits;
// Funding data
// Each funding has an ID used in the fundingMultitoken, which is equal to its index in `fundingList` plus 1
struct Funding {
uint64 depositID; // The ID of the associated Deposit struct.
uint64 lastInterestPayoutTimestamp; // Unix timestamp of the most recent interest payout, in seconds
uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal)
uint256 principalPerToken; // The amount of stablecoins that's earning interest for you per funding token you own. Scaled to 18 decimals regardless of stablecoin decimals.
}
Funding[] internal fundingList;
// the sum of (recordedFundedPrincipalAmount / recordedMoneyMarketIncomeIndex) of all fundings
uint256 public sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex;
// Params
/**
@dev Maximum deposit period, in seconds
*/
uint64 public MaxDepositPeriod;
/**
@dev Minimum deposit amount, in stablecoins
*/
uint256 public MinDepositAmount;
// Global variables
uint256 public totalDeposit;
uint256 public totalInterestOwed;
uint256 public totalFeeOwed;
uint256 public totalFundedPrincipalAmount;
// External smart contracts
IFeeModel public feeModel;
IInterestModel public interestModel;
IInterestOracle public interestOracle;
NFT public depositNFT;
FundingMultitoken public fundingMultitoken;
MPHMinter public mphMinter;
// Extra params
/**
@dev The maximum amount of deposit in the pool. Set to 0 to disable the cap.
*/
uint256 public GlobalDepositCap;
// Events
event EDeposit(
address indexed sender,
uint256 indexed depositID,
uint256 depositAmount,
uint256 interestAmount,
uint256 feeAmount,
uint64 maturationTimestamp
);
event ETopupDeposit(
address indexed sender,
uint64 indexed depositID,
uint256 depositAmount,
uint256 interestAmount,
uint256 feeAmount
);
event ERolloverDeposit(
address indexed sender,
uint64 indexed depositID,
uint64 indexed newDepositID
);
event EWithdraw(
address indexed sender,
uint256 indexed depositID,
bool indexed early,
uint256 virtualTokenAmount,
uint256 feeAmount
);
event EFund(
address indexed sender,
uint64 indexed fundingID,
uint256 fundAmount,
uint256 tokenAmount
);
event EPayFundingInterest(
uint256 indexed fundingID,
uint256 interestAmount,
uint256 refundAmount
);
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
uint256 newValue
);
function __DInterest_init(
uint64 _MaxDepositPeriod,
uint256 _MinDepositAmount,
address _feeModel,
address _interestModel,
address _interestOracle,
address _depositNFT,
address _fundingMultitoken,
address _mphMinter
) internal initializer {
__ReentrancyGuard_init();
__Ownable_init();
feeModel = IFeeModel(_feeModel);
interestModel = IInterestModel(_interestModel);
interestOracle = IInterestOracle(_interestOracle);
depositNFT = NFT(_depositNFT);
fundingMultitoken = FundingMultitoken(_fundingMultitoken);
mphMinter = MPHMinter(_mphMinter);
MaxDepositPeriod = _MaxDepositPeriod;
MinDepositAmount = _MinDepositAmount;
}
/**
@param _MaxDepositPeriod The maximum deposit period, in seconds
@param _MinDepositAmount The minimum deposit amount, in stablecoins
@param _feeModel Address of the FeeModel contract that determines how fees are charged
@param _interestModel Address of the InterestModel contract that determines how much interest to offer
@param _interestOracle Address of the InterestOracle contract that provides the average interest rate
@param _depositNFT Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract)
@param _fundingMultitoken Address of the ERC1155 multitoken representing ownership of fundings (this DInterest contract must have the minter-burner role)
@param _mphMinter Address of the contract for handling minting MPH to users
*/
function initialize(
uint64 _MaxDepositPeriod,
uint256 _MinDepositAmount,
address _feeModel,
address _interestModel,
address _interestOracle,
address _depositNFT,
address _fundingMultitoken,
address _mphMinter
) external virtual initializer {
__DInterest_init(
_MaxDepositPeriod,
_MinDepositAmount,
_feeModel,
_interestModel,
_interestOracle,
_depositNFT,
_fundingMultitoken,
_mphMinter
);
}
/**
Public action functions
*/
/**
@notice Create a deposit using `depositAmount` stablecoin that matures at timestamp `maturationTimestamp`.
@dev The ERC-721 NFT representing deposit ownership is given to msg.sender
@param depositAmount The amount of deposit, in stablecoin
@param maturationTimestamp The Unix timestamp of maturation, in seconds
@return depositID The ID of the created deposit
@return interestAmount The amount of fixed-rate interest
*/
function deposit(uint256 depositAmount, uint64 maturationTimestamp)
external
nonReentrant
returns (uint64 depositID, uint256 interestAmount)
{
return
_deposit(
msg.sender,
depositAmount,
maturationTimestamp,
false,
0,
""
);
}
/**
@notice Create a deposit using `depositAmount` stablecoin that matures at timestamp `maturationTimestamp`.
@dev The ERC-721 NFT representing deposit ownership is given to msg.sender
@param depositAmount The amount of deposit, in stablecoin
@param maturationTimestamp The Unix timestamp of maturation, in seconds
@param minimumInterestAmount If the interest amount is less than this, revert
@param uri The metadata URI for the minted NFT
@return depositID The ID of the created deposit
@return interestAmount The amount of fixed-rate interest
*/
function deposit(
uint256 depositAmount,
uint64 maturationTimestamp,
uint256 minimumInterestAmount,
string calldata uri
) external nonReentrant returns (uint64 depositID, uint256 interestAmount) {
return
_deposit(
msg.sender,
depositAmount,
maturationTimestamp,
false,
minimumInterestAmount,
uri
);
}
/**
@notice Add `depositAmount` stablecoin to the existing deposit with ID `depositID`.
@dev The interest rate for the topped up funds will be the current oracle rate.
@param depositID The deposit to top up
@param depositAmount The amount to top up, in stablecoin
@return interestAmount The amount of interest that will be earned by the topped up funds at maturation
*/
function topupDeposit(uint64 depositID, uint256 depositAmount)
external
nonReentrant
returns (uint256 interestAmount)
{
return _topupDeposit(msg.sender, depositID, depositAmount, 0);
}
/**
@notice Add `depositAmount` stablecoin to the existing deposit with ID `depositID`.
@dev The interest rate for the topped up funds will be the current oracle rate.
@param depositID The deposit to top up
@param depositAmount The amount to top up, in stablecoin
@param minimumInterestAmount If the interest amount is less than this, revert
@return interestAmount The amount of interest that will be earned by the topped up funds at maturation
*/
function topupDeposit(
uint64 depositID,
uint256 depositAmount,
uint256 minimumInterestAmount
) external nonReentrant returns (uint256 interestAmount) {
return
_topupDeposit(
msg.sender,
depositID,
depositAmount,
minimumInterestAmount
);
}
/**
@notice Withdraw all funds from deposit with ID `depositID` and use them
to create a new deposit that matures at time `maturationTimestamp`
@param depositID The deposit to roll over
@param maturationTimestamp The Unix timestamp of the new deposit, in seconds
@return newDepositID The ID of the new deposit
*/
function rolloverDeposit(uint64 depositID, uint64 maturationTimestamp)
external
nonReentrant
returns (uint256 newDepositID, uint256 interestAmount)
{
return
_rolloverDeposit(msg.sender, depositID, maturationTimestamp, 0, "");
}
/**
@notice Withdraw all funds from deposit with ID `depositID` and use them
to create a new deposit that matures at time `maturationTimestamp`
@param depositID The deposit to roll over
@param maturationTimestamp The Unix timestamp of the new deposit, in seconds
@param minimumInterestAmount If the interest amount is less than this, revert
@param uri The metadata URI of the NFT
@return newDepositID The ID of the new deposit
*/
function rolloverDeposit(
uint64 depositID,
uint64 maturationTimestamp,
uint256 minimumInterestAmount,
string calldata uri
)
external
nonReentrant
returns (uint256 newDepositID, uint256 interestAmount)
{
return
_rolloverDeposit(
msg.sender,
depositID,
maturationTimestamp,
minimumInterestAmount,
uri
);
}
/**
@notice Withdraws funds from the deposit with ID `depositID`.
@dev Virtual tokens behave like zero coupon bonds, after maturation withdrawing 1 virtual token
yields 1 stablecoin. The total supply is given by deposit.virtualTokenTotalSupply
@param depositID the deposit to withdraw from
@param virtualTokenAmount the amount of virtual tokens to withdraw
@param early True if intend to withdraw before maturation, false otherwise
@return withdrawnStablecoinAmount the amount of stablecoins withdrawn
*/
function withdraw(
uint64 depositID,
uint256 virtualTokenAmount,
bool early
) external nonReentrant returns (uint256 withdrawnStablecoinAmount) {
return
_withdraw(msg.sender, depositID, virtualTokenAmount, early, false);
}
/**
@notice Funds the fixed-rate interest of the deposit with ID `depositID`.
In exchange, the funder receives the future floating-rate interest
generated by the portion of the deposit whose interest was funded.
@dev The sender receives ERC-1155 multitokens (fundingMultitoken) representing
their funding position.
@param depositID The deposit whose fixed-rate interest will be funded
@param fundAmount The amount of stablecoins to pay for the fundingMultitokens.
If it exceeds the upper bound, it will be set to
the bound value instead. (See {_fund} implementation)
@return fundingID The ID of the fundingMultitoken the sender received
@return fundingMultitokensMinted The amount of fundingMultitokens minted to the sender
@return actualFundAmount The amount of stablecoins paid by the sender
@return principalFunded The amount of principal the minted fundingMultitokens is earning yield on
*/
function fund(uint64 depositID, uint256 fundAmount)
external
nonReentrant
returns (
uint64 fundingID,
uint256 fundingMultitokensMinted,
uint256 actualFundAmount,
uint256 principalFunded
)
{
return _fund(msg.sender, depositID, fundAmount, 0);
}
/**
@notice Funds the fixed-rate interest of the deposit with ID `depositID`.
In exchange, the funder receives the future floating-rate interest
generated by the portion of the deposit whose interest was funded.
@dev The sender receives ERC-1155 multitokens (fundingMultitoken) representing
their funding position.
@param depositID The deposit whose fixed-rate interest will be funded
@param fundAmount The amount of stablecoins to pay for the fundingMultitokens.
If it exceeds the upper bound, it will be set to
the bound value instead. (See {_fund} implementation)
@param minPrincipalFunded The minimum amount of principalFunded, below which the tx will revert
@return fundingID The ID of the fundingMultitoken the sender received
@return fundingMultitokensMinted The amount of fundingMultitokens minted to the sender
@return actualFundAmount The amount of stablecoins paid by the sender
@return principalFunded The amount of principal the minted fundingMultitokens is earning yield on
*/
function fund(
uint64 depositID,
uint256 fundAmount,
uint256 minPrincipalFunded
)
external
nonReentrant
returns (
uint64 fundingID,
uint256 fundingMultitokensMinted,
uint256 actualFundAmount,
uint256 principalFunded
)
{
return _fund(msg.sender, depositID, fundAmount, minPrincipalFunded);
}
/**
@notice Distributes the floating-rate interest accrued by a deposit to the
floating-rate bond holders.
@param fundingID The ID of the floating-rate bond
@return interestAmount The amount of interest distributed, in stablecoins
*/
function payInterestToFunders(uint64 fundingID)
external
nonReentrant
returns (uint256 interestAmount)
{
return _payInterestToFunders(fundingID, moneyMarket().incomeIndex());
}
/**
Public getter functions
*/
/**
@notice Computes the amount of fixed-rate interest (before fees) that
will be given to a deposit of `depositAmount` stablecoins that
matures in `depositPeriodInSeconds` seconds.
@param depositAmount The deposit amount, in stablecoins
@param depositPeriodInSeconds The deposit period, in seconds
@return interestAmount The amount of fixed-rate interest (before fees)
*/
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds
) public virtual returns (uint256 interestAmount) {
(, uint256 moneyMarketInterestRatePerSecond) =
interestOracle.updateAndQuery();
(bool surplusIsNegative, uint256 surplusAmount) = surplus();
return
interestModel.calculateInterestAmount(
depositAmount,
depositPeriodInSeconds,
moneyMarketInterestRatePerSecond,
surplusIsNegative,
surplusAmount
);
}
/**
@notice Computes the pool's overall surplus, which is the value of its holdings
in the `moneyMarket` minus the amount owed to depositors, funders, and
the fee beneficiary.
@return isNegative True if the surplus is negative, false otherwise
@return surplusAmount The absolute value of the surplus, in stablecoins
*/
function surplus()
public
virtual
returns (bool isNegative, uint256 surplusAmount)
{
return _surplus(moneyMarket().incomeIndex());
}
/**
@notice Returns the total number of deposits.
@return deposits.length
*/
function depositsLength() external view returns (uint256) {
return deposits.length;
}
/**
@notice Returns the total number of floating-rate bonds.
@return fundingList.length
*/
function fundingListLength() external view returns (uint256) {
return fundingList.length;
}
/**
@notice Returns the Deposit struct associated with the deposit with ID
`depositID`.
@param depositID The ID of the deposit
@return The deposit struct
*/
function getDeposit(uint64 depositID)
external
view
returns (Deposit memory)
{
return deposits[depositID - 1];
}
/**
@notice Returns the Funding struct associated with the floating-rate bond with ID
`fundingID`.
@param fundingID The ID of the floating-rate bond
@return The Funding struct
*/
function getFunding(uint64 fundingID)
external
view
returns (Funding memory)
{
return fundingList[fundingID - 1];
}
/**
@notice Returns the moneyMarket contract
@return The moneyMarket
*/
function moneyMarket() public view returns (MoneyMarket) {
return interestOracle.moneyMarket();
}
/**
@notice Returns the stablecoin ERC20 token contract
@return The stablecoin
*/
function stablecoin() public view returns (ERC20) {
return moneyMarket().stablecoin();
}
/**
Internal action functions
*/
/**
@dev See {deposit}
*/
function _deposit(
address sender,
uint256 depositAmount,
uint64 maturationTimestamp,
bool rollover,
uint256 minimumInterestAmount,
string memory uri
) internal virtual returns (uint64 depositID, uint256 interestAmount) {
(depositID, interestAmount) = _depositRecordData(
sender,
depositAmount,
maturationTimestamp,
minimumInterestAmount,
uri
);
_depositTransferFunds(sender, depositAmount, rollover);
}
function _depositRecordData(
address sender,
uint256 depositAmount,
uint64 maturationTimestamp,
uint256 minimumInterestAmount,
string memory uri
) internal virtual returns (uint64 depositID, uint256 interestAmount) {
// Ensure input is valid
require(depositAmount >= MinDepositAmount, "BAD_AMOUNT");
uint256 depositPeriod = maturationTimestamp - block.timestamp;
require(depositPeriod <= MaxDepositPeriod, "BAD_TIME");
// Calculate interest
interestAmount = calculateInterestAmount(depositAmount, depositPeriod);
require(
interestAmount > 0 && interestAmount >= minimumInterestAmount,
"BAD_INTEREST"
);
// Calculate fee
uint256 feeAmount =
feeModel.getInterestFeeAmount(address(this), interestAmount);
interestAmount -= feeAmount;
// Record deposit data
deposits.push(
Deposit({
virtualTokenTotalSupply: depositAmount + interestAmount,
interestRate: interestAmount.div(depositAmount),
feeRate: feeAmount.div(depositAmount),
maturationTimestamp: maturationTimestamp,
fundingID: 0,
averageRecordedIncomeIndex: interestOracle
.moneyMarket()
.incomeIndex()
})
);
require(deposits.length <= type(uint64).max, "OVERFLOW");
depositID = uint64(deposits.length);
// Update global values
totalDeposit += depositAmount;
{
uint256 depositCap = GlobalDepositCap;
require(depositCap == 0 || totalDeposit <= depositCap, "CAP");
}
totalInterestOwed += interestAmount;
totalFeeOwed += feeAmount;
// Mint depositNFT
if (bytes(uri).length == 0) {
depositNFT.mint(sender, depositID);
} else {
depositNFT.mint(sender, depositID, uri);
}
// Emit event
emit EDeposit(
sender,
depositID,
depositAmount,
interestAmount,
feeAmount,
maturationTimestamp
);
// Vest MPH to sender
mphMinter.createVestForDeposit(sender, depositID);
}
function _depositTransferFunds(
address sender,
uint256 depositAmount,
bool rollover
) internal virtual {
// Only transfer funds from sender if it's not a rollover
// because if it is the funds are already in the contract
if (!rollover) {
ERC20 _stablecoin = stablecoin();
// Transfer `depositAmount` stablecoin to DInterest
_stablecoin.safeTransferFrom(sender, address(this), depositAmount);
// Lend `depositAmount` stablecoin to money market
MoneyMarket _moneyMarket = moneyMarket();
_stablecoin.safeIncreaseAllowance(
address(_moneyMarket),
depositAmount
);
_moneyMarket.deposit(depositAmount);
}
}
/**
@dev See {topupDeposit}
*/
function _topupDeposit(
address sender,
uint64 depositID,
uint256 depositAmount,
uint256 minimumInterestAmount
) internal virtual returns (uint256 interestAmount) {
interestAmount = _topupDepositRecordData(
sender,
depositID,
depositAmount,
minimumInterestAmount
);
_topupDepositTransferFunds(sender, depositAmount);
}
function _topupDepositRecordData(
address sender,
uint64 depositID,
uint256 depositAmount,
uint256 minimumInterestAmount
) internal virtual returns (uint256 interestAmount) {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositNFT.ownerOf(depositID) == sender, "NOT_OWNER");
// underflow check prevents topups after maturation
uint256 depositPeriod =
depositEntry.maturationTimestamp - block.timestamp;
// Calculate interest
interestAmount = calculateInterestAmount(depositAmount, depositPeriod);
require(
interestAmount > 0 && interestAmount >= minimumInterestAmount,
"BAD_INTEREST"
);
// Calculate fee
uint256 feeAmount =
feeModel.getInterestFeeAmount(address(this), interestAmount);
interestAmount -= feeAmount;
// Update deposit struct
uint256 interestRate = depositEntry.interestRate;
uint256 currentDepositAmount =
depositEntry.virtualTokenTotalSupply.div(interestRate + PRECISION);
depositEntry.virtualTokenTotalSupply += depositAmount + interestAmount;
depositEntry.interestRate =
(PRECISION * interestAmount + currentDepositAmount * interestRate) /
(depositAmount + currentDepositAmount);
depositEntry.feeRate =
(PRECISION *
feeAmount +
currentDepositAmount *
depositEntry.feeRate) /
(depositAmount + currentDepositAmount);
uint256 sumOfRecordedDepositAmountDivRecordedIncomeIndex =
(currentDepositAmount * EXTRA_PRECISION) /
depositEntry.averageRecordedIncomeIndex +
(depositAmount * EXTRA_PRECISION) /
moneyMarket().incomeIndex();
depositEntry.averageRecordedIncomeIndex =
((depositAmount + currentDepositAmount) * EXTRA_PRECISION) /
sumOfRecordedDepositAmountDivRecordedIncomeIndex;
// Update global values
totalDeposit += depositAmount;
{
uint256 depositCap = GlobalDepositCap;
require(depositCap == 0 || totalDeposit <= depositCap, "CAP");
}
totalInterestOwed += interestAmount;
totalFeeOwed += feeAmount;
// Emit event
emit ETopupDeposit(
sender,
depositID,
depositAmount,
interestAmount,
feeAmount
);
// Update vest
mphMinter.updateVestForDeposit(
depositID,
currentDepositAmount,
depositAmount
);
}
function _topupDepositTransferFunds(address sender, uint256 depositAmount)
internal
virtual
{
ERC20 _stablecoin = stablecoin();
// Transfer `depositAmount` stablecoin to DInterest
_stablecoin.safeTransferFrom(sender, address(this), depositAmount);
// Lend `depositAmount` stablecoin to money market
MoneyMarket _moneyMarket = moneyMarket();
_stablecoin.safeIncreaseAllowance(address(_moneyMarket), depositAmount);
_moneyMarket.deposit(depositAmount);
}
/**
@dev See {rolloverDeposit}
*/
function _rolloverDeposit(
address sender,
uint64 depositID,
uint64 maturationTimestamp,
uint256 minimumInterestAmount,
string memory uri
) internal virtual returns (uint64 newDepositID, uint256 interestAmount) {
// withdraw from existing deposit
uint256 withdrawnStablecoinAmount =
_withdraw(sender, depositID, type(uint256).max, false, true);
// deposit funds into a new deposit
(newDepositID, interestAmount) = _deposit(
sender,
withdrawnStablecoinAmount,
maturationTimestamp,
true,
minimumInterestAmount,
uri
);
emit ERolloverDeposit(sender, depositID, newDepositID);
}
/**
@dev See {withdraw}
@param rollover True if being called from {_rolloverDeposit}, false otherwise
*/
function _withdraw(
address sender,
uint64 depositID,
uint256 virtualTokenAmount,
bool early,
bool rollover
) internal virtual returns (uint256 withdrawnStablecoinAmount) {
(
uint256 withdrawAmount,
uint256 feeAmount,
uint256 fundingInterestAmount,
uint256 refundAmount
) = _withdrawRecordData(sender, depositID, virtualTokenAmount, early);
return
_withdrawTransferFunds(
sender,
_getDeposit(depositID).fundingID,
withdrawAmount,
feeAmount,
fundingInterestAmount,
refundAmount,
rollover
);
}
function _withdrawRecordData(
address sender,
uint64 depositID,
uint256 virtualTokenAmount,
bool early
)
internal
virtual
returns (
uint256 withdrawAmount,
uint256 feeAmount,
uint256 fundingInterestAmount,
uint256 refundAmount
)
{
// Verify input
require(virtualTokenAmount > 0, "BAD_AMOUNT");
Deposit storage depositEntry = _getDeposit(depositID);
if (early) {
require(
block.timestamp < depositEntry.maturationTimestamp,
"MATURE"
);
} else {
require(
block.timestamp >= depositEntry.maturationTimestamp,
"IMMATURE"
);
}
require(depositNFT.ownerOf(depositID) == sender, "NOT_OWNER");
// Check if withdrawing all funds
{
uint256 virtualTokenTotalSupply =
depositEntry.virtualTokenTotalSupply;
if (virtualTokenAmount > virtualTokenTotalSupply) {
virtualTokenAmount = virtualTokenTotalSupply;
}
}
// Compute token amounts
uint256 interestRate = depositEntry.interestRate;
uint256 feeRate = depositEntry.feeRate;
uint256 depositAmount =
virtualTokenAmount.div(interestRate + PRECISION);
{
uint256 interestAmount =
early ? 0 : virtualTokenAmount - depositAmount;
withdrawAmount = depositAmount + interestAmount;
}
if (early) {
// apply fee to withdrawAmount
uint256 earlyWithdrawFee =
feeModel.getEarlyWithdrawFeeAmount(
address(this),
depositID,
withdrawAmount
);
feeAmount = earlyWithdrawFee;
withdrawAmount -= earlyWithdrawFee;
} else {
feeAmount = depositAmount.mul(feeRate);
}
// Update global values
totalDeposit -= depositAmount;
totalInterestOwed -= virtualTokenAmount - depositAmount;
totalFeeOwed -= depositAmount.mul(feeRate);
// If deposit was funded, compute funding interest payout
uint64 fundingID = depositEntry.fundingID;
if (fundingID > 0) {
Funding storage funding = _getFunding(fundingID);
// Compute funded deposit amount before withdrawal
uint256 recordedFundedPrincipalAmount =
(fundingMultitoken.totalSupply(fundingID) *
funding.principalPerToken) / ULTRA_PRECISION;
// Shrink funding principal per token value
{
uint256 totalPrincipal =
_depositVirtualTokenToPrincipal(
depositID,
depositEntry.virtualTokenTotalSupply
);
uint256 totalPrincipalDecrease =
virtualTokenAmount + depositAmount.mul(feeRate);
if (
totalPrincipal <=
totalPrincipalDecrease + recordedFundedPrincipalAmount
) {
// Not enough unfunded principal, need to decrease funding principal per token value
funding.principalPerToken = (totalPrincipal >=
totalPrincipalDecrease)
? (funding.principalPerToken *
(totalPrincipal - totalPrincipalDecrease)) /
recordedFundedPrincipalAmount
: 0;
}
}
// Compute interest payout + refund
// and update relevant state
(
fundingInterestAmount,
refundAmount
) = _computeAndUpdateFundingInterestAfterWithdraw(
fundingID,
recordedFundedPrincipalAmount,
early
);
}
// Update vest
{
uint256 depositAmountBeforeWithdrawal =
_getDeposit(depositID).virtualTokenTotalSupply.div(
interestRate + PRECISION
);
mphMinter.updateVestForDeposit(
depositID,
depositAmountBeforeWithdrawal,
0
);
}
// Burn `virtualTokenAmount` deposit virtual tokens
_getDeposit(depositID).virtualTokenTotalSupply -= virtualTokenAmount;
// Emit event
emit EWithdraw(sender, depositID, early, virtualTokenAmount, feeAmount);
}
function _withdrawTransferFunds(
address sender,
uint64 fundingID,
uint256 withdrawAmount,
uint256 feeAmount,
uint256 fundingInterestAmount,
uint256 refundAmount,
bool rollover
) internal virtual returns (uint256 withdrawnStablecoinAmount) {
ERC20 _stablecoin = stablecoin();
// Withdraw funds from money market
// Withdraws principal together with funding interest to save gas
if (rollover) {
// Rollover mode, don't withdraw `withdrawAmount` from moneyMarket
// We do this because feePlusFundingInterest might
// be slightly less due to rounding
uint256 feePlusFundingInterest =
moneyMarket().withdraw(feeAmount + fundingInterestAmount);
if (feePlusFundingInterest >= feeAmount + fundingInterestAmount) {
// enough to pay everything, if there's extra give to feeAmount
feeAmount = feePlusFundingInterest - fundingInterestAmount;
} else if (feePlusFundingInterest >= feeAmount) {
// enough to pay fee, give remainder to fundingInterestAmount
fundingInterestAmount = feePlusFundingInterest - feeAmount;
} else {
// not enough to pay fee, give everything to fee
feeAmount = feePlusFundingInterest;
fundingInterestAmount = 0;
}
// we're keeping the withdrawal amount in the money market
withdrawnStablecoinAmount = withdrawAmount;
} else {
uint256 actualWithdrawnAmount =
moneyMarket().withdraw(
withdrawAmount + feeAmount + fundingInterestAmount
);
// We do this because `actualWithdrawnAmount` might
// be slightly less due to rounding
withdrawnStablecoinAmount = withdrawAmount;
if (
actualWithdrawnAmount >=
withdrawAmount + feeAmount + fundingInterestAmount
) {
// enough to pay everything, if there's extra give to feeAmount
feeAmount =
actualWithdrawnAmount -
withdrawAmount -
fundingInterestAmount;
} else if (actualWithdrawnAmount >= withdrawAmount + feeAmount) {
// enough to pay withdrawal + fee + remainder
// give remainder to funding interest
fundingInterestAmount =
actualWithdrawnAmount -
withdrawAmount -
feeAmount;
} else if (actualWithdrawnAmount >= withdrawAmount) {
// enough to pay withdrawal + remainder
// give remainder to fee
feeAmount = actualWithdrawnAmount - withdrawAmount;
fundingInterestAmount = 0;
} else {
// not enough to pay withdrawal
// give everything to withdrawal
withdrawnStablecoinAmount = actualWithdrawnAmount;
feeAmount = 0;
fundingInterestAmount = 0;
}
if (withdrawnStablecoinAmount > 0) {
_stablecoin.safeTransfer(sender, withdrawnStablecoinAmount);
}
}
// Send `feeAmount` stablecoin to feeModel beneficiary
if (feeAmount > 0) {
_stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
// Distribute `fundingInterestAmount` stablecoins to funders
if (fundingInterestAmount > 0) {
_stablecoin.safeIncreaseAllowance(
address(fundingMultitoken),
fundingInterestAmount
);
fundingMultitoken.distributeDividends(
fundingID,
address(_stablecoin),
fundingInterestAmount
);
// Mint funder rewards
if (fundingInterestAmount > refundAmount) {
_distributeFundingRewards(
fundingID,
fundingInterestAmount - refundAmount
);
}
}
}
/**
@dev See {fund}
*/
function _fund(
address sender,
uint64 depositID,
uint256 fundAmount,
uint256 minPrincipalFunded
)
internal
virtual
returns (
uint64 fundingID,
uint256 fundingMultitokensMinted,
uint256 actualFundAmount,
uint256 principalFunded
)
{
(
fundingID,
fundingMultitokensMinted,
actualFundAmount,
principalFunded
) = _fundRecordData(sender, depositID, fundAmount, minPrincipalFunded);
_fundTransferFunds(sender, actualFundAmount);
}
function _fundRecordData(
address sender,
uint64 depositID,
uint256 fundAmount,
uint256 minPrincipalFunded
)
internal
virtual
returns (
uint64 fundingID,
uint256 fundingMultitokensMinted,
uint256 actualFundAmount,
uint256 principalFunded
)
{
Deposit storage depositEntry = _getDeposit(depositID);
fundingID = depositEntry.fundingID;
uint256 incomeIndex = moneyMarket().incomeIndex();
// Create funding struct if one doesn't exist
{
uint256 virtualTokenTotalSupply =
depositEntry.virtualTokenTotalSupply;
uint256 totalPrincipal =
_depositVirtualTokenToPrincipal(
depositID,
virtualTokenTotalSupply
);
uint256 depositAmount =
virtualTokenTotalSupply.div(
depositEntry.interestRate + PRECISION
);
if (
fundingID == 0 || _getFunding(fundingID).principalPerToken == 0
) {
// The first funder, create struct
require(block.timestamp <= type(uint64).max, "OVERFLOW");
fundingList.push(
Funding({
depositID: depositID,
lastInterestPayoutTimestamp: uint64(block.timestamp),
recordedMoneyMarketIncomeIndex: incomeIndex,
principalPerToken: ULTRA_PRECISION
})
);
require(fundingList.length <= type(uint64).max, "OVERFLOW");
fundingID = uint64(fundingList.length);
depositEntry.fundingID = fundingID;
// Bound fundAmount upwards by the fixed rate yield amount
uint256 bound =
calculateInterestAmount(
depositAmount,
depositEntry.maturationTimestamp - block.timestamp
);
if (fundAmount > bound) {
fundAmount = bound;
}
principalFunded = (totalPrincipal * fundAmount) / bound;
fundingMultitokensMinted = principalFunded;
} else {
// Not the first funder
// Trigger interest payment for existing funders
_payInterestToFunders(fundingID, incomeIndex);
// Compute amount of principal to fund
uint256 principalPerToken =
_getFunding(fundingID).principalPerToken;
uint256 unfundedPrincipalAmount =
totalPrincipal -
(fundingMultitoken.totalSupply(fundingID) *
principalPerToken) /
ULTRA_PRECISION;
// Bound fundAmount upwards by the fixed rate yield amount
uint256 bound =
calculateInterestAmount(
(depositAmount * unfundedPrincipalAmount) /
totalPrincipal,
depositEntry.maturationTimestamp - block.timestamp
);
if (fundAmount > bound) {
fundAmount = bound;
}
principalFunded =
(unfundedPrincipalAmount * fundAmount) /
bound;
fundingMultitokensMinted =
(principalFunded * ULTRA_PRECISION) /
principalPerToken;
}
}
// Check principalFunded is at least minPrincipalFunded
require(principalFunded >= minPrincipalFunded, "MIN");
// Mint funding multitoken
fundingMultitoken.mint(sender, fundingID, fundingMultitokensMinted);
// Update relevant values
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex +=
(principalFunded * EXTRA_PRECISION) /
incomeIndex;
totalFundedPrincipalAmount += principalFunded;
// Emit event
emit EFund(sender, fundingID, fundAmount, fundingMultitokensMinted);
actualFundAmount = fundAmount;
}
function _fundTransferFunds(address sender, uint256 fundAmount)
internal
virtual
{
ERC20 _stablecoin = stablecoin();
// Transfer `fundAmount` stablecoins from sender
_stablecoin.safeTransferFrom(sender, address(this), fundAmount);
// Deposit `fundAmount` stablecoins into moneyMarket
MoneyMarket _moneyMarket = moneyMarket();
_stablecoin.safeIncreaseAllowance(address(_moneyMarket), fundAmount);
_moneyMarket.deposit(fundAmount);
}
/**
@dev See {payInterestToFunders}
@param currentMoneyMarketIncomeIndex The moneyMarket's current incomeIndex
*/
function _payInterestToFunders(
uint64 fundingID,
uint256 currentMoneyMarketIncomeIndex
) internal virtual returns (uint256 interestAmount) {
Funding storage f = _getFunding(fundingID);
{
uint256 recordedMoneyMarketIncomeIndex =
f.recordedMoneyMarketIncomeIndex;
uint256 fundingTokenTotalSupply =
fundingMultitoken.totalSupply(fundingID);
uint256 recordedFundedPrincipalAmount =
(fundingTokenTotalSupply * f.principalPerToken) /
ULTRA_PRECISION;
// Update funding values
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex =
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex +
(recordedFundedPrincipalAmount * EXTRA_PRECISION) /
currentMoneyMarketIncomeIndex -
(recordedFundedPrincipalAmount * EXTRA_PRECISION) /
recordedMoneyMarketIncomeIndex;
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
// Compute interest to funders
interestAmount =
(recordedFundedPrincipalAmount *
currentMoneyMarketIncomeIndex) /
recordedMoneyMarketIncomeIndex -
recordedFundedPrincipalAmount;
}
// Distribute interest to funders
if (interestAmount > 0) {
ERC20 _stablecoin = stablecoin();
uint256 stablecoinPrecision = 10**uint256(_stablecoin.decimals());
if (
interestAmount >
stablecoinPrecision / FUNDER_PAYOUT_THRESHOLD_DIVISOR
) {
interestAmount = moneyMarket().withdraw(interestAmount);
if (interestAmount > 0) {
_stablecoin.safeIncreaseAllowance(
address(fundingMultitoken),
interestAmount
);
fundingMultitoken.distributeDividends(
fundingID,
address(_stablecoin),
interestAmount
);
_distributeFundingRewards(fundingID, interestAmount);
}
} else {
// interestAmount below minimum payout threshold, pay nothing
emit EPayFundingInterest(fundingID, 0, 0);
return 0;
}
}
emit EPayFundingInterest(fundingID, interestAmount, 0);
}
/**
@dev Mints MPH rewards to the holders of an FRB. If past the deposit maturation,
only mint proportional to the time from the last distribution to the maturation.
@param fundingID The ID of the funding
@param rawInterestAmount The interest being distributed
*/
function _distributeFundingRewards(
uint64 fundingID,
uint256 rawInterestAmount
) internal {
Funding storage f = _getFunding(fundingID);
// Mint funder rewards
uint256 maturationTimestamp =
_getDeposit(f.depositID).maturationTimestamp;
if (block.timestamp > maturationTimestamp) {
// past maturation, only mint proportionally to maturation - last payout
uint256 lastInterestPayoutTimestamp = f.lastInterestPayoutTimestamp;
if (lastInterestPayoutTimestamp < maturationTimestamp) {
uint256 effectiveInterestAmount =
(rawInterestAmount *
(maturationTimestamp - lastInterestPayoutTimestamp)) /
(block.timestamp - lastInterestPayoutTimestamp);
mphMinter.distributeFundingRewards(
fundingID,
effectiveInterestAmount
);
}
} else {
// before maturation, mint full amount
mphMinter.distributeFundingRewards(fundingID, rawInterestAmount);
}
// update last payout timestamp
require(block.timestamp <= type(uint64).max, "OVERFLOW");
f.lastInterestPayoutTimestamp = uint64(block.timestamp);
}
/**
@dev Used in {_withdraw}. Computes the amount of interest to distribute
to the deposit's floating-rate bond holders. Also updates the Funding
struct associated with the floating-rate bond.
@param fundingID The ID of the floating-rate bond
@param recordedFundedPrincipalAmount The amount of principal funded before the withdrawal
@param early True if withdrawing before maturation, false otherwise
@return fundingInterestAmount The amount of interest to distribute to the floating-rate bond holders, plus the refund amount
@return refundAmount The amount of refund caused by an early withdraw
*/
function _computeAndUpdateFundingInterestAfterWithdraw(
uint64 fundingID,
uint256 recordedFundedPrincipalAmount,
bool early
)
internal
virtual
returns (uint256 fundingInterestAmount, uint256 refundAmount)
{
Funding storage f = _getFunding(fundingID);
uint256 currentFundedPrincipalAmount =
(fundingMultitoken.totalSupply(fundingID) * f.principalPerToken) /
ULTRA_PRECISION;
// Update funding values
{
uint256 recordedMoneyMarketIncomeIndex =
f.recordedMoneyMarketIncomeIndex;
uint256 currentMoneyMarketIncomeIndex = moneyMarket().incomeIndex();
uint256 currentFundedPrincipalAmountDivRecordedIncomeIndex =
(currentFundedPrincipalAmount * EXTRA_PRECISION) /
currentMoneyMarketIncomeIndex;
uint256 recordedFundedPrincipalAmountDivRecordedIncomeIndex =
(recordedFundedPrincipalAmount * EXTRA_PRECISION) /
recordedMoneyMarketIncomeIndex;
if (
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex +
currentFundedPrincipalAmountDivRecordedIncomeIndex >=
recordedFundedPrincipalAmountDivRecordedIncomeIndex
) {
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex =
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex +
currentFundedPrincipalAmountDivRecordedIncomeIndex -
recordedFundedPrincipalAmountDivRecordedIncomeIndex;
} else {
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex = 0;
}
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
totalFundedPrincipalAmount -=
recordedFundedPrincipalAmount -
currentFundedPrincipalAmount;
// Compute interest to funders
fundingInterestAmount =
(recordedFundedPrincipalAmount *
currentMoneyMarketIncomeIndex) /
recordedMoneyMarketIncomeIndex -
recordedFundedPrincipalAmount;
}
// Add refund to interestAmount
if (early) {
Deposit storage depositEntry = _getDeposit(f.depositID);
uint256 interestRate = depositEntry.interestRate;
uint256 feeRate = depositEntry.feeRate;
(, uint256 moneyMarketInterestRatePerSecond) =
interestOracle.updateAndQuery();
refundAmount = (recordedFundedPrincipalAmount -
currentFundedPrincipalAmount)
.mul(
(moneyMarketInterestRatePerSecond *
(depositEntry.maturationTimestamp - block.timestamp))
.exp2() - PRECISION
);
uint256 maxRefundAmount =
(recordedFundedPrincipalAmount - currentFundedPrincipalAmount)
.div(PRECISION + interestRate + feeRate)
.mul(interestRate + feeRate);
refundAmount = refundAmount <= maxRefundAmount
? refundAmount
: maxRefundAmount;
fundingInterestAmount += refundAmount;
}
emit EPayFundingInterest(
fundingID,
fundingInterestAmount,
refundAmount
);
}
/**
Internal getter functions
*/
/**
@dev See {getDeposit}
*/
function _getDeposit(uint64 depositID)
internal
view
returns (Deposit storage)
{
return deposits[depositID - 1];
}
/**
@dev See {getFunding}
*/
function _getFunding(uint64 fundingID)
internal
view
returns (Funding storage)
{
return fundingList[fundingID - 1];
}
/**
@dev Converts a virtual token value into the corresponding principal value.
Principal refers to deposit + full interest + fee.
@param depositID The ID of the deposit of the virtual tokens
@param virtualTokenAmount The virtual token value
@return The corresponding principal value
*/
function _depositVirtualTokenToPrincipal(
uint64 depositID,
uint256 virtualTokenAmount
) internal view virtual returns (uint256) {
Deposit storage depositEntry = _getDeposit(depositID);
uint256 depositInterestRate = depositEntry.interestRate;
return
virtualTokenAmount.div(depositInterestRate + PRECISION).mul(
depositInterestRate + depositEntry.feeRate + PRECISION
);
}
/**
@dev See {Rescuable._authorizeRescue}
*/
function _authorizeRescue(
address, /*token*/
address /*target*/
) internal view override onlyOwner {}
/**
@dev See {surplus}
@param incomeIndex The moneyMarket's current incomeIndex
*/
function _surplus(uint256 incomeIndex)
internal
virtual
returns (bool isNegative, uint256 surplusAmount)
{
// compute totalInterestOwedToFunders
uint256 currentValue =
(incomeIndex *
sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex) /
EXTRA_PRECISION;
uint256 initialValue = totalFundedPrincipalAmount;
uint256 totalInterestOwedToFunders;
if (currentValue > initialValue) {
totalInterestOwedToFunders = currentValue - initialValue;
}
// compute surplus
uint256 totalValue = moneyMarket().totalValue(incomeIndex);
uint256 totalOwed =
totalDeposit +
totalInterestOwed +
totalFeeOwed +
totalInterestOwedToFunders;
if (totalValue >= totalOwed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = totalValue - totalOwed;
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = totalOwed - totalValue;
}
}
/**
Param setters (only callable by the owner)
*/
function setFeeModel(address newValue) external onlyOwner {
require(newValue.isContract(), "NOT_CONTRACT");
feeModel = IFeeModel(newValue);
emit ESetParamAddress(msg.sender, "feeModel", newValue);
}
function setInterestModel(address newValue) external onlyOwner {
require(newValue.isContract(), "NOT_CONTRACT");
interestModel = IInterestModel(newValue);
emit ESetParamAddress(msg.sender, "interestModel", newValue);
}
function setInterestOracle(address newValue) external onlyOwner {
require(newValue.isContract(), "NOT_CONTRACT");
interestOracle = IInterestOracle(newValue);
emit ESetParamAddress(msg.sender, "interestOracle", newValue);
}
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "NOT_CONTRACT");
moneyMarket().setRewards(newValue);
emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue);
}
function setMPHMinter(address newValue) external onlyOwner {
require(newValue.isContract(), "NOT_CONTRACT");
mphMinter = MPHMinter(newValue);
emit ESetParamAddress(msg.sender, "mphMinter", newValue);
}
function setMaxDepositPeriod(uint64 newValue) external onlyOwner {
require(newValue > 0, "BAD_VAL");
MaxDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MaxDepositPeriod", uint256(newValue));
}
function setMinDepositAmount(uint256 newValue) external onlyOwner {
require(newValue > 0, "BAD_VAL");
MinDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MinDepositAmount", newValue);
}
function setGlobalDepositCap(uint256 newValue) external onlyOwner {
GlobalDepositCap = newValue;
emit ESetParamUint(msg.sender, "GlobalDepositCap", newValue);
}
function setDepositNFTBaseURI(string calldata newURI) external onlyOwner {
depositNFT.setBaseURI(newURI);
}
function setDepositNFTContractURI(string calldata newURI)
external
onlyOwner
{
depositNFT.setContractURI(newURI);
}
function skimSurplus(address recipient) external onlyOwner {
(bool isNegative, uint256 surplusMagnitude) = surplus();
if (!isNegative) {
surplusMagnitude = moneyMarket().withdraw(surplusMagnitude);
stablecoin().safeTransfer(recipient, surplusMagnitude);
}
}
function decreaseFeeForDeposit(uint64 depositID, uint256 newFeeRate)
external
onlyOwner
{
Deposit storage depositStorage = _getDeposit(depositID);
uint256 feeRate = depositStorage.feeRate;
uint256 interestRate = depositStorage.interestRate;
uint256 virtualTokenTotalSupply =
depositStorage.virtualTokenTotalSupply;
require(newFeeRate < feeRate, "BAD_VAL");
uint256 depositAmount =
virtualTokenTotalSupply.div(interestRate + PRECISION);
// update fee rate
depositStorage.feeRate = newFeeRate;
// update interest rate
// fee reduction is allocated to interest
uint256 reducedFeeAmount = depositAmount.mul(feeRate - newFeeRate);
depositStorage.interestRate =
interestRate +
reducedFeeAmount.div(depositAmount);
// update global amounts
totalInterestOwed += reducedFeeAmount;
totalFeeOwed -= reducedFeeAmount;
}
uint256[32] private __gap;
}
| we're keeping the withdrawal amount in the money market | withdrawnStablecoinAmount = withdrawAmount;
| 6,479,273 | [
1,
1814,
4565,
19966,
326,
598,
9446,
287,
3844,
316,
326,
15601,
13667,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
598,
9446,
82,
30915,
12645,
6275,
273,
598,
9446,
6275,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "./library/Ownable.sol";
/**
* @title dForce's lending StatusOracle Contract
* @author dForce
*/
contract StatusOracle is Ownable {
using SafeMathUpgradeable for uint256;
/// @dev Set the address of the pause time.
address public pauser;
/// @dev Time zone (in seconds).
int256 internal timeZone;
/// @dev Market opening time, example: 9:00 is 9 * 3600 (in seconds).
uint256 internal marketOpeningTime;
/// @dev Duration, starting from market opening time (in seconds).
uint256 internal duration;
/// @dev Unusual opening and closing information
struct Status {
// Whether to activate the unusual status, true: activated; false: Not activated.
bool activated;
// Unusual market opening time.
uint256 marketOpeningTime;
// Unusual market closing time.
uint256 marketclosingTime;
}
/// @dev An unusual status on a certain day, key: timestamp / 1 days;
mapping(uint256 => Status) internal date;
/// @dev Pause the timestamp, only the current day (according to the time zone).
uint256 internal pauseTime;
/// @dev Asset suspension timestamp, used to suspend specific assets only on the current day (according to the time zone).
mapping(address => uint256) internal assetPauseTime;
/// @dev Emitted when `pauser` is changed.
event SetPauser(address oldPauser, address newPauser);
/// @dev Emitted when `timeZone` is changed.
event SetTimeZone(int256 oldTimeZone, int256 newTimeZone);
/// @dev Emitted when `marketOpeningTime` is changed.
event SetMarketOpeningTime(uint256 oldMarketOpeningTime, uint256 newMarketOpeningTime);
/// @dev Emitted when `duration` is changed.
event SetDuration(uint256 oldDuration, uint256 newDuration);
/// @dev Emitted when `date` is set.
event SetDate(uint256 timestamp, uint256 timeKey, uint256 marketOpeningTime, uint256 marketclosingTime, bool activated);
/// @dev Emitted when `pauseTime` is changed.
event SetPauseTime(uint256 oldPauseTime, uint256 newPauseTime);
/// @dev Emitted when `assetPauseTime` is changed.
event SetAssetPauseTime(address asset, uint256 oldPauseTime, uint256 newPauseTime);
/**
* @dev The constructor sets some data and initializes the owner
* @param _pauser New pauser.
* @param _timeZone Time zone.
* @param _marketOpeningTime The market is open every day.
* @param _duration Market duration.
*/
constructor(
address _pauser,
int256 _timeZone,
uint256 _marketOpeningTime,
uint256 _duration
) public {
__Ownable_init();
_setPauser(_pauser);
_setTimeZone(_timeZone);
_setMarketOpeningTime(_marketOpeningTime);
_setDuration(_duration);
}
/**
* @dev Throws if called by any account other than owner or pauser.
*/
modifier pauserAndOwner() {
require(pauser == msg.sender || owner == msg.sender, "pauserAndOwner: caller is not owner or pauser!");
_;
}
/**
* @dev Check if the time is valid.
*/
modifier isValidTime(uint256 _time) {
require(_time < 24 hours, "isValidTime: Not a valid time!");
_;
}
/**
* @notice Set new pauser.
* @dev Owner function to change of pauser.
* @param _pauser New pauser.
*/
function _setPauser(address _pauser) public onlyOwner {
// Gets current pauser.
address _oldPauser = pauser;
require(
_pauser != address(0) && _pauser != _oldPauser,
"_setPauser: New pauser can not be zero address or pauser has been set!"
);
// Sets new pauser.
pauser = _pauser;
emit SetPauser(_oldPauser, _pauser);
}
/**
* @notice Set new timeZone.
* @dev Owner function to change of timeZone.
* @param _timeZone New timeZone.
*/
function _setTimeZone(int256 _timeZone) public onlyOwner {
// Gets current timeZone.
int256 _oldTimeZone = timeZone;
require(
_timeZone >= -11 hours && _timeZone <= 11 hours && _timeZone != _oldTimeZone,
"_setTimeZone: New timeZone Exceeding the setting range or timeZone has been set!"
);
// Sets new timeZone.
timeZone = _timeZone;
emit SetTimeZone(_oldTimeZone, _timeZone);
}
/**
* @notice Set new marketOpeningTime.
* @dev Owner function to change of marketOpeningTime.
* @param _marketOpeningTime New marketOpeningTime.
*/
function _setMarketOpeningTime(uint256 _marketOpeningTime) public onlyOwner isValidTime(_marketOpeningTime) {
// Gets current marketOpeningTime.
uint256 _oldMarketOpeningTime = marketOpeningTime;
require(
_marketOpeningTime != _oldMarketOpeningTime,
"_setMarketOpeningTime: marketOpeningTime has been set!"
);
// Sets new marketOpeningTime.
marketOpeningTime = _marketOpeningTime;
emit SetMarketOpeningTime(_oldMarketOpeningTime, _marketOpeningTime);
}
/**
* @notice Set new duration.
* @dev Owner function to change of duration.
* @param _duration New duration.
*/
function _setDuration(uint256 _duration) public onlyOwner isValidTime(_duration) {
// Gets current duration.
uint256 _oldDuration = duration;
require(
_duration != _oldDuration,
"_setDuration: duration has been set!"
);
// Sets new duration.
duration = _duration;
emit SetDuration(_oldDuration, _duration);
}
/**
* @notice Set an unusual status for a certain day.
* @dev Owner function to set of date unusual status.
* @param _timestamp Unusual timestamp.
* @param _marketOpeningTime Unusual market opening time.
* @param _marketclosingTime Unusual market closing time.
*/
function _setDate(uint256 _timestamp, uint256 _marketOpeningTime, uint256 _marketclosingTime)
public
onlyOwner
isValidTime(_marketOpeningTime)
isValidTime(_marketclosingTime)
{
require(
_marketOpeningTime != _marketclosingTime,
"_setDate: _marketOpeningTime and _marketclosingTime cannot be the same!"
);
Status storage _date = date[_timestamp / 1 days];
_date.marketOpeningTime = _marketOpeningTime;
_date.marketclosingTime = _marketclosingTime;
_date.activated = true;
emit SetDate(_timestamp, _timestamp / 1 days, _marketOpeningTime, _marketclosingTime, true);
}
function _setDateBatch(uint256[] calldata _timestamps, uint256[] calldata _marketOpeningTimes, uint256[] calldata _marketclosingTimes) external {
require(
_timestamps.length == _marketOpeningTimes.length && _marketOpeningTimes.length == _marketclosingTimes.length ,
"_setDate: _timestamps & _marketOpeningTimes & _marketclosingTimes must match the current length!"
);
for (uint256 i = 0; i < _timestamps.length; i++) {
_setDate(_timestamps[i], _marketOpeningTimes[i], _marketclosingTimes[i]);
}
}
/**
* @notice Cancel the unusual status.
* @dev Owner function cancels unusual status.
* @param _timestamp Unusual timestamp.
*/
function _disableDate(uint256 _timestamp) public onlyOwner {
Status storage _date = date[_timestamp / 1 days];
_date.marketOpeningTime = 0;
_date.marketclosingTime = 0;
_date.activated = false;
emit SetDate(_timestamp, _timestamp / 1 days, 0, 0, false);
}
function _disableDateBatch(uint256[] calldata _timestamps) external {
for (uint256 i = 0; i < _timestamps.length; i++) {
_disableDate(_timestamps[i]);
}
}
/**
* @notice Called by the contract owner to unpause, returns to normal status.
* @dev clear pauseTime.
*/
function _unpause() external onlyOwner {
uint256 _oldPauseTime;
(_oldPauseTime, pauseTime) = (pauseTime, 0);
emit SetPauseTime(_oldPauseTime, 0);
}
/**
* @notice Called by the contract owner to unpause an asset, returns to normal status.
* @dev clear assetPauseTime.
* @param _asset Asset for which to set the `assetPauseTime`.
*/
function _unpauseAsset(address _asset) external onlyOwner {
uint256 _oldAssetPauseTime;
(_oldAssetPauseTime, assetPauseTime[_asset]) = (assetPauseTime[_asset], 0);
emit SetAssetPauseTime(_asset, _oldAssetPauseTime, 0);
}
/**
* @notice Called by the contract pauser or owner to pause, triggers stopped status.
* @dev Set pauseTime to the current timestamp.
*/
function pause() external pauserAndOwner {
uint256 _oldPauseTime;
(_oldPauseTime, pauseTime) = (pauseTime, block.timestamp);
emit SetPauseTime(_oldPauseTime, pauseTime);
}
/**
* @notice Called by the contract pauser or owner to pause an asset, triggers stopped status.
* @dev Set assetPauseTime to the current timestamp.
* @param _asset Asset for which to set the `assetPauseTime`.
*/
function pauseAsset(address _asset) external pauserAndOwner {
uint256 _oldAssetPauseTime;
(_oldAssetPauseTime, assetPauseTime[_asset]) = (assetPauseTime[_asset], block.timestamp);
emit SetAssetPauseTime(_asset, _oldAssetPauseTime, assetPauseTime[_asset]);
}
/**
* @notice Get asset opening status.
* @dev Calculate the daily opening and closing time, filter weekends and other.
* @param _asset Asset for which to get the status.
* @param _timestamp Timestamp for which to get the status.
* @return true: available,false: unavailable.
*/
function _getAssetStatus(address _asset, uint256 _timestamp) internal view returns (bool) {
// Timestamp converted to the corresponding time zone.
uint256 _timeZone = uint256(timeZone);
uint256 _localTime = _timestamp + _timeZone;
// Greenwich Mean Time starts on Thursday. (_localTime % 1 weeks) / 1 days == 0, Thursday in this time zone.
// ((_localTime + 3 days) % 1 weeks) / 1 days == 0, Monday in this time zone,
// 0: Monday; 1: Tuesday; 2: Wednesday; 3: Thursday; 4: Friday; 5: Saturday; 6: Sunday.
uint256 _secondsPassedInWeek = _localTime.add(3 days) % 1 weeks;
// Filter weekend
if (_secondsPassedInWeek / 1 days > 4)
return false;
(uint256 _marketOpeningTime, uint256 _marketclosingTime) = (marketOpeningTime, marketOpeningTime + duration);
// When the non-normal status has been activated, update the opening and closing time.
Status storage _date = date[_localTime / 1 days];
if (_date.activated)
(_marketOpeningTime, _marketclosingTime) = (_date.marketOpeningTime, _date.marketclosingTime);
// Calculate the time of day
uint256 _secondsPassedInDay = _secondsPassedInWeek % 1 days;
// Filter before opening and after closing
if (_secondsPassedInDay < _marketOpeningTime || _secondsPassedInDay > _marketclosingTime)
return false;
uint256 _pauseTime = assetPauseTime[_asset] > pauseTime ? assetPauseTime[_asset] : pauseTime;
// Filter pause time, when the pause time and local time are on the same day.
if ((_pauseTime + _timeZone) / 1 days == _localTime / 1 days)
return false;
return true;
}
/**
* @notice Get asset opening status.
* @dev Get the asset status of the current block time.
* @param _asset Asset for which to get the status.
* @return true: available,false: unavailable.
*/
function getAssetPriceStatus(address _asset) external view returns (bool) {
return _getAssetStatus(_asset, block.timestamp);
}
function getAssetStatus(address _asset, uint256 _timestamp) external view returns (bool) {
return _getAssetStatus(_asset, _timestamp);
}
/**
* @dev Get timeZone.
* @return Time zone (in seconds).
*/
function getTimeZone() external view returns (int256) {
return timeZone;
}
/**
* @dev Get market opening time.
* @return Market opening time (in seconds).
*/
function getMarketOpeningTime() external view returns (uint256) {
return marketOpeningTime;
}
/**
* @dev Get duration.
* @return Duration (in seconds).
*/
function getDuration() external view returns (uint256) {
return duration;
}
/**
* @dev Get unusual opening and closing information.
* @param _timestamp Unusual timestamp.
* @return timestamp key, Active status, Unusual market opening time, Unusual market closing time .
*/
function getDateInfo(uint256 _timestamp) external view returns (uint256, bool ,uint256, uint256) {
uint256 _key = _timestamp / 1 days;
Status storage _date = date[_key];
return (_key, _date.activated, _date.marketOpeningTime, _date.marketclosingTime);
}
/**
* @dev Get pauseTime.
* @return Pause the timestamp.
*/
function getPauseTime() external view returns (uint256) {
return pauseTime;
}
/**
* @dev Get assetPauseTime.
* @param _asset Asset for which to set the `assetPauseTime`.
* @return Asset pause timestamp.
*/
function getAssetPauseTime(address _asset) external view returns (uint256) {
return assetPauseTime[_asset];
}
}
| @dev Emitted when `pauseTime` is changed. | event SetPauseTime(uint256 oldPauseTime, uint256 newPauseTime);
| 5,542,052 | [
1,
1514,
11541,
1347,
1375,
19476,
950,
68,
353,
3550,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
1000,
19205,
950,
12,
11890,
5034,
1592,
19205,
950,
16,
2254,
5034,
394,
19205,
950,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/contracts/utils/Address.sol
// pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/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");
}
}
}
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: contracts/governance/common/ProxyStorage.sol
// pragma solidity 0.6.10;
/**
* All storage must be declared here
* New storage must be appended to the end
* Never remove items from this list
*/
contract ProxyStorage {
bool public initalized;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(uint144 => uint256) attributes_Depricated;
address owner_;
address pendingOwner_;
mapping(address => address) public delegates; // A record of votes checkpoints for each account, by index
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint32 fromBlock;
uint96 votes;
}
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; // A record of votes checkpoints for each account, by index
mapping(address => uint32) public numCheckpoints; // The number of checkpoints for each account
mapping(address => uint256) public nonces;
/* Additionally, we have several keccak-based storage locations.
* If you add more keccak-based storage mappings, such as mappings, you must document them here.
* If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision.
* A preimage collision can be used to attack the contract by treating one storage location as another,
* which would always be a critical issue.
* Carefully examine future keccak-based storage to ensure there can be no preimage collisions.
*******************************************************************************************************
** length input usage
*******************************************************************************************************
** 19 "trueXXX.proxy.owner" Proxy Owner
** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner
** 28 "trueXXX.proxy.implementation" Proxy Implementation
** 64 uint256(address),uint256(1) balanceOf
** 64 uint256(address),keccak256(uint256(address),uint256(2)) allowance
** 64 uint256(address),keccak256(bytes32,uint256(3)) attributes
**/
}
// Dependency file: contracts/governance/common/ERC20.sol
/**
* @notice This is a copy of openzeppelin ERC20 contract with removed state variables.
* Removing state variables has been necessary due to proxy pattern usage.
* Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol:
* - Remove state variables _name, _symbol, _decimals
* - Use state variables balances, allowances, totalSupply from ProxyStorage
* - Remove constructor
* - Solidity version changed from ^0.6.0 to 0.6.10
* - Contract made abstract
* - Remove inheritance from IERC20 because of ProxyStorage name conflicts
*
* See also: ClaimableOwnable.sol and ProxyStorage.sol
*/
// pragma solidity 0.6.10;
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// import {ProxyStorage} from "contracts/governance/common/ProxyStorage.sol";
// prettier-ignore
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
abstract contract ERC20 is ProxyStorage, Context {
using SafeMath for uint256;
using Address for address;
/**
* @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 Returns the name of the token.
*/
function name() public virtual pure returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public virtual pure returns (string memory);
/**
* @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 virtual pure returns (uint8) {
return 18;
}
/**
* @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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual 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 returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance[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, allowance[_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, allowance[_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);
balanceOf[sender] = balanceOf[sender].sub(amount, "ERC20: transfer amount exceeds balance");
balanceOf[recipient] = balanceOf[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);
balanceOf[account] = balanceOf[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);
balanceOf[account] = balanceOf[account].sub(amount, "ERC20: burn amount exceeds balance");
totalSupply = totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
allowance[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].
*/
// solhint-disable-next-line no-empty-blocks
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Dependency file: contracts/governance/interface/IVoteToken.sol
// pragma solidity ^0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVoteToken {
function delegate(address delegatee) external;
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
function getCurrentVotes(address account) external view returns (uint96);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
}
interface IVoteTokenWithERC20 is IVoteToken, IERC20 {}
// Dependency file: contracts/governance/VoteToken.sol
// AND COPIED FROM https://github.com/compound-finance/compound-protocol/blob/c5fcc34222693ad5f547b14ed01ce719b5f4b000/contracts/Governance/Comp.sol
// Copyright 2020 Compound Labs, Inc.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Ctrl+f for OLD to see all the modifications.
// pragma solidity 0.6.10;
// import {ERC20} from "contracts/governance/common/ERC20.sol";
// import {IVoteToken} from "contracts/governance/interface/IVoteToken.sol";
/**
* @title VoteToken
* @notice Custom token which tracks voting power for governance
* @dev This is an abstraction of a fork of the Compound governance contract
* VoteToken is used by TRU and stkTRU to allow tracking voting power
* Checkpoints are created every time state is changed which record voting power
* Inherits standard ERC20 behavior
*/
abstract contract VoteToken is ERC20, IVoteToken {
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
function delegate(address delegatee) public override {
return _delegate(msg.sender, delegatee);
}
/**
* @dev Delegate votes using signature
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public override {
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("", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TrustToken::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TrustToken::delegateBySig: invalid nonce");
require(now <= expiry, "TrustToken::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @dev Get current voting power for an account
* @param account Account to get voting power for
* @return Voting power for an account
*/
function getCurrentVotes(address account) public virtual override view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @dev Get voting power at a specific block for an account
* @param account Account to get voting power for
* @param blockNumber Block to get voting power at
* @return Voting power for an account at specific block
*/
function getPriorVotes(address account, uint256 blockNumber) public virtual override view returns (uint96) {
require(blockNumber < block.number, "TrustToken::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;
}
/**
* @dev Internal function to delegate voting power to an account
* @param delegator Account to delegate votes from
* @param delegatee Account to delegate votes to
*/
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
// OLD: uint96 delegatorBalance = balanceOf(delegator);
uint96 delegatorBalance = safe96(_balanceOf(delegator), "StkTruToken: uint96 overflow");
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _balanceOf(address account) internal view virtual returns (uint256) {
return balanceOf[account];
}
function _transfer(
address _from,
address _to,
uint256 _value
) internal virtual override {
super._transfer(_from, _to, _value);
_moveDelegates(delegates[_from], delegates[_to], safe96(_value, "StkTruToken: uint96 overflow"));
}
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
_moveDelegates(address(0), delegates[account], safe96(amount, "StkTruToken: uint96 overflow"));
}
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_moveDelegates(delegates[account], address(0), safe96(amount, "StkTruToken: uint96 overflow"));
}
/**
* @dev internal function to move delegates between accounts
*/
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "TrustToken::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "TrustToken::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
* @dev internal function to write a checkpoint for voting power
*/
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "TrustToken::_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);
}
/**
* @dev internal function to convert from uint256 to uint32
*/
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
/**
* @dev internal function to convert from uint256 to uint96
*/
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
/**
* @dev internal safe math function to add two uint96 numbers
*/
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev internal safe math function to subtract two uint96 numbers
*/
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev internal function to get chain ID
*/
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// Dependency file: contracts/truefi/interface/ITrueDistributor.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ITrueDistributor {
function trustToken() external view returns (IERC20);
function farm() external view returns (address);
function distribute() external;
function nextDistribution() external view returns (uint256);
function empty() external;
}
// Dependency file: contracts/governance/common/StkClaimableContract.sol
// pragma solidity 0.6.10;
// import {ProxyStorage} from "contracts/governance/common/ProxyStorage.sol";
/**
* @title ClaimableContract
* @dev The ClaimableContract contract is a copy of Claimable Contract by Zeppelin.
and provides basic authorization control functions. Inherits storage layout of
ProxyStorage.
*/
contract StkClaimableContract is ProxyStorage {
function owner() public view returns (address) {
return owner_;
}
function pendingOwner() public view returns (address) {
return pendingOwner_;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sets the original `owner` of the contract to the sender
* at construction. Must then be reinitialized
*/
constructor() public {
owner_ = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner_, "only owner");
_;
}
/**
* @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) public onlyOwner {
pendingOwner_ = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
address _pendingOwner = pendingOwner_;
emit OwnershipTransferred(owner_, _pendingOwner);
owner_ = _pendingOwner;
pendingOwner_ = address(0);
}
}
// Dependency file: contracts/common/interface/IPauseableContract.sol
// pragma solidity 0.6.10;
/**
* @dev interface to allow standard pause function
*/
interface IPauseableContract {
function setPauseStatus(bool pauseStatus) external;
}
// Root file: contracts/governance/StkTruToken.sol
pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// import {VoteToken} from "contracts/governance/VoteToken.sol";
// import {ITrueDistributor} from "contracts/truefi/interface/ITrueDistributor.sol";
// import {StkClaimableContract} from "contracts/governance/common/StkClaimableContract.sol";
// import {IPauseableContract} from "contracts/common/interface/IPauseableContract.sol";
/**
* @title stkTRU
* @dev Staking contract for TrueFi
* TRU is staked and stored in the contract
* stkTRU is minted when staking
* Holders of stkTRU accrue rewards over time
* Rewards are paid in TRU and tfUSD
* stkTRU can be used to vote in governance
* stkTRU can be used to rate and approve loans
*/
contract StkTruToken is VoteToken, StkClaimableContract, IPauseableContract, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant PRECISION = 1e30;
uint256 private constant MIN_DISTRIBUTED_AMOUNT = 100e8;
struct FarmRewards {
// track overall cumulative rewards
uint256 cumulativeRewardPerToken;
// track previous cumulate rewards for accounts
mapping(address => uint256) previousCumulatedRewardPerToken;
// track claimable rewards for accounts
mapping(address => uint256) claimableReward;
// track total rewards
uint256 totalClaimedRewards;
uint256 totalFarmRewards;
}
struct ScheduledTfUsdRewards {
uint64 timestamp;
uint96 amount;
}
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
IERC20 public tru;
IERC20 public tfusd;
ITrueDistributor public distributor;
address public liquidator;
uint256 public stakeSupply;
mapping(address => uint256) private cooldowns;
uint256 public cooldownTime;
uint256 public unstakePeriodDuration;
mapping(IERC20 => FarmRewards) public farmRewards;
uint32[] public sortedScheduledRewardIndices;
ScheduledTfUsdRewards[] public scheduledRewards;
uint256 public undistributedTfusdRewards;
uint32 public nextDistributionIndex;
mapping(address => bool) public whitelistedFeePayers;
mapping(address => uint256) public receivedDuringCooldown;
// allow pausing of deposits
bool public pauseStatus;
IERC20 public feeToken;
// ======= STORAGE DECLARATION END ============
event Stake(address indexed staker, uint256 amount);
event Unstake(address indexed staker, uint256 burntAmount);
event Claim(address indexed who, IERC20 indexed token, uint256 amountClaimed);
event Withdraw(uint256 amount);
event Cooldown(address indexed who, uint256 endTime);
event CooldownTimeChanged(uint256 newUnstakePeriodDuration);
event UnstakePeriodDurationChanged(uint256 newUnstakePeriodDuration);
event FeePayerWhitelistingStatusChanged(address payer, bool status);
event PauseStatusChanged(bool pauseStatus);
event FeeTokenChanged(IERC20 token);
event LiquidatorChanged(address liquidator);
/**
* @dev pool can only be joined when it's unpaused
*/
modifier joiningNotPaused() {
require(!pauseStatus, "StkTruToken: Joining the pool is paused");
_;
}
/**
* @dev Only Liquidator contract can perform TRU liquidations
*/
modifier onlyLiquidator() {
require(msg.sender == liquidator, "StkTruToken: Can be called only by the liquidator");
_;
}
/**
* @dev Only whitelisted payers can pay fees
*/
modifier onlyWhitelistedPayers() {
require(whitelistedFeePayers[msg.sender], "StkTruToken: Can be called only by whitelisted payers");
_;
}
/**
* Get TRU from distributor
*/
modifier distribute() {
// pull TRU from distributor
// do not pull small amounts to save some gas
// only pull if there is distribution and distributor farm is set to this farm
if (distributor.nextDistribution() > MIN_DISTRIBUTED_AMOUNT && distributor.farm() == address(this)) {
distributor.distribute();
}
_;
}
/**
* Update all rewards when an account changes state
* @param account Account to update rewards for
*/
modifier update(address account) {
updateTotalRewards(tru);
updateClaimableRewards(tru, account);
updateTotalRewards(tfusd);
updateClaimableRewards(tfusd, account);
updateTotalRewards(feeToken);
updateClaimableRewards(feeToken, account);
_;
}
/**
* Update rewards for a specific token when an account changes state
* @param account Account to update rewards for
* @param token Token to update rewards for
*/
modifier updateRewards(address account, IERC20 token) {
if (token == tru) {
updateTotalRewards(tru);
updateClaimableRewards(tru, account);
} else if (token == tfusd) {
updateTotalRewards(tfusd);
updateClaimableRewards(tfusd, account);
} else if (token == feeToken) {
updateTotalRewards(feeToken);
updateClaimableRewards(feeToken, account);
}
_;
}
/**
* @dev Initialize contract and set default values
* @param _tru TRU token
* @param _tfusd tfUSD token
* @param _feeToken Token for fees, currently tfUSDC
* @param _distributor Distributor for this contract
* @param _liquidator Liquidator for staked TRU
*/
function initialize(
IERC20 _tru,
IERC20 _tfusd,
IERC20 _feeToken,
ITrueDistributor _distributor,
address _liquidator
) public {
require(!initalized, "StkTruToken: Already initialized");
tru = _tru;
tfusd = _tfusd;
feeToken = _feeToken;
distributor = _distributor;
liquidator = _liquidator;
cooldownTime = 14 days;
unstakePeriodDuration = 2 days;
owner_ = msg.sender;
initalized = true;
}
/**
* @dev Set tfUSDC address
* @param _feeToken Address of tfUSDC to be set
*/
function setFeeToken(IERC20 _feeToken) external onlyOwner {
require(rewardBalance(feeToken) == 0, "StkTruToken: Cannot replace fee token with underlying rewards");
feeToken = _feeToken;
emit FeeTokenChanged(_feeToken);
}
/**
* @dev Set liquidator address
* @param _liquidator Address of liquidator to be set
*/
function setLiquidator(address _liquidator) external onlyOwner {
liquidator = _liquidator;
emit LiquidatorChanged(_liquidator);
}
/**
* @dev Owner can use this function to add new addresses to payers whitelist
* Only whitelisted payers can call payFee method
* @param payer Address that is being added to or removed from whitelist
* @param status New whitelisting status
*/
function setPayerWhitelistingStatus(address payer, bool status) external onlyOwner {
whitelistedFeePayers[payer] = status;
emit FeePayerWhitelistingStatusChanged(payer, status);
}
/**
* @dev Owner can use this function to set cooldown time
* Cooldown time defines how long a staker waits to unstake TRU
* @param newCooldownTime New cooldown time for stakers
*/
function setCooldownTime(uint256 newCooldownTime) external onlyOwner {
// Avoid overflow
require(newCooldownTime <= 100 * 365 days, "StkTruToken: Cooldown too large");
cooldownTime = newCooldownTime;
emit CooldownTimeChanged(newCooldownTime);
}
/**
* @dev Allow pausing of deposits in case of emergency
* @param status New deposit status
*/
function setPauseStatus(bool status) external override onlyOwner {
pauseStatus = status;
emit PauseStatusChanged(status);
}
/**
* @dev Owner can set unstake period duration
* Unstake period defines how long after cooldown a user has to withdraw stake
* @param newUnstakePeriodDuration New unstake period
*/
function setUnstakePeriodDuration(uint256 newUnstakePeriodDuration) external onlyOwner {
require(newUnstakePeriodDuration > 0, "StkTruToken: Unstake period cannot be 0");
// Avoid overflow
require(newUnstakePeriodDuration <= 100 * 365 days, "StkTruToken: Unstake period too large");
unstakePeriodDuration = newUnstakePeriodDuration;
emit UnstakePeriodDurationChanged(newUnstakePeriodDuration);
}
/**
* @dev Stake TRU for stkTRU
* Updates rewards when staking
* @param amount Amount of TRU to stake for stkTRU
*/
function stake(uint256 amount) external distribute update(msg.sender) joiningNotPaused {
_stakeWithoutTransfer(amount);
tru.safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @dev Unstake stkTRU for TRU
* Can only unstake when cooldown complete and within unstake period
* Claims rewards when unstaking
* @param amount Amount of stkTRU to unstake for TRU
*/
function unstake(uint256 amount) external distribute update(msg.sender) nonReentrant {
require(amount > 0, "StkTruToken: Cannot unstake 0");
require(unstakable(msg.sender) >= amount, "StkTruToken: Insufficient balance");
require(unlockTime(msg.sender) <= block.timestamp, "StkTruToken: Stake on cooldown");
_claim(tru);
_claim(tfusd);
_claim(feeToken);
uint256 amountToTransfer = amount.mul(stakeSupply).div(totalSupply);
_burn(msg.sender, amount);
stakeSupply = stakeSupply.sub(amountToTransfer);
tru.safeTransfer(msg.sender, amountToTransfer);
emit Unstake(msg.sender, amount);
}
/**
* @dev Initiate cooldown period
*/
function cooldown() public {
cooldowns[msg.sender] = block.timestamp;
receivedDuringCooldown[msg.sender] = 0;
emit Cooldown(msg.sender, block.timestamp.add(cooldownTime));
}
/**
* @dev Withdraw TRU from the contract for liquidation
* @param amount Amount to withdraw for liquidation
*/
function withdraw(uint256 amount) external onlyLiquidator {
stakeSupply = stakeSupply.sub(amount);
tru.safeTransfer(liquidator, amount);
emit Withdraw(amount);
}
/**
* @dev View function to get unlock time for an account
* @param account Account to get unlock time for
* @return Unlock time for account
*/
function unlockTime(address account) public view returns (uint256) {
if (cooldowns[account] == 0 || cooldowns[account].add(cooldownTime).add(unstakePeriodDuration) < block.timestamp) {
return type(uint256).max;
}
return cooldowns[account].add(cooldownTime);
}
/**
* @dev Give tfUSD as origination fee to stake.this
* 50% are given immediately and 50% after `endTime` passes
*/
function payFee(uint256 amount, uint256 endTime) external onlyWhitelistedPayers {
require(endTime < type(uint64).max, "StkTruToken: time overflow");
require(amount < type(uint96).max, "StkTruToken: amount overflow");
tfusd.safeTransferFrom(msg.sender, address(this), amount);
undistributedTfusdRewards = undistributedTfusdRewards.add(amount.div(2));
scheduledRewards.push(ScheduledTfUsdRewards({amount: uint96(amount.div(2)), timestamp: uint64(endTime)}));
uint32 newIndex = findPositionForTimestamp(endTime);
insertAt(newIndex, uint32(scheduledRewards.length) - 1);
}
/**
* @dev Claim all rewards
*/
function claim() external distribute update(msg.sender) {
_claim(tru);
_claim(tfusd);
_claim(feeToken);
}
/**
* @dev Claim rewards for specific token
* Allows account to claim specific token to save gas
* @param token Token to claim rewards for
*/
function claimRewards(IERC20 token) external distribute updateRewards(msg.sender, token) {
require(token == tfusd || token == tru || token == feeToken, "Token not supported for rewards");
_claim(token);
}
/**
* @dev Claim TRU rewards, transfer in extraStakeAmount, and
* stake both the rewards and the new amount.
* Allows account to save more gas by avoiding out-and-back transfers of rewards
*/
function claimRestake(uint256 extraStakeAmount) external distribute update(msg.sender) {
uint256 amount = _claimWithoutTransfer(tru).add(extraStakeAmount);
_stakeWithoutTransfer(amount);
if (extraStakeAmount > 0) {
tru.safeTransferFrom(msg.sender, address(this), extraStakeAmount);
}
}
/**
* @dev View to estimate the claimable reward for an account
* @param account Account to get claimable reward for
* @param token Token to get rewards for
* @return claimable rewards for account
*/
function claimable(address account, IERC20 token) external view returns (uint256) {
// estimate pending reward from distributor
uint256 pending = token == tru ? distributor.nextDistribution() : 0;
// calculate total rewards (including pending)
uint256 newTotalFarmRewards = rewardBalance(token)
.add(pending > MIN_DISTRIBUTED_AMOUNT ? pending : 0)
.add(farmRewards[token].totalClaimedRewards)
.mul(PRECISION);
// calculate block reward
uint256 totalBlockReward = newTotalFarmRewards.sub(farmRewards[token].totalFarmRewards);
// calculate next cumulative reward per token
uint256 nextCumulativeRewardPerToken = farmRewards[token].cumulativeRewardPerToken.add(totalBlockReward.div(totalSupply));
// return claimable reward for this account
return
farmRewards[token].claimableReward[account].add(
balanceOf[account]
.mul(nextCumulativeRewardPerToken.sub(farmRewards[token].previousCumulatedRewardPerToken[account]))
.div(PRECISION)
);
}
/**
* @dev max amount of stkTRU than can be unstaked after current cooldown period is over
*/
function unstakable(address staker) public view returns (uint256) {
if (unlockTime(staker) == type(uint256).max) {
return balanceOf[staker];
}
if (receivedDuringCooldown[staker] > balanceOf[staker]) {
return 0;
}
return balanceOf[staker].sub(receivedDuringCooldown[staker]);
}
/**
* @dev Prior votes votes are calculated as priorVotes * stakedSupply / totalSupply
* This dilutes voting power when TRU is liquidated
* @param account Account to get current voting power for
* @param blockNumber Block to get prior votes at
* @return prior voting power for account and block
*/
function getPriorVotes(address account, uint256 blockNumber) public override view returns (uint96) {
uint96 votes = super.getPriorVotes(account, blockNumber);
return safe96(stakeSupply.mul(votes).div(totalSupply), "StkTruToken: uint96 overflow");
}
/**
* @dev Current votes are calculated as votes * stakedSupply / totalSupply
* This dilutes voting power when TRU is liquidated
* @param account Account to get current voting power for
* @return voting power for account
*/
function getCurrentVotes(address account) public override view returns (uint96) {
uint96 votes = super.getCurrentVotes(account);
return safe96(stakeSupply.mul(votes).div(totalSupply), "StkTruToken: uint96 overflow");
}
function decimals() public override pure returns (uint8) {
return 8;
}
function rounding() public pure returns (uint8) {
return 8;
}
function name() public override pure returns (string memory) {
return "Staked TrueFi";
}
function symbol() public override pure returns (string memory) {
return "stkTRU";
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override distribute update(sender) {
updateClaimableRewards(tru, recipient);
updateClaimableRewards(tfusd, recipient);
updateClaimableRewards(feeToken, recipient);
// unlockTime returns MAX_UINT256 when there's no ongoing cooldown for the address
if (unlockTime(recipient) != type(uint256).max) {
receivedDuringCooldown[recipient] = receivedDuringCooldown[recipient].add(amount);
}
if (unlockTime(sender) != type(uint256).max) {
receivedDuringCooldown[sender] = receivedDuringCooldown[sender].sub(min(receivedDuringCooldown[sender], amount));
}
super._transfer(sender, recipient, amount);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Internal claim function
* Claim rewards for a specific ERC20 token
* @param token Token to claim rewards for
*/
function _claim(IERC20 token) internal {
uint256 rewardToClaim = _claimWithoutTransfer(token);
if (rewardToClaim > 0) {
token.safeTransfer(msg.sender, rewardToClaim);
}
}
/**
* @dev Internal claim function that returns the transfer value
* Claim rewards for a specific ERC20 token to return in a uint256
* @param token Token to claim rewards for
*/
function _claimWithoutTransfer(IERC20 token) internal returns (uint256) {
uint256 rewardToClaim = farmRewards[token].claimableReward[msg.sender];
farmRewards[token].totalClaimedRewards = farmRewards[token].totalClaimedRewards.add(rewardToClaim);
farmRewards[token].claimableReward[msg.sender] = 0;
emit Claim(msg.sender, token, rewardToClaim);
return rewardToClaim;
}
/**
* @dev Internal stake of TRU for stkTRU from a uint256
* Caller is responsible for ensuring amount is transferred from a valid source
* @param amount Amount of TRU to stake for stkTRU
*/
function _stakeWithoutTransfer(uint256 amount) internal {
require(amount > 0, "StkTruToken: Cannot stake 0");
if (cooldowns[msg.sender] != 0 && cooldowns[msg.sender].add(cooldownTime).add(unstakePeriodDuration) > block.timestamp) {
cooldown();
}
if (delegates[msg.sender] == address(0)) {
delegates[msg.sender] = msg.sender;
}
uint256 amountToMint = stakeSupply == 0 ? amount : amount.mul(totalSupply).div(stakeSupply);
_mint(msg.sender, amountToMint);
stakeSupply = stakeSupply.add(amount);
emit Stake(msg.sender, amount);
}
/**
* @dev Get reward balance of this contract for a token
* @param token Token to get reward balance for
* @return Reward balance for token
*/
function rewardBalance(IERC20 token) internal view returns (uint256) {
if (address(token) == address(0)) {
return 0;
}
if (token == tru) {
return token.balanceOf(address(this)).sub(stakeSupply);
}
if (token == tfusd) {
return token.balanceOf(address(this)).sub(undistributedTfusdRewards);
}
if (token == feeToken) {
return token.balanceOf(address(this));
}
return 0;
}
/**
* @dev Check if any scheduled rewards should be distributed
*/
function distributeScheduledRewards() internal {
uint32 index = nextDistributionIndex;
while (index < scheduledRewards.length && scheduledRewards[sortedScheduledRewardIndices[index]].timestamp < block.timestamp) {
undistributedTfusdRewards = undistributedTfusdRewards.sub(scheduledRewards[sortedScheduledRewardIndices[index]].amount);
index++;
}
if (nextDistributionIndex != index) {
nextDistributionIndex = index;
}
}
/**
* @dev Update rewards state for `token`
*/
function updateTotalRewards(IERC20 token) internal {
if (token == tfusd) {
distributeScheduledRewards();
}
// calculate total rewards
uint256 newTotalFarmRewards = rewardBalance(token).add(farmRewards[token].totalClaimedRewards).mul(PRECISION);
if (newTotalFarmRewards == farmRewards[token].totalFarmRewards) {
return;
}
// calculate block reward
uint256 totalBlockReward = newTotalFarmRewards.sub(farmRewards[token].totalFarmRewards);
// update farm rewards
farmRewards[token].totalFarmRewards = newTotalFarmRewards;
// if there are stakers
if (totalSupply > 0) {
farmRewards[token].cumulativeRewardPerToken = farmRewards[token].cumulativeRewardPerToken.add(
totalBlockReward.div(totalSupply)
);
}
}
/**
* @dev Update claimable rewards for a token and account
* @param token Token to update claimable rewards for
* @param user Account to update claimable rewards for
*/
function updateClaimableRewards(IERC20 token, address user) internal {
// update claimable reward for sender
if (balanceOf[user] > 0) {
farmRewards[token].claimableReward[user] = farmRewards[token].claimableReward[user].add(
balanceOf[user]
.mul(farmRewards[token].cumulativeRewardPerToken.sub(farmRewards[token].previousCumulatedRewardPerToken[user]))
.div(PRECISION)
);
}
// update previous cumulative for sender
farmRewards[token].previousCumulatedRewardPerToken[user] = farmRewards[token].cumulativeRewardPerToken;
}
/**
* @dev Find next distribution index given a timestamp
* @param timestamp Timestamp to find next distribution index for
*/
function findPositionForTimestamp(uint256 timestamp) internal view returns (uint32 i) {
for (i = nextDistributionIndex; i < sortedScheduledRewardIndices.length; i++) {
if (scheduledRewards[sortedScheduledRewardIndices[i]].timestamp > timestamp) {
break;
}
}
}
/**
* @dev internal function to insert distribution index in a sorted list
* @param index Index to insert at
* @param value Value at index
*/
function insertAt(uint32 index, uint32 value) internal {
sortedScheduledRewardIndices.push(0);
for (uint32 j = uint32(sortedScheduledRewardIndices.length) - 1; j > index; j--) {
sortedScheduledRewardIndices[j] = sortedScheduledRewardIndices[j - 1];
}
sortedScheduledRewardIndices[index] = value;
}
} | allow pausing of deposits | bool public pauseStatus;
| 11,985,966 | [
1,
5965,
6790,
9940,
434,
443,
917,
1282,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1426,
1071,
11722,
1482,
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,
-100
] |
pragma solidity ^0.4.24;
/**
* This utility library was forked from https://github.com/o0ragman0o/LibCLL
*/
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList {
mapping (uint256 => mapping (bool => uint256)) list;
uint256 length;
uint256 index;
}
/**
* @dev returns true if the list exists
* @param self stored linked list from contract
*/
function listExists(LinkedList storage self)
internal
view returns (bool) {
return self.length > 0;
}
/**
* @dev returns true if the node exists
* @param self stored linked list from contract
* @param _node a node to search for
*/
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool) {
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* @dev Returns the number of elements in the list
* @param self stored linked list from contract
*/
function sizeOf(LinkedList storage self)
internal
view
returns (uint256 numElements) {
return self.length;
}
/**
* @dev Returns the links of a node as a tuple
* @param self stored linked list from contract
* @param _node id of the node to get
*/
function getNode(LinkedList storage self, uint256 _node)
public
view
returns (bool, uint256, uint256) {
if (!nodeExists(self,_node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
/**
* @dev Returns the link of a node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node id of the node to step from
* @param _direction direction to step in
*/
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
public
view
returns (bool, uint256) {
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
/**
* @dev Can be used before `insert` to build an ordered list
* @param self stored linked list from contract
* @param _node an existing node to search from, e.g. HEAD.
* @param _value value to seek
* @param _direction direction to seek in
* @return next first node beyond '_node' in direction `_direction`
*/
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
public
view
returns (uint256) {
if (sizeOf(self) == 0) {
return 0;
}
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
/**
* @dev Creates a bidirectional link between two nodes on direction `_direction`
* @param self stored linked list from contract
* @param _node first node for linking
* @param _link node to link to in the _direction
*/
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction)
private {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
/**
* @dev Insert node `_new` beside existing node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node existing node
* @param _new new node to insert
* @param _direction direction to insert node in
*/
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction)
internal
returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
self.length++;
return true;
} else {
return false;
}
}
/**
* @dev removes an entry from the linked list
* @param self stored linked list from contract
* @param _node node to remove from the list
*/
function remove(LinkedList storage self, uint256 _node)
internal
returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) {
return 0;
}
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
self.length--;
return _node;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _index The node Id
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function add(LinkedList storage self, uint256 _index, bool _direction)
internal
returns (uint256) {
insert(self, HEAD, _index, _direction);
return self.index;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function push(LinkedList storage self, bool _direction)
internal
returns (uint256) {
self.index++;
insert(self, HEAD, self.index, _direction);
return self.index;
}
/**
* @dev pops the first entry from the linked list
* @param self stored linked list from contract
* @param _direction pop from the head (NEXT) or the tail (PREV)
*/
function pop(LinkedList storage self, bool _direction)
internal
returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
/**
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed to);
/**
* Constructor
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Only the owner of contract
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev transfer the ownership to other
* - Only the owner can operate
*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/**
* @dev Accept the ownership from last owner
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TripioToken {
string public name;
string public symbol;
uint8 public decimals;
function transfer(address _to, uint256 _value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}
contract TripioRoomNightData is Owned {
using LinkedListLib for LinkedListLib.LinkedList;
// Interface signature of erc165.
// bytes4(keccak256("supportsInterface(bytes4)"))
bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7;
// Interface signature of erc721 metadata.
// bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)"));
bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd;
// Interface signature of erc721.
// bytes4(keccak256("balanceOf(address)")) ^
// bytes4(keccak256("ownerOf(uint256)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^
// bytes4(keccak256("transferFrom(address,address,uint256)")) ^
// bytes4(keccak256("approve(address,uint256)")) ^
// bytes4(keccak256("setApprovalForAll(address,bool)")) ^
// bytes4(keccak256("getApproved(uint256)")) ^
// bytes4(keccak256("isApprovedForAll(address,address)"));
bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5;
// Base URI of token asset
string public tokenBaseURI;
// Authorized contracts
struct AuthorizedContract {
string name;
address acontract;
}
mapping (address=>uint256) public authorizedContractIds;
mapping (uint256 => AuthorizedContract) public authorizedContracts;
LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0);
// Rate plan prices
struct Price {
uint16 inventory; // Rate plan inventory
bool init; // Whether the price is initied
mapping (uint256 => uint256) tokens;
}
// Vendor hotel RPs
struct RatePlan {
string name; // Name of rate plan.
uint256 timestamp; // Create timestamp.
bytes32 ipfs; // The address of rate plan detail on IPFS.
Price basePrice; // The base price of rate plan
mapping (uint256 => Price) prices; // date -> Price
}
// Vendors
struct Vendor {
string name; // Name of vendor.
address vendor; // Address of vendor.
uint256 timestamp; // Create timestamp.
bool valid; // Whether the vendor is valid(default is true)
LinkedListLib.LinkedList ratePlanList;
mapping (uint256=>RatePlan) ratePlans;
}
mapping (address => uint256) public vendorIds;
mapping (uint256 => Vendor) vendors;
LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0);
// Supported digital currencies
mapping (uint256 => address) public tokenIndexToAddress;
LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0);
// RoomNight tokens
struct RoomNight {
uint256 vendorId;
uint256 rpid;
uint256 token; // The digital currency token
uint256 price; // The digital currency price
uint256 timestamp; // Create timestamp.
uint256 date; // The checkin date
bytes32 ipfs; // The address of rate plan detail on IPFS.
}
RoomNight[] public roomnights;
// rnid -> owner
mapping (uint256 => address) public roomNightIndexToOwner;
// Owner Account
mapping (address => LinkedListLib.LinkedList) public roomNightOwners;
// Vendor Account
mapping (address => LinkedListLib.LinkedList) public roomNightVendors;
// The authorized address for each TRN
mapping (uint256 => address) public roomNightApprovals;
// The authorized operators for each address
mapping (address => mapping (address => bool)) public operatorApprovals;
// The applications of room night redund
mapping (address => mapping (uint256 => bool)) public refundApplications;
// The signature of `onERC721Received(address,uint256,bytes)`
// bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba;
/**
* This emits when contract authorized
*/
event ContractAuthorized(address _contract);
/**
* This emits when contract deauthorized
*/
event ContractDeauthorized(address _contract);
/**
* The contract is valid
*/
modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
/**
* The contract is valid
*/
modifier authorizedContractIdValid(uint256 _cid) {
require(authorizedContractList.nodeExists(_cid));
_;
}
/**
* Only the owner or authorized contract is valid
*/
modifier onlyOwnerOrAuthorizedContract {
require(msg.sender == owner || authorizedContractIds[msg.sender] > 0);
_;
}
/**
* Constructor
*/
constructor() public {
// Add one invalid RoomNight, avoid subscript 0
roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0));
}
/**
* @dev Returns the node list and next node as a tuple
* @param self stored linked list from contract
* @param _node the begin id of the node to get
* @param _limit the total nodes of one page
* @param _direction direction to step in
*/
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
}else {
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
}else {
return (temp, ei);
}
}
}
/**
* @dev Authorize `_contract` to execute this contract's funs
* @param _contract The contract address
* @param _name The contract name
*/
function authorizeContract(address _contract, string _name)
public
onlyOwner
returns(bool) {
uint256 codeSize;
assembly { codeSize := extcodesize(_contract) }
require(codeSize != 0);
// Not exists
require(authorizedContractIds[_contract] == 0);
// Add
uint256 id = authorizedContractList.push(false);
authorizedContractIds[_contract] = id;
authorizedContracts[id] = AuthorizedContract(_name, _contract);
// Event
emit ContractAuthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by address
* @param _contract The contract address
*/
function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
// Event
emit ContractDeauthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by contract id
* @param _cid The contract id
*/
function deauthorizeContractById(uint256 _cid)
public
onlyOwner
authorizedContractIdValid(_cid)
returns(bool) {
address acontract = authorizedContracts[_cid].acontract;
authorizedContractList.remove(_cid);
authorizedContractIds[acontract] = 0;
delete authorizedContracts[_cid];
// Event
emit ContractDeauthorized(acontract);
return true;
}
/**
* @dev Get authorize contract ids by page
* @param _from The begin authorize contract id
* @param _limit How many authorize contract ids one page
* @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0
*/
function getAuthorizeContractIds(uint256 _from, uint256 _limit)
external
view
returns(uint256[], uint256){
return getNodes(authorizedContractList, _from, _limit, true);
}
/**
* @dev Get authorize contract by id
* @param _cid Then authorize contract id
* @return The authorize contract info(_name, _acontract)
*/
function getAuthorizeContract(uint256 _cid)
external
view
returns(string _name, address _acontract) {
AuthorizedContract memory acontract = authorizedContracts[_cid];
_name = acontract.name;
_acontract = acontract.acontract;
}
/*************************************** GET ***************************************/
/**
* @dev Get the rate plan by `_vendorId` and `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function getRatePlan(uint256 _vendorId, uint256 _rpid)
public
view
returns (string _name, uint256 _timestamp, bytes32 _ipfs) {
_name = vendors[_vendorId].ratePlans[_rpid].name;
_timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp;
_ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs;
}
/**
* @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
/**
* @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _dates The dates desc ([20180723,20180724,20180725])
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
// Get the base price
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
/**
* @dev Get the inventory by by `_vendorId`, `_rpid` and `_date`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @return The inventory info(inventory, init)
*/
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
/**
* @dev Whether the rate plan is exist
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @return If the rate plan of the vendor is exist returns true otherwise return false
*/
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid)
public
view
returns (bool) {
return vendors[_vendorId].ratePlanList.nodeExists(_rpid);
}
/**
* @dev Get orders of owner by page
* @param _owner The owner address
* @param _from The begin id of the node to get
* @param _limit The total nodes of one page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightOwners[_owner], _from, _limit, _direction);
}
/**
* @dev Get orders of vendor by page
* @param _owner The vendor address
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightVendors[_owner], _from, _limit, _direction);
}
/**
* @dev Get the token count of somebody
* @param _owner The owner of token
* @return The token count of `_owner`
*/
function balanceOf(address _owner)
public
view
returns(uint256) {
return roomNightOwners[_owner].length;
}
/**
* @dev Get rate plan ids of `_vendorId`
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The rate plan ids and the next id
*/
function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction);
}
/**
* @dev Get token ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The token ids and the next id
*/
function getTokens(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(tokenList, _from, _limit, _direction);
}
/**
* @dev Get token Info
* @param _tokenId The token id
* @return The token info(symbol, name, decimals)
*/
function getToken(uint256 _tokenId)
public
view
returns(string _symbol, string _name, uint8 _decimals, address _token) {
_token = tokenIndexToAddress[_tokenId];
TripioToken tripio = TripioToken(_token);
_symbol = tripio.symbol();
_name = tripio.name();
_decimals = tripio.decimals();
}
/**
* @dev Get vendor ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The vendor ids and the next id
*/
function getVendors(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendorList, _from, _limit, _direction);
}
/**
* @dev Get the vendor infomation by vendorId
* @param _vendorId The vendor id
* @return The vendor infomation(name, vendor, timestamp, valid)
*/
function getVendor(uint256 _vendorId)
public
view
returns(string _name, address _vendor,uint256 _timestamp, bool _valid) {
_name = vendors[_vendorId].name;
_vendor = vendors[_vendorId].vendor;
_timestamp = vendors[_vendorId].timestamp;
_valid = vendors[_vendorId].valid;
}
/*************************************** SET ***************************************/
/**
* @dev Update base uri of token metadata
* @param _tokenBaseURI The base uri
*/
function updateTokenBaseURI(string _tokenBaseURI)
public
onlyOwnerOrAuthorizedContract {
tokenBaseURI = _tokenBaseURI;
}
/**
* @dev Push order to user's order list
* @param _owner The buyer address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
/**
* @dev Remove order from owner's order list
* @param _owner The owner address
* @param _rnid The room night order id
*/
function removeOrderOfOwner(address _owner, uint _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightOwners[_owner].nodeExists(_rnid));
roomNightOwners[_owner].remove(_rnid);
}
/**
* @dev Push order to the vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
/**
* @dev Remove order from vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
*/
function removeOrderOfVendor(address _vendor, uint256 _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightVendors[_vendor].nodeExists(_rnid));
roomNightVendors[_vendor].remove(_rnid);
}
/**
* @dev Transfer token to somebody
* @param _tokenId The token id
* @param _to The target owner of the token
*/
function transferTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightIndexToOwner[_tokenId] = _to;
roomNightApprovals[_tokenId] = address(0);
}
/**
* @dev Approve `_to` to operate the `_tokenId`
* @param _tokenId The token id
* @param _to Somebody to be approved
*/
function approveTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightApprovals[_tokenId] = _to;
}
/**
* @dev Approve `_operator` to operate all the Token of `_to`
* @param _operator The operator to be approved
* @param _to The owner of tokens to be operate
* @param _approved Approved or not
*/
function approveOperatorTo(address _operator, address _to, bool _approved)
public
onlyOwnerOrAuthorizedContract {
operatorApprovals[_to][_operator] = _approved;
}
/**
* @dev Update base price of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.init = true;
vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price;
}
/**
* @dev Update base inventory of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _inventory The inventory to be updated
*/
function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory;
}
/**
* @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The inventory to be updated
*/
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
/**
* @dev Reduce inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be reduced
*/
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
/**
* @dev Add inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be add
*/
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
/**
* @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
* @param _inventory The inventory to be updated
*/
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Push rate plan to `_vendorId`'s rate plan list
* @param _vendorId The vendor id
* @param _name The name of rate plan
* @param _ipfs The rate plan IPFS address
* @param _direction direction to step in
*/
function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));
uint256 id = vendors[_vendorId].ratePlanList.push(_direction);
vendors[_vendorId].ratePlans[id] = rp;
return id;
}
/**
* @dev Remove rate plan of `_vendorId` by `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function removeRatePlan(uint256 _vendorId, uint256 _rpid)
public
onlyOwnerOrAuthorizedContract {
delete vendors[_vendorId].ratePlans[_rpid];
vendors[_vendorId].ratePlanList.remove(_rpid);
}
/**
* @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _name The rate plan name
* @param _ipfs The rate plan IPFS address
*/
function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs;
vendors[_vendorId].ratePlans[_rpid].name = _name;
}
/**
* @dev Push token contract to the token list
* @param _direction direction to step in
*/
function pushToken(address _contract, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = tokenList.push(_direction);
tokenIndexToAddress[id] = _contract;
return id;
}
/**
* @dev Remove token by `_tokenId`
* @param _tokenId The digital token id
*/
function removeToken(uint256 _tokenId)
public
onlyOwnerOrAuthorizedContract {
delete tokenIndexToAddress[_tokenId];
tokenList.remove(_tokenId);
}
/**
* @dev Generate room night token
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _token The token id
* @param _price The token price
* @param _ipfs The rate plan IPFS address
*/
function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));
// Give the token to `_customer`
uint256 rnid = uint256(roomnights.length - 1);
return rnid;
}
/**
* @dev Update refund applications
* @param _buyer The room night token holder
* @param _rnid The room night token id
* @param _isRefund Is redund or not
*/
function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund)
public
onlyOwnerOrAuthorizedContract {
refundApplications[_buyer][_rnid] = _isRefund;
}
/**
* @dev Push vendor info to the vendor list
* @param _name The name of vendor
* @param _vendor The vendor address
* @param _direction direction to step in
*/
function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
/**
* @dev Remove vendor from vendor list
* @param _vendorId The vendor id
*/
function removeVendor(uint256 _vendorId)
public
onlyOwnerOrAuthorizedContract {
vendorList.remove(_vendorId);
address vendor = vendors[_vendorId].vendor;
vendorIds[vendor] = 0;
delete vendors[_vendorId];
}
/**
* @dev Make vendor valid or invalid
* @param _vendorId The vendor id
* @param _valid The vendor is valid or not
*/
function updateVendorValid(uint256 _vendorId, bool _valid)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].valid = _valid;
}
/**
* @dev Modify vendor's name
* @param _vendorId The vendor id
* @param _name Then vendor name
*/
function updateVendorName(uint256 _vendorId, string _name)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].name = _name;
}
} | * @dev Push vendor info to the vendor list @param _name The name of vendor @param _vendor The vendor address @param _direction direction to step in/ | function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
| 1,978,850 | [
1,
7621,
8556,
1123,
358,
326,
8556,
666,
225,
389,
529,
1021,
508,
434,
8556,
225,
389,
10645,
1021,
8556,
1758,
225,
389,
9855,
4068,
358,
2235,
316,
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,
1817,
14786,
12,
1080,
389,
529,
16,
1758,
389,
10645,
16,
1426,
389,
9855,
13,
203,
3639,
1071,
7010,
3639,
1338,
5541,
1162,
15341,
8924,
7010,
3639,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
612,
273,
8556,
682,
18,
6206,
24899,
9855,
1769,
203,
3639,
8556,
2673,
63,
67,
10645,
65,
273,
612,
31,
203,
3639,
331,
409,
1383,
63,
350,
65,
273,
776,
5227,
24899,
529,
16,
389,
10645,
16,
2254,
5034,
12,
3338,
3631,
638,
16,
10688,
5664,
18,
13174,
682,
12,
20,
16,
374,
10019,
203,
3639,
327,
612,
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
] |
./partial_match/1/0xfdc8eCB8B79C400217A2a524AECB2c5E310cE0B4/sources/lib/solady/src/utils/SignatureCheckerLib.sol | @solidity memory-safe-assembly Clean the upper 96 bits of `signer` in case they are dirty. `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. | function isValidSignatureNowCalldata(address signer, bytes32 hash, bytes calldata signature)
internal
view
returns (bool isValid)
assembly {
let m := mload(0x40)
if eq(signature.length, 65) {
mstore(m, hash)
pop(
staticcall(
)
)
if mul(eq(mload(m), signer), returndatasize()) {
isValid := 1
break
}
}
let f := shl(224, 0x1626ba7e)
mstore(add(m, 0x04), hash)
mstore(add(m, 0x44), signature.length)
and(
),
)
)
break
}
| 9,225,690 | [
1,
36,
30205,
560,
3778,
17,
4626,
17,
28050,
9645,
326,
3854,
19332,
4125,
434,
1375,
2977,
264,
68,
316,
648,
2898,
854,
9603,
18,
1375,
2463,
13178,
554,
20338,
903,
506,
1375,
20,
92,
3462,
68,
12318,
2216,
16,
471,
1375,
20,
92,
713,
68,
3541,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4908,
5374,
8674,
1477,
892,
12,
2867,
10363,
16,
1731,
1578,
1651,
16,
1731,
745,
892,
3372,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
4908,
13,
203,
3639,
19931,
288,
203,
7734,
2231,
312,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
7734,
309,
7555,
12,
8195,
18,
2469,
16,
15892,
13,
288,
203,
10792,
312,
2233,
12,
81,
16,
1651,
13,
203,
10792,
1843,
12,
203,
13491,
760,
1991,
12,
203,
13491,
262,
203,
10792,
262,
203,
10792,
309,
14064,
12,
11253,
12,
81,
945,
12,
81,
3631,
10363,
3631,
327,
13178,
554,
10756,
288,
203,
13491,
4908,
519,
404,
203,
13491,
898,
203,
10792,
289,
203,
7734,
289,
203,
7734,
2231,
284,
519,
699,
80,
12,
23622,
16,
374,
92,
2313,
5558,
12124,
27,
73,
13,
203,
7734,
312,
2233,
12,
1289,
12,
81,
16,
374,
92,
3028,
3631,
1651,
13,
203,
7734,
312,
2233,
12,
1289,
12,
81,
16,
374,
92,
6334,
3631,
3372,
18,
2469,
13,
203,
10792,
471,
12,
203,
10792,
262,
16,
203,
10792,
262,
203,
7734,
262,
203,
7734,
898,
203,
5411,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x94c491e298625b1226a89DDA091B3932c59FAbc1/sources/FraxUnifiedFarm_ERC20_Convex_FRAXBP_Volatile.sol | -------------------- COMMON -------------------- -------------------- VARIES -------------------- Convex stkcvxFPIFRAX, stkcvxFRAXBP, etc ICurvefrxETHETHPool public curvePool; Fraxswap IFraxswapPair public stakingToken; Fraxlend IFraxlendPair public stakingToken; G-UNI IGUniPool public stakingToken; mStable IFeederPool public stakingToken; sdETH-FraxPut Vault IOpynPerpVault public stakingToken; StakeDAO Vault IStakeDaoVault public stakingToken; Uniswap V2 IUniswapV2Pair public stakingToken; Vesper IVPool public stakingToken; ------------------------------------------------ Stake tracking Struct for the stake | contract FraxUnifiedFarm_ERC20 is FraxUnifiedFarmTemplate {
bool internal frax_is_token0;
IConvexStakingWrapperFrax public stakingToken;
I2poolToken public curveToken;
I2pool public curvePool;
mapping(address => LockedStake[]) public lockedStakes;
}
struct LockedStake {
bytes32 kek_id;
uint256 start_timestamp;
uint256 liquidity;
uint256 ending_timestamp;
}
constructor (
address _owner,
address[] memory _rewardTokens,
address[] memory _rewardManagers,
uint256[] memory _rewardRatesManual,
address[] memory _gaugeControllers,
address[] memory _rewardDistributors,
address _stakingToken
)
FraxUnifiedFarmTemplate(_owner, _rewardTokens, _rewardManagers, _rewardRatesManual, _gaugeControllers, _rewardDistributors)
{
}
function fraxPerLPToken() public virtual view override returns (uint256) {
uint256 frax_per_lp_token;
return frax_per_lp_token;
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
function calcCurrLockMultiplier(address account, uint256 stake_idx) public view returns (uint256 midpoint_lock_multiplier) {
LockedStake memory thisStake = lockedStakes[account][stake_idx];
uint256 accrue_start_time;
if (lastRewardClaimTime[account] < thisStake.start_timestamp) {
accrue_start_time = thisStake.start_timestamp;
}
else {
accrue_start_time = lastRewardClaimTime[account];
}
if (thisStake.ending_timestamp <= block.timestamp) {
if (lastRewardClaimTime[account] < thisStake.ending_timestamp){
uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time;
uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp;
uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2);
uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry);
midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry);
}
else {
midpoint_lock_multiplier = 0;
}
}
else {
uint256 avg_time_left;
{
uint256 time_left_p1 = thisStake.ending_timestamp - accrue_start_time;
uint256 time_left_p2 = thisStake.ending_timestamp - block.timestamp;
avg_time_left = (time_left_p1 + time_left_p2) / 2;
}
midpoint_lock_multiplier = lockMultiplier(avg_time_left);
}
}
if (midpoint_lock_multiplier > thisStake.lock_multiplier) midpoint_lock_multiplier = thisStake.lock_multiplier;
function calcCurCombinedWeight(address account) public override view
returns (
uint256 old_combined_weight,
uint256 new_vefxs_multiplier,
uint256 new_combined_weight
)
{
old_combined_weight = _combined_weights[account];
new_vefxs_multiplier = veFXSMultiplier(account);
uint256 midpoint_vefxs_multiplier;
if (
(_locked_liquidity[account] == 0 && _combined_weights[account] == 0) ||
(new_vefxs_multiplier >= _vefxsMultiplierStored[account])
) {
midpoint_vefxs_multiplier = new_vefxs_multiplier;
}
else {
midpoint_vefxs_multiplier = (new_vefxs_multiplier + _vefxsMultiplierStored[account]) / 2;
}
for (uint256 i = 0; i < lockedStakes[account].length; i++) {
LockedStake memory thisStake = lockedStakes[account][i];
uint256 midpoint_lock_multiplier = calcCurrLockMultiplier(account, i);
uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
}
}
function calcCurCombinedWeight(address account) public override view
returns (
uint256 old_combined_weight,
uint256 new_vefxs_multiplier,
uint256 new_combined_weight
)
{
old_combined_weight = _combined_weights[account];
new_vefxs_multiplier = veFXSMultiplier(account);
uint256 midpoint_vefxs_multiplier;
if (
(_locked_liquidity[account] == 0 && _combined_weights[account] == 0) ||
(new_vefxs_multiplier >= _vefxsMultiplierStored[account])
) {
midpoint_vefxs_multiplier = new_vefxs_multiplier;
}
else {
midpoint_vefxs_multiplier = (new_vefxs_multiplier + _vefxsMultiplierStored[account]) / 2;
}
for (uint256 i = 0; i < lockedStakes[account].length; i++) {
LockedStake memory thisStake = lockedStakes[account][i];
uint256 midpoint_lock_multiplier = calcCurrLockMultiplier(account, i);
uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
}
}
function calcCurCombinedWeight(address account) public override view
returns (
uint256 old_combined_weight,
uint256 new_vefxs_multiplier,
uint256 new_combined_weight
)
{
old_combined_weight = _combined_weights[account];
new_vefxs_multiplier = veFXSMultiplier(account);
uint256 midpoint_vefxs_multiplier;
if (
(_locked_liquidity[account] == 0 && _combined_weights[account] == 0) ||
(new_vefxs_multiplier >= _vefxsMultiplierStored[account])
) {
midpoint_vefxs_multiplier = new_vefxs_multiplier;
}
else {
midpoint_vefxs_multiplier = (new_vefxs_multiplier + _vefxsMultiplierStored[account]) / 2;
}
for (uint256 i = 0; i < lockedStakes[account].length; i++) {
LockedStake memory thisStake = lockedStakes[account][i];
uint256 midpoint_lock_multiplier = calcCurrLockMultiplier(account, i);
uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
}
}
new_combined_weight = 0;
function calcCurCombinedWeight(address account) public override view
returns (
uint256 old_combined_weight,
uint256 new_vefxs_multiplier,
uint256 new_combined_weight
)
{
old_combined_weight = _combined_weights[account];
new_vefxs_multiplier = veFXSMultiplier(account);
uint256 midpoint_vefxs_multiplier;
if (
(_locked_liquidity[account] == 0 && _combined_weights[account] == 0) ||
(new_vefxs_multiplier >= _vefxsMultiplierStored[account])
) {
midpoint_vefxs_multiplier = new_vefxs_multiplier;
}
else {
midpoint_vefxs_multiplier = (new_vefxs_multiplier + _vefxsMultiplierStored[account]) / 2;
}
for (uint256 i = 0; i < lockedStakes[account].length; i++) {
LockedStake memory thisStake = lockedStakes[account][i];
uint256 midpoint_lock_multiplier = calcCurrLockMultiplier(account, i);
uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
}
}
function lockedStakesOf(address account) external view returns (LockedStake[] memory) {
return lockedStakes[account];
}
function lockedStakesOfLength(address account) external view returns (uint256) {
return lockedStakes[account].length;
}
function _updateLiqAmts(address staker_address, uint256 amt, bool is_add) internal {
address the_proxy = getProxyFor(staker_address);
if (is_add) {
_total_liquidity_locked += amt;
_locked_liquidity[staker_address] += amt;
if (the_proxy != address(0)) proxy_lp_balances[the_proxy] += amt;
}
else {
_total_liquidity_locked -= amt;
_locked_liquidity[staker_address] -= amt;
if (the_proxy != address(0)) proxy_lp_balances[the_proxy] -= amt;
}
}
function _updateLiqAmts(address staker_address, uint256 amt, bool is_add) internal {
address the_proxy = getProxyFor(staker_address);
if (is_add) {
_total_liquidity_locked += amt;
_locked_liquidity[staker_address] += amt;
if (the_proxy != address(0)) proxy_lp_balances[the_proxy] += amt;
}
else {
_total_liquidity_locked -= amt;
_locked_liquidity[staker_address] -= amt;
if (the_proxy != address(0)) proxy_lp_balances[the_proxy] -= amt;
}
}
function _updateLiqAmts(address staker_address, uint256 amt, bool is_add) internal {
address the_proxy = getProxyFor(staker_address);
if (is_add) {
_total_liquidity_locked += amt;
_locked_liquidity[staker_address] += amt;
if (the_proxy != address(0)) proxy_lp_balances[the_proxy] += amt;
}
else {
_total_liquidity_locked -= amt;
_locked_liquidity[staker_address] -= amt;
if (the_proxy != address(0)) proxy_lp_balances[the_proxy] -= amt;
}
}
_updateRewardAndBalance(staker_address, false, true);
function _getStake(address staker_address, bytes32 kek_id) internal view returns (LockedStake memory locked_stake, uint256 arr_idx) {
for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){
if (kek_id == lockedStakes[staker_address][i].kek_id){
locked_stake = lockedStakes[staker_address][i];
arr_idx = i;
break;
}
}
require(locked_stake.kek_id == kek_id, "Stake not found");
}
function _getStake(address staker_address, bytes32 kek_id) internal view returns (LockedStake memory locked_stake, uint256 arr_idx) {
for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){
if (kek_id == lockedStakes[staker_address][i].kek_id){
locked_stake = lockedStakes[staker_address][i];
arr_idx = i;
break;
}
}
require(locked_stake.kek_id == kek_id, "Stake not found");
}
function _getStake(address staker_address, bytes32 kek_id) internal view returns (LockedStake memory locked_stake, uint256 arr_idx) {
for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){
if (kek_id == lockedStakes[staker_address][i].kek_id){
locked_stake = lockedStakes[staker_address][i];
arr_idx = i;
break;
}
}
require(locked_stake.kek_id == kek_id, "Stake not found");
}
function lockAdditional(bytes32 kek_id, uint256 addl_liq) nonReentrant updateRewardAndBalanceMdf(msg.sender, true) public {
(LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id);
uint256 new_amt = thisStake.liquidity + addl_liq;
require(addl_liq >= 0, "Must be positive");
TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), addl_liq);
lockedStakes[msg.sender][theArrayIndex] = LockedStake(
kek_id,
thisStake.start_timestamp,
new_amt,
thisStake.ending_timestamp,
thisStake.lock_multiplier
);
_updateLiqAmts(msg.sender, addl_liq, true);
emit LockedAdditional(msg.sender, kek_id, addl_liq);
}
function lockLonger(bytes32 kek_id, uint256 new_ending_ts) nonReentrant updateRewardAndBalanceMdf(msg.sender, true) public {
(LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id);
require(new_ending_ts > block.timestamp, "Must be in the future");
uint256 time_left = (thisStake.ending_timestamp > block.timestamp) ? thisStake.ending_timestamp - block.timestamp : 0;
uint256 new_secs = new_ending_ts - block.timestamp;
require(new_secs > time_left, "Cannot shorten lock time");
require(new_secs >= lock_time_min, "Minimum stake time not met");
require(new_secs <= lock_time_for_max_multiplier, "Trying to lock for too long");
lockedStakes[msg.sender][theArrayIndex] = LockedStake(
kek_id,
block.timestamp,
thisStake.liquidity,
new_ending_ts,
lockMultiplier(new_secs)
);
_updateRewardAndBalance(msg.sender, false, true);
emit LockedLonger(msg.sender, kek_id, new_secs, block.timestamp, new_ending_ts);
}
function stakeLocked(uint256 liquidity, uint256 secs) nonReentrant external returns (bytes32) {
return _stakeLocked(msg.sender, msg.sender, liquidity, secs, block.timestamp);
}
function _stakeLocked(
address staker_address,
address source_address,
uint256 liquidity,
uint256 secs,
uint256 start_timestamp
) internal updateRewardAndBalanceMdf(staker_address, true) returns (bytes32) {
require(stakingPaused == false, "Staking paused");
require(secs >= lock_time_min, "Minimum stake time not met");
require(secs <= lock_time_for_max_multiplier,"Trying to lock for too long");
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity);
uint256 lock_multiplier = lockMultiplier(secs);
bytes32 kek_id = keccak256(abi.encodePacked(staker_address, start_timestamp, liquidity, _locked_liquidity[staker_address]));
lockedStakes[staker_address].push(LockedStake(
kek_id,
start_timestamp,
liquidity,
start_timestamp + secs,
lock_multiplier
));
_updateLiqAmts(staker_address, liquidity, true);
emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address);
return kek_id;
}
function withdrawLocked(bytes32 kek_id, address destination_address, bool claim_rewards) nonReentrant external returns (uint256) {
require(withdrawalsPaused == false, "Withdrawals paused");
return _withdrawLocked(msg.sender, destination_address, kek_id, claim_rewards);
}
function _withdrawLocked(
address staker_address,
address destination_address,
bytes32 kek_id,
bool claim_rewards
) internal returns (uint256) {
if (claim_rewards || !collectRewardsOnWithdrawalPaused) _getReward(staker_address, destination_address, true);
else {
_updateRewardAndBalance(staker_address, true, false);
}
require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true, "Stake is still locked!");
uint256 liquidity = thisStake.liquidity;
if (liquidity > 0) {
TransferHelper.safeTransfer(address(stakingToken), destination_address, liquidity);
delete lockedStakes[staker_address][theArrayIndex];
_updateLiqAmts(staker_address, liquidity, false);
emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address);
}
return liquidity;
}
function _withdrawLocked(
address staker_address,
address destination_address,
bytes32 kek_id,
bool claim_rewards
) internal returns (uint256) {
if (claim_rewards || !collectRewardsOnWithdrawalPaused) _getReward(staker_address, destination_address, true);
else {
_updateRewardAndBalance(staker_address, true, false);
}
require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true, "Stake is still locked!");
uint256 liquidity = thisStake.liquidity;
if (liquidity > 0) {
TransferHelper.safeTransfer(address(stakingToken), destination_address, liquidity);
delete lockedStakes[staker_address][theArrayIndex];
_updateLiqAmts(staker_address, liquidity, false);
emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address);
}
return liquidity;
}
(LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(staker_address, kek_id);
function _withdrawLocked(
address staker_address,
address destination_address,
bytes32 kek_id,
bool claim_rewards
) internal returns (uint256) {
if (claim_rewards || !collectRewardsOnWithdrawalPaused) _getReward(staker_address, destination_address, true);
else {
_updateRewardAndBalance(staker_address, true, false);
}
require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true, "Stake is still locked!");
uint256 liquidity = thisStake.liquidity;
if (liquidity > 0) {
TransferHelper.safeTransfer(address(stakingToken), destination_address, liquidity);
delete lockedStakes[staker_address][theArrayIndex];
_updateLiqAmts(staker_address, liquidity, false);
emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address);
}
return liquidity;
}
function _getRewardExtraLogic(address rewardee, address destination_address) internal override {
}
event LockedLonger(address indexed user, bytes32 kek_id, uint256 new_secs, uint256 new_start_ts, uint256 new_end_ts);
event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address);
event WithdrawLocked(address indexed user, uint256 liquidity, bytes32 kek_id, address destination_address);
event LockedAdditional(address indexed user, bytes32 kek_id, uint256 amount);
}
| 3,975,277 | [
1,
1271,
553,
5423,
17667,
12146,
6062,
12146,
6062,
8350,
8805,
12146,
6062,
18263,
338,
384,
79,
19774,
16275,
1102,
9981,
2501,
16,
384,
79,
19774,
92,
9981,
2501,
30573,
16,
5527,
467,
9423,
4840,
92,
1584,
44,
1584,
2500,
1371,
1071,
8882,
2864,
31,
478,
354,
92,
22270,
11083,
354,
92,
22270,
4154,
1071,
384,
6159,
1345,
31,
478,
354,
18402,
409,
11083,
354,
18402,
409,
4154,
1071,
384,
6159,
1345,
31,
611,
17,
10377,
13102,
984,
77,
2864,
1071,
384,
6159,
1345,
31,
312,
30915,
467,
8141,
264,
2864,
1071,
384,
6159,
1345,
31,
8349,
1584,
44,
17,
42,
354,
92,
6426,
17329,
1665,
84,
878,
2173,
84,
12003,
1071,
384,
6159,
1345,
31,
934,
911,
18485,
17329,
467,
510,
911,
11412,
12003,
1071,
384,
6159,
1345,
31,
1351,
291,
91,
438,
776,
22,
467,
984,
291,
91,
438,
58,
22,
4154,
1071,
384,
6159,
1345,
31,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
478,
354,
92,
984,
939,
42,
4610,
67,
654,
39,
3462,
353,
478,
354,
92,
984,
939,
42,
4610,
2283,
288,
203,
203,
203,
565,
1426,
2713,
284,
354,
92,
67,
291,
67,
2316,
20,
31,
203,
203,
203,
565,
467,
17467,
338,
510,
6159,
3611,
42,
354,
92,
1071,
384,
6159,
1345,
31,
203,
565,
467,
22,
6011,
1345,
1071,
8882,
1345,
31,
203,
565,
467,
22,
6011,
1071,
8882,
2864,
31,
203,
203,
203,
203,
377,
203,
203,
203,
203,
203,
203,
203,
565,
2874,
12,
2867,
516,
3488,
329,
510,
911,
63,
5717,
1071,
8586,
510,
3223,
31,
203,
203,
203,
97,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
1958,
3488,
329,
510,
911,
288,
203,
3639,
1731,
1578,
417,
3839,
67,
350,
31,
203,
3639,
2254,
5034,
787,
67,
5508,
31,
203,
3639,
2254,
5034,
4501,
372,
24237,
31,
203,
3639,
2254,
5034,
11463,
67,
5508,
31,
203,
565,
289,
203,
377,
203,
565,
3885,
261,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
1758,
8526,
3778,
389,
266,
2913,
5157,
16,
203,
3639,
1758,
8526,
3778,
389,
266,
2913,
17570,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
266,
2913,
20836,
25139,
16,
203,
3639,
1758,
8526,
3778,
389,
75,
8305,
13745,
16,
203,
3639,
1758,
8526,
3778,
389,
266,
2913,
1669,
665,
13595,
16,
203,
3639,
1758,
389,
334,
6159,
1345,
203,
565,
262,
7010,
565,
478,
354,
92,
984,
939,
42,
4610,
2283,
24899,
8443,
16,
389,
2
] |
./full_match/11155111/0xDf01A4040493B514605392620B3a0a05Eb8Cd295/sources/contracts/ExquisiteGraphics.sol | @notice A way to say "Thank You" | function ty(string memory message) external payable {
ThankYou._ty(message);
}
| 3,797,340 | [
1,
37,
4031,
358,
12532,
315,
1315,
2304,
4554,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
13806,
12,
1080,
3778,
883,
13,
3903,
8843,
429,
288,
203,
565,
935,
2304,
6225,
6315,
4098,
12,
2150,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x46b13E7E8f1aEF156973AE3eD975E738cAFB08C8/sources/contracts/interfaces/IPool.sol | * @notice Pool interface/ | interface IPool is IPauseable, IGovernable {
function debtFloorInUsd() external view returns (uint256);
function depositFee() external view returns (uint256);
function issueFee() external view returns (uint256);
function withdrawFee() external view returns (uint256);
function repayFee() external view returns (uint256);
function swapFee() external view returns (uint256);
function feeCollector() external view returns (address);
function maxLiquidable() external view returns (uint256);
function isSyntheticTokenExists(ISyntheticToken syntheticToken_) external view returns (bool);
function isDebtTokenExists(IDebtToken debtToken_) external view returns (bool);
function isDepositTokenExists(IDepositToken depositToken_) external view returns (bool);
function depositTokenOf(IERC20 underlying_) external view returns (IDepositToken);
function debtTokenOf(ISyntheticToken syntheticToken_) external view returns (IDebtToken);
function getDepositTokens() external view returns (address[] memory);
function getDebtTokens() external view returns (address[] memory);
function getRewardsDistributors() external view returns (IRewardsDistributor[] memory);
function debtOf(address account_) external view returns (uint256 _debtInUsd);
function depositOf(address account_) external view returns (uint256 _depositInUsd, uint256 _issuableLimitInUsd);
function debtPositionOf(address account_)
external
view
returns (
bool _isHealthy,
uint256 _depositInUsd,
uint256 _debtInUsd,
uint256 _issuableLimitInUsd,
uint256 _issuableInUsd
);
function addDebtToken(IDebtToken debtToken_) external;
function removeDebtToken(IDebtToken debtToken_) external;
function addDepositToken(address depositToken_) external;
function removeDepositToken(IDepositToken depositToken_) external;
function liquidate(
ISyntheticToken syntheticToken_,
address account_,
uint256 amountToRepay_,
IDepositToken depositToken_
) external;
function swap(
ISyntheticToken syntheticTokenIn_,
ISyntheticToken syntheticTokenOut_,
uint256 amountIn_
) external returns (uint256 _amountOut);
function updateSwapFee(uint256 newSwapFee_) external;
function updateDebtFloor(uint256 newDebtFloorInUsd_) external;
function updateDepositFee(uint256 newDepositFee_) external;
function updateIssueFee(uint256 newIssueFee_) external;
function updateWithdrawFee(uint256 newWithdrawFee_) external;
function updateRepayFee(uint256 newRepayFee_) external;
function updateLiquidatorLiquidationFee(uint128 newLiquidatorLiquidationFee_) external;
function updateProtocolLiquidationFee(uint128 newProtocolLiquidationFee_) external;
function updateMaxLiquidable(uint256 newMaxLiquidable_) external;
function updateTreasury(ITreasury newTreasury_) external;
function treasury() external view returns (ITreasury);
function masterOracle() external view returns (IMasterOracle);
function poolRegistry() external view returns (IPoolRegistry);
function addToDepositTokensOfAccount(address account_) external;
function removeFromDepositTokensOfAccount(address account_) external;
function addToDebtTokensOfAccount(address account_) external;
function removeFromDebtTokensOfAccount(address account_) external;
function getDepositTokensOfAccount(address account_) external view returns (address[] memory);
function getDebtTokensOfAccount(address account_) external view returns (address[] memory);
function addRewardsDistributor(IRewardsDistributor distributor_) external;
function removeRewardsDistributor(IRewardsDistributor distributor_) external;
function toggleIsSwapActive() external;
function isSwapActive() external view returns (bool);
}
| 3,134,117 | [
1,
2864,
1560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
2864,
353,
2971,
1579,
429,
16,
13102,
1643,
6914,
288,
203,
565,
445,
18202,
88,
42,
5807,
382,
3477,
72,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
443,
1724,
14667,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
5672,
14667,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
598,
9446,
14667,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
2071,
528,
14667,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7720,
14667,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
14036,
7134,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
943,
48,
18988,
27621,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
353,
10503,
16466,
1345,
4002,
12,
5127,
878,
16466,
1345,
25535,
1345,
67,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
353,
758,
23602,
1345,
4002,
12,
734,
73,
23602,
1345,
18202,
88,
1345,
67,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
353,
758,
1724,
1345,
4002,
12,
734,
881,
538,
305,
1345,
443,
1724,
1345,
67,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
443,
1724,
1345,
951,
12,
45,
654,
39,
3462,
6808,
67,
13,
3903,
1476,
1135,
261,
734,
881,
538,
305,
1345,
1769,
203,
203,
565,
445,
18202,
88,
1345,
951,
12,
5127,
878,
16466,
1345,
25535,
1345,
67,
13,
3903,
1476,
1135,
261,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol";
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import "./IEulerBeats.sol";
import "hardhat/console.sol";
// The printing press for the EulerBeats token contract. This contract is responsible
// for minting and burning EulerBeat prints.
// To be functional, this must be set as the owner of the original EulerBeats contract,
// and the EulerBeats contract should be disabled. After that, this is the only
// way to print those fresh beats.
contract PrintingPress is Ownable, ERC1155Holder, ReentrancyGuard {
using SafeMath for uint256;
/***********************************|
| Variables and Events |
|__________________________________*/
bool public burnEnabled = false;
bool public printEnabled = false;
// Supply restriction on seeds/original NFTs
uint256 constant MAX_SEEDS_SUPPLY = 27;
// The 40 bit is flag to distinguish prints - 1 for print
uint256 constant PRINTS_FLAG_BIT = 1 << 39;
// PrintingPress EulerBeats wrapper specific storage
address public EulerBeats;
mapping (uint => uint) public seedToPrintId;
/**
* @dev Function to return the seedIds in an iterable array of uints
*/
function getSeedIds() public pure returns (uint256[MAX_SEEDS_SUPPLY] memory seedIds){
seedIds = [
uint256(21575894274),
uint256(18052613891),
uint256(12918588162),
uint256(21760049923),
uint256(22180136451),
uint256(8926004995),
uint256(22364095747),
uint256(17784178691),
uint256(554240256),
uint256(17465084160),
uint256(13825083651),
uint256(12935627264),
uint256(8925938433),
uint256(4933026051),
uint256(8673888000),
uint256(13439075074),
uint256(13371638787),
uint256(17750625027),
uint256(21592343040),
uint256(4916052483),
uint256(4395697411),
uint256(13556253699),
uint256(470419715),
uint256(17800760067),
uint256(9193916675),
uint256(9395767298),
uint256(22314157057)
];
}
constructor(address _parent) {
EulerBeats = _parent;
uint256[MAX_SEEDS_SUPPLY] memory seedIds = getSeedIds();
for (uint256 i = 0; i < MAX_SEEDS_SUPPLY; i++) {
// Set the valid original seeds and hard-code their corresponding print tokenId
seedToPrintId[seedIds[i]] = getPrintTokenIdFromSeed(seedIds[i]);
}
}
/***********************************|
| User Interactions |
|__________________________________*/
/**
* @dev Function to correct a seedToOwner value if incorrect, before royalty paid
* @param seed The NFT id to mint print of
* @param _owner The current on-chain owner of the seed
*/
function ensureEulerBeatsSeedOwner(uint256 seed, address _owner) public {
require(seedToPrintId[seed] > 0, "Seed does not exist");
require(IEulerBeats(EulerBeats).balanceOf(_owner, seed) == 1, "Incorrect seed owner");
address registeredOwner = IEulerBeats(EulerBeats).seedToOwner(seed);
if (registeredOwner != _owner) {
IEulerBeats(EulerBeats).safeTransferFrom(address(this), _owner, seed, 0, hex"");
require(IEulerBeats(EulerBeats).seedToOwner(seed) == _owner, "Invalid seed owner");
}
}
/**
* @dev Function to mint prints from an existing seed. Msg.value must be sufficient.
* @param seed The NFT id to mint print of
* @param _owner The current on-chain owner of the seed
*/
function mintPrint(uint256 seed, address payable _owner)
public
payable
nonReentrant
returns (uint256)
{
require(printEnabled, "Printing is disabled");
// Record initial balance minus msg.value (difference to be refunded to user post-print)
uint preCallBalance = address(this).balance.sub(msg.value);
// Test that seed is valid
require(seedToPrintId[seed] > 0, "Seed does not exist");
// Verify owner of seed & ensure royalty ownership
ensureEulerBeatsSeedOwner(seed, _owner);
// Get print tokenId from seed
uint256 tokenId = seedToPrintId[seed];
// Enable EB.mintPrint
IEulerBeats(EulerBeats).setEnabled(true);
// EB.mintPrint(), let EB check price and refund to address(this)
IEulerBeats(EulerBeats).mintPrint{value: msg.value}(seed);
// Disable EB.mintPrint
IEulerBeats(EulerBeats).setEnabled(false);
// Transfer print to msg.sender
IEulerBeats(EulerBeats).safeTransferFrom(address(this), msg.sender, tokenId, 1, hex"");
// Send to user difference between current and preCallBalance if nonzero amt
uint refundBalance = address(this).balance.sub(preCallBalance);
if (refundBalance > 0) {
(bool success, ) = msg.sender.call{value: refundBalance}("");
require(success, "Refund payment failed");
}
return tokenId;
}
/**
* @dev Function to burn a print
* @param seed The seed for the print to burn.
* @param minimumSupply The minimum token supply for burn to succeed, this is a way to set slippage.
* Set to 1 to allow burn to go through no matter what the price is.
*/
function burnPrint(uint256 seed, uint256 minimumSupply) public nonReentrant {
require(burnEnabled, "Burning is disabled");
uint startBalance = address(this).balance;
// Check that seed is one of hard-coded 27
require(seedToPrintId[seed] > 0, "Seed does not exist");
// Get token id for prints
uint256 tokenId = seedToPrintId[seed];
// Transfer 1 EB print @ tokenID from msg.sender to this contract (requires approval)
IEulerBeats(EulerBeats).safeTransferFrom(msg.sender, address(this), tokenId, 1, hex"");
// Enable EulerBeats
IEulerBeats(EulerBeats).setEnabled(true);
// Burn print on v1, should receive the funds here
IEulerBeats(EulerBeats).burnPrint(seed, minimumSupply);
// Disable EulerBeats
IEulerBeats(EulerBeats).setEnabled(false);
(bool success, ) = msg.sender.call{value: address(this).balance.sub(startBalance)}("");
require(success, "Refund payment failed");
}
/***********************************|
| Admin |
|__________________________________*/
/**
* Should never be a balance here, only via selfdestruct
* @dev Withdraw earned funds from original Nft sales and print fees. Cannot withdraw the reserve funds.
*/
function withdraw() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
/**
* @dev Function to enable/disable printing
* @param _enabled The flag to turn printing on or off
*/
function setPrintEnabled(bool _enabled) public onlyOwner {
printEnabled = _enabled;
}
/**
* @dev Function to enable/disable burning prints
* @param _enabled The flag to turn burning on or off
*/
function setBurnEnabled(bool _enabled) public onlyOwner {
burnEnabled = _enabled;
}
/**
* @dev The token id for the prints contains the seed/original NFT id
* @param seed The seed/original NFT token id
*/
function getPrintTokenIdFromSeed(uint256 seed) internal pure returns (uint256) {
return seed | PRINTS_FLAG_BIT;
}
/***********************************|
| Admin - Passthrough |
|__________________________________*/
// methods that can access onlyOwner methods of EB contract, must be onlyOwner
/**
* @dev Function to transfer ownership of the EB contract
* @param newowner Address to set as the new owner of EB
*/
function transferOwnershipEB(address newowner) public onlyOwner {
IEulerBeats(EulerBeats).transferOwnership(newowner);
}
/**
* @dev Function to enable/disable mintPrint and burnPrint on EB contract
* @param enabled Bool value for setting whether EB is enabled
*/
function setEnabledEB(bool enabled) public onlyOwner {
IEulerBeats(EulerBeats).setEnabled(enabled);
}
/**
* @dev Function to withdraw Treum fee balance from EB contract
*/
function withdrawEB() public onlyOwner {
IEulerBeats(EulerBeats).withdraw();
msg.sender.transfer(address(this).balance);
}
/**
* @dev Set the base metadata uri on the EB contract
* @param newuri The new base uri
*/
function setURIEB(string memory newuri) public onlyOwner {
IEulerBeats(EulerBeats).setURI(newuri);
}
/**
* @dev Reset script count in EB
*/
function resetScriptCountEB() public onlyOwner {
IEulerBeats(EulerBeats).resetScriptCount();
}
/**
* @dev Add script string to EB
* @param _script String chunk of EB music gen code
*/
function addScriptEB(string memory _script) public onlyOwner {
IEulerBeats(EulerBeats).addScript(_script);
}
/**
* @dev Update script at index
* @param _script String chunk of EB music gen code
* @param index Index of the script which will be updated
*/
function updateScriptEB(string memory _script, uint256 index) public onlyOwner {
IEulerBeats(EulerBeats).updateScript(_script, index);
}
/**
* @dev Locks ability to check scripts in EB, this is irreversible
* @param locked Bool value whether to lock the script updates
*/
function setLockedEB(bool locked) public onlyOwner {
IEulerBeats(EulerBeats).setLocked(locked);
}
// Need payable fallback to receive ETH from burns, withdraw, etc
receive() external payable {
// WARNING: this does not prevent selfdestruct ETH transfers
require(msg.sender == EulerBeats, "Only EulerBeats allowed to send ETH here");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
}
}
pragma solidity >=0.6.0 <0.8.0;
interface IEulerBeats {
function reserve() external view returns (uint);
function totalSupply(uint) external view returns (uint);
function safeTransferFrom( address from,
address to,
uint256 id,
uint256 amount,
bytes memory data) external;
function balanceOf(address, uint256) external view returns (uint256);
function burnPrint(uint256, uint256) external;
function mintPrint(uint256) external payable returns (uint256);
function seedToOwner(uint256) external view returns (address);
function setEnabled(bool) external;
function setLocked(bool) external;
function transferOwnership(address) external;
function withdraw() external;
function setURI(string memory) external;
function resetScriptCount() external;
function addScript(string memory) external;
function updateScript(string memory, uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: 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;
import "./IERC1155Receiver.sol";
import "../../introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
constructor() internal {
_registerInterface(
ERC1155Receiver(address(0)).onERC1155Received.selector ^
ERC1155Receiver(address(0)).onERC1155BatchReceived.selector
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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);
}
| * @dev Function to mint prints from an existing seed. Msg.value must be sufficient. @param seed The NFT id to mint print of @param _owner The current on-chain owner of the seed/ Record initial balance minus msg.value (difference to be refunded to user post-print) Test that seed is valid Verify owner of seed & ensure royalty ownership Get print tokenId from seed Enable EB.mintPrint EB.mintPrint(), let EB check price and refund to address(this) Disable EB.mintPrint Transfer print to msg.sender Send to user difference between current and preCallBalance if nonzero amt | function mintPrint(uint256 seed, address payable _owner)
public
payable
nonReentrant
returns (uint256)
{
require(printEnabled, "Printing is disabled");
uint preCallBalance = address(this).balance.sub(msg.value);
require(seedToPrintId[seed] > 0, "Seed does not exist");
ensureEulerBeatsSeedOwner(seed, _owner);
uint256 tokenId = seedToPrintId[seed];
IEulerBeats(EulerBeats).setEnabled(true);
IEulerBeats(EulerBeats).setEnabled(false);
IEulerBeats(EulerBeats).safeTransferFrom(address(this), msg.sender, tokenId, 1, hex"");
uint refundBalance = address(this).balance.sub(preCallBalance);
if (refundBalance > 0) {
require(success, "Refund payment failed");
}
return tokenId;
}
| 7,222,764 | [
1,
2083,
358,
312,
474,
14971,
628,
392,
2062,
5009,
18,
8671,
18,
1132,
1297,
506,
18662,
18,
225,
5009,
1021,
423,
4464,
612,
358,
312,
474,
1172,
434,
225,
389,
8443,
1021,
783,
603,
17,
5639,
3410,
434,
326,
5009,
19,
5059,
2172,
11013,
12647,
1234,
18,
1132,
261,
23444,
358,
506,
1278,
12254,
358,
729,
1603,
17,
1188,
13,
7766,
716,
5009,
353,
923,
8553,
3410,
434,
5009,
473,
3387,
721,
93,
15006,
23178,
968,
1172,
1147,
548,
628,
5009,
9677,
512,
38,
18,
81,
474,
5108,
512,
38,
18,
81,
474,
5108,
9334,
2231,
512,
38,
866,
6205,
471,
16255,
358,
1758,
12,
2211,
13,
10639,
512,
38,
18,
81,
474,
5108,
12279,
1172,
358,
1234,
18,
15330,
2479,
358,
729,
7114,
3086,
783,
471,
675,
1477,
13937,
309,
16966,
25123,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
5108,
12,
11890,
5034,
5009,
16,
1758,
8843,
429,
389,
8443,
13,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2583,
12,
1188,
1526,
16,
315,
5108,
310,
353,
5673,
8863,
203,
203,
3639,
2254,
675,
1477,
13937,
273,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
3576,
18,
1132,
1769,
203,
203,
3639,
2583,
12,
12407,
774,
5108,
548,
63,
12407,
65,
405,
374,
16,
315,
12702,
1552,
486,
1005,
8863,
203,
203,
3639,
3387,
41,
17040,
1919,
2323,
12702,
5541,
12,
12407,
16,
389,
8443,
1769,
203,
203,
3639,
2254,
5034,
1147,
548,
273,
5009,
774,
5108,
548,
63,
12407,
15533,
203,
203,
3639,
10897,
17040,
1919,
2323,
12,
41,
17040,
1919,
2323,
2934,
542,
1526,
12,
3767,
1769,
203,
203,
203,
3639,
10897,
17040,
1919,
2323,
12,
41,
17040,
1919,
2323,
2934,
542,
1526,
12,
5743,
1769,
203,
203,
3639,
10897,
17040,
1919,
2323,
12,
41,
17040,
1919,
2323,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
1147,
548,
16,
404,
16,
3827,
3660,
1769,
203,
203,
3639,
2254,
16255,
13937,
273,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
1484,
1477,
13937,
1769,
203,
3639,
309,
261,
1734,
1074,
13937,
405,
374,
13,
288,
203,
5411,
2583,
12,
4768,
16,
315,
21537,
5184,
2535,
8863,
203,
3639,
289,
203,
540,
203,
3639,
327,
1147,
548,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100
] |
pragma solidity >=0.8.2;
// to enable certain compiler features
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract CyberPigs is ERC721, Ownable {
using Strings for uint256;
//amount of tokens that have been minted so far, in total and in presale
uint256 private numberOfTotalTokens;
//declares the maximum amount of tokens that can be minted, total and in presale
uint256 private maxTotalTokens;
//initial part of the URI for the metadata
string private _currentBaseURI = "https://api.cyberpigs.io/api/metadata/";
//marks the timestamp of when the respective sales open
uint256 internal presaleLaunchTime;
uint256 internal publicSaleLaunchTime;
uint256 internal revealTime;
uint256 private reservedMints_;
uint256 private maxReservedMints = 500;
//if breeding is open or not
bool private breeding;
//stores how many breeds each nft has done
mapping(uint256 => uint256) private breedsPerToken;
uint256 private maxBreeds = 5;
uint256 private mintCostPresale = 0.1 ether;
uint256 private mintCostPublicSale = 0.15 ether;
uint256 private breedCost_ = 0.1 ether;
//amount of mints that each address has executed
mapping(address => uint256) public mintsPerAddress;
//current state os sale
enum State {
NoSale,
Presale,
PublicSale
}
//defines the uri for when the NFTs have not been yet revealed
string public unrevealedURI;
//tokens that have been created from breeding
uint256 private tokensBreeded;
//funds from each category
uint256 private fundsMint;
uint256 private fundsBreed;
address private _withdrawAddress =
0xC91deCE250A0d55CE5febAC6f9951c0c76D3e99f;
//declaring initial values for variables
constructor() ERC721("CyberPigs", "PIGLET") {
maxTotalTokens = 10000;
unrevealedURI = "https://api.cyberpigs.io/api/unrevealed/";
}
//in case somebody accidentaly sends funds or transaction to contract
receive() external payable {}
fallback() external payable {
revert();
}
//visualize baseURI
function _baseURI() internal view virtual override returns (string memory) {
return _currentBaseURI;
}
//change baseURI in case needed for IPFS
function changeBaseURI(string memory baseURI_) public onlyOwner {
_currentBaseURI = baseURI_;
}
function changeUnrevealedURI(string memory unrevealedURI_)
public
onlyOwner
{
unrevealedURI = unrevealedURI_;
}
//change withdraw funds address
function changeWithdrawAddress(address newAddress) public onlyOwner {
_withdrawAddress = newAddress;
}
//gets withdraw funds address
function getWithdrawAddress() public view onlyOwner returns (address) {
require(
address(_withdrawAddress) != address(0),
"Withdraw address is not set yet."
);
return _withdrawAddress;
}
//gets the tokenID of NFT to be minted
function tokenId() internal view returns (uint256) {
uint256 currentId = numberOfTotalTokens;
bool exists = true;
while (exists) {
currentId += 1;
exists = _exists(currentId);
}
return currentId;
}
function switchToPresale() public onlyOwner {
require(saleState() == State.NoSale, "Sale is already Open!");
presaleLaunchTime = block.timestamp;
}
function switchToPublicSale() public onlyOwner {
require(saleState() == State.Presale, "Sale is already Open!");
publicSaleLaunchTime = block.timestamp;
}
//mint a @param number of NFTs in presale
function presaleMint(uint256 number) public payable {
State saleState_ = saleState();
require(saleState_ == State.Presale, "Presale in not open!");
require(
numberOfTotalTokens + number <=
maxTotalTokens - (maxReservedMints - reservedMints_),
"Not enough NFTs left to mint.."
);
require(
msg.value >= mintCost() * number,
"Not sufficient Ether to mint this amount of NFTs"
);
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTotalTokens += 1;
}
fundsMint += msg.value;
}
//mint a @param number of NFTs in presale
function publicSaleMint(uint256 number) public payable {
State saleState_ = saleState();
require(saleState_ == State.PublicSale, "Sale in not open!");
require(
numberOfTotalTokens + number <=
maxTotalTokens - (maxReservedMints - reservedMints_),
"Not enough NFTs left to mint.."
);
require(
msg.value >= mintCost() * number,
"Not sufficient Ether to mint this amount of NFTs"
);
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTotalTokens += 1;
}
fundsMint += msg.value;
}
//reserved NFTs for creator
function reservedMint(uint256 number, address recipient) public onlyOwner {
require(
reservedMints_ + number <= maxReservedMints,
"Not enough Reserved NFTs left to mint.."
);
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(recipient, tid);
mintsPerAddress[recipient] += 1;
numberOfTotalTokens += 1;
reservedMints_ += 1;
}
}
function tokenURI(uint256 tokenId_)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId_),
"ERC721Metadata: URI query for nonexistent token"
);
//check to see that 24 hours have passed since beginning of publicsale launch
if (revealTime == 0) {
return
string(
abi.encodePacked(
unrevealedURI,
tokenId_.toString(),
".json"
)
);
} else {
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(baseURI, tokenId_.toString(), ".json")
)
: "";
}
}
//burn the tokens that have not been sold yet
function burnTokens() public onlyOwner {
maxTotalTokens =
numberOfTotalTokens +
(maxReservedMints - reservedMints_);
}
//se the current account balance
function accountBalance() public view onlyOwner returns (uint256) {
return address(this).balance;
}
//retrieve all funds recieved from minting
function withdrawMint() public onlyOwner {
require(
address(_withdrawAddress) != address(0),
"Withdraw address is not set yet."
);
require(fundsMint > 0, "No Funds to withdraw, Mint Balance is 0");
_withdraw(payable(_withdrawAddress), fundsMint); //to avoid dust eth
fundsMint = 0;
}
//retrieve all funds recieved from minting
function withdrawBreed() public onlyOwner {
require(
address(_withdrawAddress) != address(0),
"Withdraw address is not set yet."
);
require(fundsBreed > 0, "No Funds to withdraw, Breed Balance is 0");
_withdraw(payable(_withdrawAddress), fundsBreed); //to avoid dust eth
fundsBreed = 0;
}
//retrieve all funds
function withdraw(uint256 amount) public onlyOwner {
require(amount <= address(this).balance, "Incorrect amount");
payable(0x653E79D37c39e98977f87a6131b8de456ee396D8).transfer(amount);
fundsBreed = 0;
fundsMint = 0;
}
//send the percentage of funds to a shareholder´s wallet
function _withdraw(address payable account, uint256 amount) internal {
(bool sent, ) = account.call{value: amount}("");
require(sent, "Failed to send Ether");
}
//see the total amount of tokens that have been minted
function totalSupply() public view returns (uint256) {
return numberOfTotalTokens + tokensBreeded;
}
//see current state of sale
//see the current state of the sale
function saleState() public view returns (State) {
if (presaleLaunchTime == 0) {
return State.NoSale;
} else if (publicSaleLaunchTime == 0) {
return State.Presale;
} else {
return State.PublicSale;
}
}
//to reveal the nfts
function reveal() public onlyOwner {
require(
revealTime == 0,
"Can only reveal when current state is unrevealed!"
);
revealTime = block.timestamp;
}
//shows total amount of tokens that could be minted
function maxTokens() public view returns (uint256) {
return maxTotalTokens;
}
function breed(uint256 tokenIdParent1, uint256 tokenIdParent2)
public
payable
{
require(breeding, "Breeding is currently not Open!");
require(
msg.sender == ownerOf(tokenIdParent1) &&
msg.sender == ownerOf(tokenIdParent2),
"Not the owner of this Token!"
);
require(msg.value >= breedCost(), "Insufficient Eth sent to breed!");
require(
breedsPerToken[tokenIdParent1] < maxBreeds &&
breedsPerToken[tokenIdParent2] < maxBreeds,
"Token has reached max breeds!"
);
_safeMint(msg.sender, maxTotalTokens + tokensBreeded + 1);
breedsPerToken[tokenIdParent1] += 1;
breedsPerToken[tokenIdParent2] += 1;
tokensBreeded += 1;
fundsBreed += msg.value;
}
function toggleBreeding() public onlyOwner {
breeding = !breeding;
}
function breedIsOpen() public view returns (bool) {
return breeding;
}
function changeMaxBreeds(uint256 newBreeds) public onlyOwner {
maxBreeds = newBreeds;
}
function breedCost() public view returns (uint256) {
return breedCost_;
}
function changeBreedCost(uint256 newCost) public onlyOwner {
breedCost_ = newCost;
}
function mintCost() public view returns (uint256) {
State saleState_ = saleState();
if (saleState_ == State.NoSale || saleState_ == State.Presale) {
return mintCostPresale;
} else {
return mintCostPublicSale;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | see the total amount of tokens that have been minted | function totalSupply() public view returns (uint256) {
return numberOfTotalTokens + tokensBreeded;
}
| 6,113,930 | [
1,
5946,
326,
2078,
3844,
434,
2430,
716,
1240,
2118,
312,
474,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
7922,
5269,
5157,
397,
2430,
38,
992,
785,
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
] |
pragma solidity ^0.5.0;
//Importing OpenZeppelin's SafeMath Implementation
import "./SafeMath.sol";
contract CrowdfundingCampaign {
using SafeMath for uint256;
address payable public creator;
mapping(address => bool) contributors; //bool to check if contributor supported a campaign
string public title;
string public description;
uint256 public minimumContribution; //minimum constribution a contributor can send set by the creator
uint256 public targetGoal; //The target goal of the campaign set by the creator
uint256 public contributorsCount; //count of contributors for a single campaign
struct Withdrawal {
string description; //reason for withdraw of campaign
uint value; //value creator wants to withdrawl
address payable recipient; //creator can send to either themself or support someone else
bool complete;
uint approvalCount; //contributors vote on if the withdrawl should happen
mapping(address => bool) approvals;
}
Withdrawal[] public withdrawals;
event LogContribution(address contributor, uint256 value);
event LogWithdrawalCreation(address creator, address recipient, uint256 value);
event LogWithdrawalCompletion(address recipient, uint256 value);
constructor(string memory _title, string memory _description, uint256 _minimum, uint256 _goal) public {
creator = msg.sender;
title = _title;
description = _description;
minimumContribution = _minimum;
targetGoal = _goal;
}
//modifier to check if the caller is the owner of the campaign
modifier isCreator {
require(msg.sender == creator, "You must be the owner");
_;
}
//modifier to check if the caller is a contributor of the campaign
modifier isContributor {
require(contributors[msg.sender], "You must be a contributor");
_;
}
//Function to read a single crowdfunding campaign
function readCampaign() public view returns (string memory _title, string memory _description,
uint256 _minimum, uint256 _goal, uint256 _count) {
_title = title;
_description = description;
_minimum = minimumContribution;
_goal = targetGoal;
_count = contributorsCount;
}
/** @dev Function to fund the campaign as a contributor
*/
function contribute() public payable isContributor {
require(msg.value >= minimumContribution, "The contribution must be above the minimum Contribution");
contributors[msg.sender] = true;
contributorsCount++;
emit LogContribution(msg.sender, msg.value);
}
/** @dev Creator creates a withdrawl request to withdrawl funds from raised crowdfund
*/
function createWithdrawlRequest(string memory withdrawalDescription, uint value, address payable recipient) public isCreator {
Withdrawal memory newWithdrawal = Withdrawal ({
description: withdrawalDescription,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
withdrawals.push(newWithdrawal);
emit LogWithdrawalCreation(msg.sender, recipient, value);
}
/** @dev Returns the details for a withdrawl request
*/
function readWithdrawlRequest(uint index)public view returns
(string memory withdrawalDescription, uint256 value,
address recipient, bool complete, uint256 approvalCount) {
withdrawalDescription = withdrawals[index].description;
value = withdrawals[index].value;
recipient = withdrawals[index].recipient;
complete = withdrawals[index].complete;
approvalCount = withdrawals[index].approvalCount;
}
/** @dev Contributor(s) vote on withdrawl request created by the creator of the crowdfund
*/
function approveWithdrawal(uint index) public isContributor {
Withdrawal storage withdrawal = withdrawals[index];
require(!withdrawal.approvals[msg.sender], "Contributor has already voted");
withdrawal.approvals[msg.sender] = true;
withdrawal.approvalCount++;
}
/** @dev Function for Creator to withdrawl funds if contributor vote is grater than 50%
*/
function finalizeWithdrawal(uint index) public isCreator {
Withdrawal storage withdrawal = withdrawals[index];
require(withdrawal.approvalCount > (contributorsCount / 2),"Approval must be greater than 50%");
require(!withdrawal.complete, "Withdrawal must not already be complete");
withdrawal.recipient.transfer(withdrawal.value);
withdrawal.complete = true;
emit LogWithdrawalCompletion(withdrawal.recipient, withdrawal.value);
}
} | * @dev Creator creates a withdrawl request to withdrawl funds from raised crowdfund/ | function createWithdrawlRequest(string memory withdrawalDescription, uint value, address payable recipient) public isCreator {
Withdrawal memory newWithdrawal = Withdrawal ({
description: withdrawalDescription,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
withdrawals.push(newWithdrawal);
emit LogWithdrawalCreation(msg.sender, recipient, value);
}
| 12,864,156 | [
1,
10636,
3414,
279,
598,
9446,
80,
590,
358,
598,
9446,
80,
284,
19156,
628,
11531,
276,
492,
2180,
1074,
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,
752,
1190,
9446,
80,
691,
12,
1080,
3778,
598,
9446,
287,
3291,
16,
2254,
460,
16,
1758,
8843,
429,
8027,
13,
1071,
353,
10636,
288,
203,
3639,
3423,
9446,
287,
3778,
394,
1190,
9446,
287,
273,
3423,
9446,
287,
10797,
203,
5411,
2477,
30,
598,
9446,
287,
3291,
16,
203,
5411,
460,
30,
460,
16,
203,
5411,
8027,
30,
8027,
16,
203,
5411,
3912,
30,
629,
16,
203,
5411,
23556,
1380,
30,
374,
203,
3639,
15549,
203,
3639,
598,
9446,
1031,
18,
6206,
12,
2704,
1190,
9446,
287,
1769,
203,
3639,
3626,
1827,
1190,
9446,
287,
9906,
12,
3576,
18,
15330,
16,
8027,
16,
460,
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
] |
/**
******************************************************************************************************************************************************************************************
$$$$$$$\ $$\ $$\ $$\ $$\
$$ __$$\ $$ | \__| $$ | $$ |
$$ | $$ | $$$$$$\ $$$$$$\$$$$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$$$$$\ $$\ $$$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$ | $$\
$$ | $$ |$$ __$$\ $$ _$$ _$$\ $$ __$$\ $$ _____|$$ __$$\ \____$$\ \_$$ _| $$ |$$ _____| $$ | $$ | $$ |$$ _____|$$ | $$ |
$$ | $$ |$$$$$$$$ |$$ / $$ / $$ |$$ / $$ |$$ / $$ | \__| $$$$$$$ | $$ | $$ |$$ / $$ | $$ | $$ |$$ / $$$$$$ /
$$ | $$ |$$ ____|$$ | $$ | $$ |$$ | $$ |$$ | $$ | $$ __$$ | $$ |$$\ $$ |$$ | $$ | $$ | $$ |$$ | $$ _$$<
$$$$$$$ |\$$$$$$$\ $$ | $$ | $$ |\$$$$$$ |\$$$$$$$\ $$ | \$$$$$$$ | \$$$$ |$$ |\$$$$$$$\ $$$$$$$$\ \$$$$$$ |\$$$$$$$\ $$ | \$$\
\_______/ \_______|\__| \__| \__| \______/ \_______|\__| \_______| \____/ \__| \_______| \________| \______/ \_______|\__| \__|
_ _ _ _
| | | | | |(_)
__ ____ ____ __ ___ | |_ | |__ __ _ __ _ _ __ ___ ___ | | _ __ __ ___
\ \ /\ / /\ \ /\ / /\ \ /\ / / / _ \| __|| '_ \ / _` | / _` || '_ ` _ \ / _ \ | || |\ \ / / / _ \
\ 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;
}
} | * @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;
}
| 13,123,145 | [
1,
1893,
729,
353,
9322,
27037,
316,
279,
3643,
35,
225,
389,
1615,
2279,
225,
3643,
1807,
770,
1158,
225,
389,
4793,
225,
9322,
27037,
2236,
327,
389,
2088,
225,
353,
9322,
27037,
578,
486,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
866,
13614,
38,
16213,
382,
54,
72,
12,
11890,
5034,
389,
1615,
2279,
16,
1758,
389,
4793,
13,
7010,
225,
1071,
7010,
225,
1476,
7010,
225,
1135,
12,
6430,
389,
2088,
13,
7010,
225,
288,
203,
565,
2583,
12,
1893,
54,
72,
4786,
24899,
1615,
2279,
10019,
203,
203,
565,
309,
12,
13623,
56,
363,
38,
9835,
414,
63,
67,
1615,
2279,
6362,
67,
4793,
8009,
16282,
2578,
405,
374,
13,
203,
1377,
327,
638,
31,
203,
565,
327,
629,
31,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.0;
import "./IStorage.sol";
import "./checkingContract.sol";
contract RegistrarMain is checkingContract{
uint256 public registrarFees;
uint256 public safleIdFees;
address public contractOwner;
address payable public walletAddress;
bool public storageContractAddress;
bool public safleIdRegStatus;
RegistrarStorage public registrarStorageContractAddress;
// @dev Modifier to ensure the function caller is the contract owner.
modifier onlyOwner () {
require(msg.sender == contractOwner, "msg sender is not a contract owner");
_;
}
// @dev Modifier to ensure the Storage contract address is set.
modifier checkStorageContractAddress () {
require(storageContractAddress, "storage address not set");
_;
}
// @dev Modifier to ensure the safleId registration is not paused.
modifier checkRegistrationStatus () {
require(safleIdRegStatus == false, "SafleId Registration is Paused");
_;
}
// @dev Modifier to ensure the conditions for Registrar are met.
modifier registrarChecks(string memory _registrarName) {
require(msg.value >= registrarFees, "Registration fees not matched.");
require(isSafleIdValid(_registrarName));
_;
}
// @dev Modifier to ensure the conditions for SafleId registration are met.
modifier safleIdChecks(string memory _safleId) {
require(msg.value >= safleIdFees, "Registration fees not matched.");
require(isSafleIdValid(_safleId));
_;
}
/**
* @dev constructor of the contract
* @param _walletAddress wallet address to transfer fees
*/
constructor (address payable _walletAddress) public {
require(_walletAddress != address(0), "Please provide a valid wallet address.");
contractOwner = msg.sender;
walletAddress = _walletAddress;
}
/**
* @dev Set safleId registration fees
* Only the contract owner can call this function
* @param _amount fees in wei
*/
function setSafleIdFees(uint256 _amount) public onlyOwner
{
require(_amount >= 0, "Please set a fees for SafleID registration.");
safleIdFees = _amount;
}
/**
* @dev Set Registrar registration fees by owner
* Only the contract owner can call this function
* @param _amount fees in wei
*/
function setRegistrarFees(uint256 _amount) public onlyOwner
{
require(_amount >= 0, "Please set a fees for Registrar registration.");
registrarFees = _amount;
}
/**
* @dev Pause and resume the safleId registration
* Only the contract owner can call this function
* @return True if paused, else false.
*/
function toggleRegistrationStatus () external onlyOwner returns (bool){
if(safleIdRegStatus == false){
safleIdRegStatus = true;
}else{
safleIdRegStatus = false;
}
return true;
}
/**
* @dev Register a new Registrar
* Can be called only if safleId registration is not paused and storage contract is set
* This method is payable.
* @param _registrarName Registrar name in string
*/
function registerRegistrar(string memory _registrarName) public registrarChecks(_registrarName)
checkRegistrationStatus
checkStorageContractAddress
payable {
string memory lower = toLower(_registrarName);
walletAddress.transfer(msg.value);
require(registrarStorageContractAddress.registerRegistrar(msg.sender, lower), "Storage contract error.");
}
/**
* @dev Update an already registered Registrar
* This method is payable.
* Can be called only if safleId registration is not paused and storage contract is set
* @param _registrarName string to be taken as a New name of Registrar
*/
function updateRegistrar(string memory _registrarName)
public
registrarChecks(_registrarName)
checkRegistrationStatus
checkStorageContractAddress
payable {
string memory lower = toLower(_registrarName);
walletAddress.transfer(msg.value);
require(registrarStorageContractAddress.updateRegistrar(msg.sender,lower), "Storage contract error.");
}
/**
* @dev Register a user's safleId
* Can be called only if safleId registration is not paused and storage contract is set
* This method is payable.
* @param _userAddress address of the user
* @param _safleId safleId of the user
*/
function registerSafleId(address _userAddress, string memory _safleId)
public
safleIdChecks(_safleId)
checkRegistrationStatus
checkStorageContractAddress
payable
{
string memory lower = toLower(_safleId);
walletAddress.transfer(msg.value);
require(registrarStorageContractAddress.registerSafleId(msg.sender,_userAddress,lower), "Storage contract error.");
}
/**
* @dev Update the safleId of a user
* Can be called only if safleId registration is not paused and storage contract is set
* This method is payable.
* @param _userAddress address of a user
* @param _newSafleId new safleId of the user to update
*/
function updateSafleId(address _userAddress, string memory _newSafleId)
public
safleIdChecks(_newSafleId)
checkRegistrationStatus
checkStorageContractAddress
payable
{
string memory lower = toLower(_newSafleId);
walletAddress.transfer(msg.value);
require(registrarStorageContractAddress.updateSafleId(msg.sender,_userAddress,lower), "Storage contract error.");
}
/**
* @dev Set registrar storage contract address
* Can be called only be the contract owner
* @param _registrarStorageContract Address of the storage contract
*/
function setStorageContract(RegistrarStorage _registrarStorageContract) onlyOwner
public
{
registrarStorageContractAddress = _registrarStorageContract;
storageContractAddress = true;
}
/**
* @dev Update wallet address to collect fees
* Can be called only by the contract owner
* This method is payable.
* @param _walletAddress to redirect fees
*/
function updateWalletAddress(address payable _walletAddress) onlyOwner
public
{
require(!isContract(_walletAddress));
walletAddress = _walletAddress;
}
/**
* @dev Create an other coin address mapping
* @param _indexnumber index of a new coin
* @param _blockchainName Name of the coin
* @param _aliasName Alias name in string
* @return true if successful, else false
*/
function mapCoins(uint256 _indexnumber, string calldata _blockchainName, string calldata _aliasName) external returns (bool){
string memory lowerBlockchainName = toLower(_blockchainName);
string memory lowerAliasName = toLower(_aliasName);
require(_indexnumber != 0);
require(checkAlphaNumeric(lowerBlockchainName) && checkAlphaNumeric(lowerAliasName), "Only alphanumeric allowed in blockchain name and alias name");
require(registrarStorageContractAddress.mapCoin(_indexnumber,lowerBlockchainName,lowerAliasName, msg.sender),"Storage contract fails");
return true;
}
/**
* @dev Register a new coin address
* @param _userAddress public address of a user
* @param _index index of the blockchain to set the address
* @param _address Coin address
* @return true if successful, else false
*/
function registerCoinAddress(address _userAddress,uint256 _index, string calldata _address) external returns (bool){
string memory lowerAddress = toLower(_address);
uint8 length = checkLength(_address);
require(_index != 0 && _userAddress != address(0));
require(length > 0);
require(registrarStorageContractAddress.registerCoinAddress(_userAddress,_index,lowerAddress, msg.sender),"Storage contract fail");
}
/**
* @dev Update the coin address of that user
* @param _userAddress address of the user
* @param _index index of that blockchain
* @param _address new address of that coin
* @return true if successful, else false
*/
function updateCoinAddress(address _userAddress,uint256 _index, string calldata _address) external returns (bool){
string memory lowerAddress = toLower(_address);
uint8 length = checkLength(_address);
require(_index != 0 && _userAddress != address(0));
require(length > 0);
require(registrarStorageContractAddress.updateCoinAddress(_userAddress,_index,lowerAddress, msg.sender),"Storage contract fail");
}
}
| * @dev Update the safleId of a user Can be called only if safleId registration is not paused and storage contract is set This method is payable. @param _userAddress address of a user @param _newSafleId new safleId of the user to update/ | function updateSafleId(address _userAddress, string memory _newSafleId)
public
safleIdChecks(_newSafleId)
checkRegistrationStatus
checkStorageContractAddress
payable
{
string memory lower = toLower(_newSafleId);
walletAddress.transfer(msg.value);
require(registrarStorageContractAddress.updateSafleId(msg.sender,_userAddress,lower), "Storage contract error.");
}
| 1,039,796 | [
1,
1891,
326,
11029,
298,
548,
434,
279,
729,
4480,
506,
2566,
1338,
309,
11029,
298,
548,
7914,
353,
486,
17781,
471,
2502,
6835,
353,
444,
1220,
707,
353,
8843,
429,
18,
225,
389,
1355,
1887,
1758,
434,
279,
729,
225,
389,
2704,
26946,
298,
548,
394,
11029,
298,
548,
434,
326,
729,
358,
1089,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
26946,
298,
548,
12,
2867,
389,
1355,
1887,
16,
533,
3778,
389,
2704,
26946,
298,
548,
13,
203,
565,
1071,
203,
565,
11029,
298,
548,
4081,
24899,
2704,
26946,
298,
548,
13,
203,
565,
866,
7843,
1482,
203,
565,
866,
3245,
8924,
1887,
203,
565,
8843,
429,
203,
565,
288,
203,
203,
3639,
533,
3778,
2612,
273,
358,
4070,
24899,
2704,
26946,
298,
548,
1769,
203,
3639,
9230,
1887,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
3639,
2583,
12,
1574,
3337,
297,
3245,
8924,
1887,
18,
2725,
26946,
298,
548,
12,
3576,
18,
15330,
16,
67,
1355,
1887,
16,
8167,
3631,
315,
3245,
6835,
555,
1199,
1769,
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
] |
./full_match/1/0xee415688D294C2956B5d5e4220db281DB2cF4076/sources/browser/Arbitrage22.sol | ERC20Interface(tokenAddress).approve(uniExchange, amount); | if (task == 32) {
address uniExchange = UniswapFactory(uniFactoryAddress).getExchange(tokenAddress);
if(Uniswap(uniExchange).getTokenToEthInputPrice(amount) >= min){
tokenAddress.call(abi.encodeWithSignature("approve(address,uint256)", uniExchange, uint(-1)));
uint balance = ERC20Interface(tokenAddress).balanceOf(address(this));
if (amount > balance) {
uint need = amount.sub(balance);
amount = balance.add(borrowToken(tokenAddress, need));
}
uniExchange.call(abi.encodeWithSignature("tokenToEthSwapInput(uint256,uint256,uint256)", amount, min, 999999999999999999999));
emit Report(2);
}
}
| 3,179,584 | [
1,
654,
39,
3462,
1358,
12,
2316,
1887,
2934,
12908,
537,
12,
318,
77,
11688,
16,
3844,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
4146,
422,
3847,
13,
288,
203,
5411,
1758,
7738,
11688,
273,
1351,
291,
91,
438,
1733,
12,
318,
77,
1733,
1887,
2934,
588,
11688,
12,
2316,
1887,
1769,
203,
5411,
309,
12,
984,
291,
91,
438,
12,
318,
77,
11688,
2934,
588,
1345,
774,
41,
451,
1210,
5147,
12,
8949,
13,
1545,
1131,
15329,
203,
5411,
1147,
1887,
18,
1991,
12,
21457,
18,
3015,
1190,
5374,
2932,
12908,
537,
12,
2867,
16,
11890,
5034,
2225,
16,
7738,
11688,
16,
2254,
19236,
21,
3719,
1769,
203,
2398,
203,
5411,
2254,
11013,
273,
4232,
39,
3462,
1358,
12,
2316,
1887,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
309,
261,
8949,
405,
11013,
13,
288,
203,
7734,
2254,
1608,
273,
3844,
18,
1717,
12,
12296,
1769,
203,
7734,
3844,
273,
11013,
18,
1289,
12,
70,
15318,
1345,
12,
2316,
1887,
16,
1608,
10019,
203,
5411,
289,
203,
203,
5411,
7738,
11688,
18,
1991,
12,
21457,
18,
3015,
1190,
5374,
2932,
2316,
774,
41,
451,
12521,
1210,
12,
11890,
5034,
16,
11890,
5034,
16,
11890,
5034,
2225,
16,
3844,
16,
1131,
16,
23841,
7991,
7991,
7991,
7991,
10019,
203,
7734,
3626,
8706,
12,
22,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// pragma solidity ^0.4.24;
pragma solidity ^0.4.19; //for Ethereum Classic
import "./dependencies/SafeMath.sol";
import "./dependencies/Ownable.sol";
import "./dependencies/RLP.sol";
import "./dependencies/BytesLib.sol";
import "./dependencies/ERC721Basic.sol";
import "./dependencies/ERC721BasicToken.sol";
import "./dependencies/AddressUtils.sol";
contract TokenContract is ERC721BasicToken {
using SafeMath for uint256;
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
using RLP for bytes;
using BytesLib for bytes;
address depositContract;
address custodian;
address custodianHome;
uint256 mintedAmount;
uint256 public mintNonce = 0;
mapping (uint256 => uint256) public transferNonce;
mapping (bytes32 => address) public custodianApproval;
constructor (address _custodian) {
custodian = _custodian;
}
modifier onlyCustodian() {
require(custodian == msg.sender);
_;
}
event Mint(uint256 amount,
address indexed depositedTo,
uint256 mintNonce,
uint256 tokenId);
event Withdraw(uint256 tokenId);
event TransferRequest(address indexed from,
address indexed to,
uint256 indexed tokenId,
uint256 declaredNonce,
bytes32 approvalHash);
function setDepositContract(address _depositContract) onlyCustodian public {
depositContract = _depositContract;
}
function mint(uint256 _value, address _to) public {
//might have to log the value, to, Z details
bytes memory value = uint256ToBytes(_value);
bytes memory to = addressToBytes(_to);
bytes memory Z = uint256ToBytes(mintNonce);
uint256 tokenId = bytes32ToUint256(keccak256(value.concat(to).concat(Z)));
_mint(_to, tokenId);
emit Mint(_value, _to, mintNonce, tokenId);
mintNonce += 1;
}
function withdraw(uint256 _tokenId) public {
emit Withdraw(_tokenId);
//USED TO ANNOUNCE A WITHDRAWL (DOESNT NECESSISTATE SUBMISSION)
}
/* ERC721 Related Functions --------------------------------------------------*/
// Mapping from token ID to approved address
/**
* @dev Requests transfer of 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
* @param _declaredNonce uint256 nonce, depth of transaction
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId,
uint256 _declaredNonce
)
public
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
require(_declaredNonce == transferNonce[_tokenId]);
clearApproval(_from, _tokenId);
//TODO: Double check if hash is secure, no chance of collision
bytes32 approvalHash = keccak256(uint256ToBytes(_tokenId)
.concat(uint256ToBytes(_declaredNonce)));
custodianApproval[approvalHash] = _to;
transferNonce[_tokenId] += 1;
emit TransferRequest(_from, _to, _tokenId, _declaredNonce, approvalHash);
}
function custodianApprove(uint256 _tokenId, uint256 _declaredNonce)
onlyCustodian public {
require(exists(_tokenId));
bytes32 approvalHash = keccak256(uint256ToBytes(_tokenId)
.concat(uint256ToBytes(_declaredNonce)));
address _to = custodianApproval[approvalHash];
address _from = ownerOf(_tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
clearCustodianApproval(approvalHash);
}
function revertTransfer(uint256 _tokenId, uint256 _declaredNonce) public {
require(isApprovedOrOwner(msg.sender, _tokenId), "no approval/ not owner");
clearCustodianApproval(keccak256(uint256ToBytes(_tokenId)
.concat(uint256ToBytes(_declaredNonce))));
}
/* View functions --------------------------------------------------*/
function viewTransferRequest(bytes32 _approvalHash) public view
returns(address) {
return custodianApproval[_approvalHash];
}
/* Util functions --------------------------------------------------*/
/**
* @dev Internal function to clear current custodian approval of a given token ID
* @param _approvalHash bytes32 ID of the token to be transferred
*/
function clearCustodianApproval(bytes32 _approvalHash) internal {
if (custodianApproval[_approvalHash] != address(0)) {
custodianApproval[_approvalHash] = address(0);
}
}
function bytesToBytes32(bytes b, uint offset) private pure returns (bytes32) {
bytes32 out;
for (uint i = 0; i < 32; i++) {
out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
function stringToBytes( string s) internal returns (bytes memory b3){
b3 = bytes(s);
return b3;
}
// Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity
function uint256ToBytes(uint256 x) internal returns (bytes b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
// Tjaden Hess https://ethereum.stackexchange.com/questions/884/how-to-convert-an-address-to-bytes-in-solidity
function addressToBytes(address a) internal returns (bytes b) {
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
// https://ethereum.stackexchange.com/questions/6498/how-to-convert-a-uint256-type-integer-into-a-bytes32
function bytes32ToUint256(bytes32 n) internal returns (uint256) {
return uint256(n);
}
}
| TODO: Double check if hash is secure, no chance of collision | function transferFrom(
address _from,
address _to,
uint256 _tokenId,
uint256 _declaredNonce
)
public
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
require(_declaredNonce == transferNonce[_tokenId]);
clearApproval(_from, _tokenId);
bytes32 approvalHash = keccak256(uint256ToBytes(_tokenId)
.concat(uint256ToBytes(_declaredNonce)));
custodianApproval[approvalHash] = _to;
transferNonce[_tokenId] += 1;
emit TransferRequest(_from, _to, _tokenId, _declaredNonce, approvalHash);
}
| 7,283,675 | [
1,
6241,
30,
3698,
866,
309,
1651,
353,
8177,
16,
1158,
17920,
434,
17740,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7412,
1265,
12,
203,
565,
1758,
389,
2080,
16,
203,
565,
1758,
389,
869,
16,
203,
565,
2254,
5034,
389,
2316,
548,
16,
203,
565,
2254,
5034,
389,
16571,
13611,
203,
225,
262,
203,
565,
1071,
203,
225,
288,
203,
565,
2583,
12,
291,
31639,
1162,
5541,
12,
3576,
18,
15330,
16,
389,
2316,
548,
10019,
203,
565,
2583,
24899,
2080,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
16571,
13611,
422,
7412,
13611,
63,
67,
2316,
548,
19226,
203,
203,
565,
2424,
23461,
24899,
2080,
16,
389,
2316,
548,
1769,
203,
565,
1731,
1578,
23556,
2310,
273,
417,
24410,
581,
5034,
12,
11890,
5034,
21033,
24899,
2316,
548,
13,
203,
21821,
263,
16426,
12,
11890,
5034,
21033,
24899,
16571,
13611,
3719,
1769,
203,
565,
276,
641,
369,
2779,
23461,
63,
12908,
1125,
2310,
65,
273,
389,
869,
31,
203,
565,
7412,
13611,
63,
67,
2316,
548,
65,
1011,
404,
31,
203,
565,
3626,
12279,
691,
24899,
2080,
16,
389,
869,
16,
389,
2316,
548,
16,
389,
16571,
13611,
16,
23556,
2310,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x4E2D021Dd1b6e8F723aEd274bb05Ebec56aF8FF8/sources/contracts/Reserve/Reserve.sol | * @inheritdoc IReserve/ | function initialize(IPrimexDNS _dns, address _registry) external override initializer {
_require(
IERC165Upgradeable(address(_dns)).supportsInterface(type(IPrimexDNS).interfaceId) &&
IERC165Upgradeable(_registry).supportsInterface(type(IAccessControl).interfaceId),
Errors.ADDRESS_NOT_SUPPORTED.selector
);
registry = _registry;
dns = _dns;
__Pausable_init();
__ERC165_init();
__ReentrancyGuard_init();
}
| 4,746,855 | [
1,
36,
10093,
467,
607,
6527,
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,
4046,
12,
45,
2050,
381,
338,
11602,
389,
14926,
16,
1758,
389,
9893,
13,
3903,
3849,
12562,
288,
203,
3639,
389,
6528,
12,
203,
5411,
467,
654,
39,
28275,
10784,
429,
12,
2867,
24899,
14926,
13,
2934,
28064,
1358,
12,
723,
12,
45,
2050,
381,
338,
11602,
2934,
5831,
548,
13,
597,
203,
7734,
467,
654,
39,
28275,
10784,
429,
24899,
9893,
2934,
28064,
1358,
12,
723,
12,
45,
16541,
2934,
5831,
548,
3631,
203,
5411,
9372,
18,
15140,
67,
4400,
67,
21134,
18,
9663,
203,
3639,
11272,
203,
3639,
4023,
273,
389,
9893,
31,
203,
3639,
6605,
273,
389,
14926,
31,
203,
3639,
1001,
16507,
16665,
67,
2738,
5621,
203,
3639,
1001,
654,
39,
28275,
67,
2738,
5621,
203,
3639,
1001,
426,
8230,
12514,
16709,
67,
2738,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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);
}
pragma solidity ^0.6.0;
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;
}
}
pragma solidity ^0.6.0;
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity 0.6.6;
contract ESkillzStraightBet is Ownable {
using SafeMath for uint256;
IERC20 public cue;
mapping(uint256 => mapping (address => uint256)) private balances;
struct Game {
uint256 table_id;
address [] players; // players
address landowner; // land owner address
string status; // created, started, finished.
uint256 game_level; // 0 => amatuer, 1 => professional, 2 => championship
uint256 game_type; // 0 => pool game, 1 => golf, 2 => football
uint256 max_players; // should be bigger than 1
}
uint256 [] table_fee = [0,0,0]; // 0 => amatuer, 1 => professional, 2 => championship
uint256 private eskillz_fee;
address public eskillzFeeReceiver;
uint256 [] landprice = [100,300,500];
event Deposit(address player, uint256 amount, uint256 game_id);
mapping (uint256 => Game) private game_list;
mapping (uint256 => uint256) private bet_amount;
uint256 public game_count = 0;
constructor (address addr) public { cue = IERC20(addr); eskillz_fee = 0;}
function createGame(address landowner, uint256 game_type, uint256 game_level, uint256 amount, uint256 max_players ) public {
require(max_players > 1, "max players should be bigger than 1");
Game memory new_game = Game({ table_id: game_count, players: new address[](0), landowner:landowner, status: "created", game_level: game_level, game_type: game_type, max_players:max_players});
game_list[game_count] = new_game;
joinGame(amount, game_count);
game_count++;
}
function joinGame(uint256 amount, uint256 game_id) public {
require(amount>0, "betting amount should be bigger than zero");
require(game_count>=game_id, "this game is not created!");
require(keccak256(abi.encodePacked((game_list[game_id].status)))== keccak256(abi.encodePacked(("created"))), "this game already started or finished");
require(game_list[game_id].players.length<game_list[game_id].max_players, "already filled all players");
game_list[game_id].players.push(msg.sender);
balances[game_id][msg.sender] = balances[game_id][msg.sender].add(amount);
bet_amount[game_id] = bet_amount[game_id].add(amount);
//require(cue.balanceOf(msg.sender) >= amount,"balance is low");
cue.transferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, game_id);
}
function startGame(uint256 game_id) public {
require(game_list[game_id].players.length>1, "more players need to join this game to start.");
game_list[game_id].status = "started";
}
function getDistrubuteAmount(uint256 game_id) private returns(uint256, uint256, uint256) {
uint256 tableFeeAmount = bet_amount[game_id].mul(table_fee[game_list[game_id].game_level]).div(100);
uint256 eskillzFeeAmount = bet_amount[game_id].mul(eskillz_fee).div(100);
uint256 winnerAmount = bet_amount[game_id] - tableFeeAmount - eskillzFeeAmount;
return (winnerAmount, tableFeeAmount, eskillzFeeAmount);
}
function finishGame(uint256 game_id, address winner) public {
game_list[game_id].status = "finished";
(uint256 winnerAmount, uint256 tableFee, uint256 eskillzFee) = getDistrubuteAmount(game_id);
cue.transfer(winner, winnerAmount);
cue.transfer(game_list[game_id].landowner, tableFee);
cue.transfer(eskillzFeeReceiver, eskillzFee);
}
function getGame(uint256 game_id) public view returns (uint256, address[] memory, string memory, uint256, uint256) {
return (game_list[game_id].table_id, game_list[game_id].players, game_list[game_id].status, game_list[game_id].game_type, game_list[game_id].max_players);
}
function totalBetAmountOnGame(uint256 game_id) public view returns(uint256) {
return bet_amount[game_id];
}
function getTableFee() public view returns(uint256, uint256, uint256) {
return (table_fee[0], table_fee[1], table_fee[2]);
}
function setTableFee(uint256 _aFee, uint256 _pFee, uint256 _cFee) public {
table_fee[0] = _aFee; table_fee[1] = _pFee; table_fee[2] = _cFee;
}
function getESkillzFee() public view returns(uint256) {
return eskillz_fee;
}
function setESkillzFee(uint256 _fee) public {
eskillz_fee = _fee;
}
function setEskilzFeeReceiver(address _feeReceiver) public {
eskillzFeeReceiver = _feeReceiver;
}
function landPrice() public view returns(uint256, uint256, uint256) {
return (landprice[0], landprice[1], landprice[2]);
}
function setLandPrice(uint256 _price0, uint256 _price1, uint256 _price2) public {
landprice[0] = _price0;
landprice[1] = _price1;
landprice[2] = _price2;
}
function buyLand(uint8 level) public {
cue.transferFrom(msg.sender, address(this), landprice[level]);
}
}
| should be bigger than 1
| uint256 max_players; | 12,950,860 | [
1,
13139,
506,
18983,
2353,
404,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
943,
67,
1601,
414,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "./interfaces.sol";
import "./helpers.sol";
contract Resolver is Helpers {
/**
* @dev Sort token address
* @param _token0: token0 Address
* @param _token1: token1 Address
*/
function sort(address _token0, address _token1) external view returns (address token0, address token1) {
if (_token0 < _token1) {
token0 = _token1;
token1 = _token0;
} else {
token0 = _token0;
token1 = _token1;
}
}
function getPositionInfoByTokenId(uint256 tokenId) public view returns (PositionInfo memory pInfo) {
(pInfo) = positions(tokenId);
}
function getPositionsInfo(address user)
public
view
returns (uint256[] memory tokenIds, PositionInfo[] memory positionsInfo)
{
tokenIds = userNfts(user);
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
(positionsInfo[i]) = positions(tokenId);
}
}
function getDepositAmount(
uint256 tokenId,
uint256 amountA,
uint256 amountB
)
public
view
returns (
uint256 liquidity,
uint256 amount0,
uint256 amount1
)
{
(liquidity, amount0, amount1) = depositAmount(tokenId, amountA, amountB);
}
function getSigleDepositAmount(
uint256 tokenId,
address tokenA,
uint256 amountA
)
public
view
returns (
address,
uint256,
address,
uint256
)
{
(address tokenB, uint256 amountB) = singleDepositAmount(tokenId, tokenA, amountA);
return (tokenA, amountA, tokenB, amountB);
}
function getWithdrawAmount(uint256 tokenId, uint128 liquidity)
public
view
returns (uint256 amountA, uint256 amountB)
{
(amountA, amountB) = withdrawAmount(tokenId, liquidity);
}
function getCollectAmount(uint256 tokenId) public view returns (uint256 amountA, uint256 amountB) {
(amountA, amountB) = collectInfo(tokenId);
}
function getUserNFTs(address user) public view returns (uint256[] memory tokenIds) {
tokenIds = userNfts(user);
}
}
contract InstaUniswapV3Resolver is Resolver {
string public constant name = "UniswapV3-Resolver-v1";
}
pragma solidity =0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol";
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
pragma solidity 0.7.6;
pragma abicoder v2;
import { DSMath } from "../../utils/dsmath.sol";
import "./contracts/interfaces/IUniswapV3Pool.sol";
import "./contracts/libraries/TickMath.sol";
import "./contracts/libraries/FullMath.sol";
import "./contracts/libraries/FixedPoint128.sol";
import "./contracts/libraries/LiquidityAmounts.sol";
import "./contracts/libraries/PositionKey.sol";
import "./contracts/libraries/PoolAddress.sol";
import "./interfaces.sol";
abstract contract Helpers is DSMath {
/**
* @dev Return ethereum address
*/
address internal constant ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
* @dev Return Wrapped ETH address
*/
address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
INonfungiblePositionManager private nftManager = INonfungiblePositionManager(getUniswapNftManagerAddr());
/**
* @dev Return uniswap v3 NFT Manager Address
*/
function getUniswapNftManagerAddr() internal pure returns (address) {
return 0xC36442b4a4522E871399CD717aBDD847Ab11FE88;
}
function convert18ToDec(uint256 _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = (_amt / 10**(18 - _dec));
}
function convertTo18(uint256 _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = mul(_amt, 10**(18 - _dec));
}
function changeEthAddress(address buy, address sell)
internal
pure
returns (TokenInterface _buy, TokenInterface _sell)
{
_buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy);
_sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell);
}
/**
* @dev Return uniswap v3 Swap Router Address
*/
function getUniswapRouterAddr() internal pure returns (address) {
return 0xE592427A0AEce92De3Edee1F18E0157C05861564;
}
/**
* @dev Get Last NFT Index
* @param user: User address
*/
function getLastNftId(address user) internal view returns (uint256 tokenId) {
uint256 len = nftManager.balanceOf(user);
tokenId = nftManager.tokenOfOwnerByIndex(user, len - 1);
}
function userNfts(address user) internal view returns (uint256[] memory tokenIds) {
uint256 len = nftManager.balanceOf(user);
tokenIds = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
uint256 tokenId = nftManager.tokenOfOwnerByIndex(user, i);
tokenIds[i] = tokenId;
}
}
function getMinAmount(
TokenInterface token,
uint256 amt,
uint256 slippage
) internal view returns (uint256 minAmt) {
uint256 _amt18 = convertTo18(token.decimals(), amt);
minAmt = wmul(_amt18, sub(WAD, slippage));
minAmt = convert18ToDec(token.decimals(), minAmt);
}
struct PositionInfo {
address token0;
address token1;
address pool;
uint24 fee;
int24 tickLower;
int24 tickUpper;
int24 currentTick;
uint128 liquidity;
uint128 tokenOwed0;
uint128 tokenOwed1;
uint256 amount0;
uint256 amount1;
uint256 collectAmount0;
uint256 collectAmount1;
}
function positions(uint256 tokenId) internal view returns (PositionInfo memory pInfo) {
(
,
,
pInfo.token0,
pInfo.token1,
pInfo.fee,
pInfo.tickLower,
pInfo.tickUpper,
pInfo.liquidity,
,
,
,
) = nftManager.positions(tokenId);
(, , , , , , , , , , pInfo.tokenOwed0, pInfo.tokenOwed1) = nftManager.positions(tokenId);
pInfo.pool = getPoolAddress(pInfo.token0, pInfo.token1, pInfo.fee);
IUniswapV3Pool pool = IUniswapV3Pool(pInfo.pool);
(, pInfo.currentTick, , , , , ) = pool.slot0();
(pInfo.amount0, pInfo.amount1) = withdrawAmount(tokenId, pInfo.liquidity);
(pInfo.collectAmount0, pInfo.collectAmount1) = collectInfo(tokenId);
}
function getPoolAddress(
address token0,
address token1,
uint24 fee
) internal view returns (address poolAddr) {
poolAddr = PoolAddress.computeAddress(
nftManager.factory(),
PoolAddress.PoolKey({ token0: token0, token1: token1, fee: fee })
);
}
function depositAmount(
uint256 tokenId,
uint256 amountA,
uint256 amountB
)
internal
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(, , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, , , , , ) = nftManager
.positions(tokenId);
IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee));
// compute the liquidity amount
{
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amountA,
amountB
);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
// amount0 = sub(amountA, amount0);
// amount1 = sub(amountB, amount1);
}
}
function singleDepositAmount(
uint256 tokenId,
address tokenA,
uint256 amountA
) internal view returns (address tokenB, uint256 amountB) {
(, , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, , , , , ) = nftManager
.positions(tokenId);
bool reverseFlag = false;
if (tokenA != _token0) {
(tokenA, tokenB) = (_token0, _token1);
reverseFlag = true;
} else {
tokenB = _token1;
}
if (!reverseFlag) {
uint128 liquidity = LiquidityAmounts.getLiquidityForAmount0(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amountA
);
amountB = LiquidityAmounts.getAmount1ForLiquidity(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
} else {
uint128 liquidity = LiquidityAmounts.getLiquidityForAmount1(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amountA
);
amountB = LiquidityAmounts.getAmount0ForLiquidity(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
}
function withdrawAmount(uint256 tokenId, uint128 liquidity)
internal
view
returns (uint256 amount0, uint256 amount1)
{
require(liquidity > 0, "liquidity should greater than 0");
(
,
,
address _token0,
address _token1,
uint24 _fee,
int24 tickLower,
int24 tickUpper,
uint128 positionLiquidity,
,
,
,
) = nftManager.positions(tokenId);
require(positionLiquidity >= liquidity, "Liquidity amount is over than position liquidity amount");
IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee));
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
function collectInfo(uint256 tokenId) internal view returns (uint256 amount0, uint256 amount1) {
(
,
,
address _token0,
address _token1,
uint24 _fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 _feeGrowthInside0LastX128,
uint256 _feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
) = nftManager.positions(tokenId);
IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee));
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(
PositionKey.compute(getUniswapNftManagerAddr(), tickLower, tickUpper)
);
tokensOwed0 += uint128(
FullMath.mulDiv(feeGrowthInside0LastX128 - _feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128)
);
tokensOwed1 += uint128(
FullMath.mulDiv(feeGrowthInside1LastX128 - _feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128)
);
amount0 = tokensOwed0;
amount1 = tokensOwed1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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.7.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.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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "math-not-safe");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x - y <= x ? x - y : 0;
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
uint256 internal constant WAD = 10**18;
uint256 internal constant RAY = 10**27;
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./pool/IUniswapV3PoolImmutables.sol";
import "./pool/IUniswapV3PoolState.sol";
import "./pool/IUniswapV3PoolDerivedState.sol";
import "./pool/IUniswapV3PoolActions.sol";
import "./pool/IUniswapV3PoolOwnerActions.sol";
import "./pool/IUniswapV3PoolEvents.sol";
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
pragma solidity >=0.5.0;
import "./FullMath.sol";
import "./FixedPoint96.sol";
library LiquidityAmounts {
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
pragma solidity >=0.5.0;
library PositionKey {
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
pragma solidity >=0.5.0;
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({ token0: tokenA, token1: tokenB, fee: fee });
}
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
| * @dev Get Last NFT Index @param user: User address/ | function getLastNftId(address user) internal view returns (uint256 tokenId) {
uint256 len = nftManager.balanceOf(user);
tokenId = nftManager.tokenOfOwnerByIndex(user, len - 1);
}
| 480,249 | [
1,
967,
6825,
423,
4464,
3340,
225,
729,
30,
2177,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7595,
50,
1222,
548,
12,
2867,
729,
13,
2713,
1476,
1135,
261,
11890,
5034,
1147,
548,
13,
288,
203,
3639,
2254,
5034,
562,
273,
290,
1222,
1318,
18,
12296,
951,
12,
1355,
1769,
203,
3639,
1147,
548,
273,
290,
1222,
1318,
18,
2316,
951,
5541,
21268,
12,
1355,
16,
562,
300,
404,
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
] |
./full_match/100/0x87926e4dCB09bE44B54b9863322c43DfdA98b687/sources/contracts/LSP20CallVerification/LSP20CallVerification.sol | Look for revert reason and bubble it up if present The easiest way to bubble the revert reason is using memory via assembly solhint-disable no-inline-assembly @solidity memory-safe-assembly | function _revert(bool postCall, bytes memory returnedData) internal pure {
if (returnedData.length > 0) {
assembly {
let returndata_size := mload(returnedData)
revert(add(32, returnedData), returndata_size)
}
revert LSP20CallingVerifierFailed(postCall);
}
}
| 14,285,087 | [
1,
9794,
364,
15226,
3971,
471,
21577,
518,
731,
309,
3430,
1021,
7264,
77,
395,
4031,
358,
21577,
326,
15226,
3971,
353,
1450,
3778,
3970,
19931,
3704,
11317,
17,
8394,
1158,
17,
10047,
17,
28050,
632,
30205,
560,
3778,
17,
4626,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
266,
1097,
12,
6430,
1603,
1477,
16,
1731,
3778,
2106,
751,
13,
2713,
16618,
288,
203,
3639,
309,
261,
2463,
329,
751,
18,
2469,
405,
374,
13,
288,
203,
5411,
19931,
288,
203,
7734,
2231,
327,
892,
67,
1467,
519,
312,
945,
12,
2463,
329,
751,
13,
203,
7734,
15226,
12,
1289,
12,
1578,
16,
2106,
751,
3631,
327,
892,
67,
1467,
13,
203,
5411,
289,
203,
5411,
15226,
511,
3118,
3462,
19677,
17758,
2925,
12,
2767,
1477,
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
] |
pragma solidity 0.5.2;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance ; //inject UNINIT LOCAL/STATE VAR
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance ; //inject UNINIT LOCAL/STATE VAR
require(token.approve(spender, newAllowance));
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract Freeze is Ownable, ERC20 {
using SafeMath for uint256;
uint256 public endOfIco;
uint256 public unlockSchema ; //inject UNINIT LOCAL/STATE VAR
struct Group {
address[] holders;
uint until;
}
/**
* @dev number of groups
*/
uint public groups;
address[] public gofindAllowedAddresses; // ADD 0xO ADDRESS AT FIRST PLACE
/**
* @dev link group ID ---> Group structure
*/
mapping (uint => Group) public lockup;
/**
* @dev Check if holder under lock up
*/
modifier lockupEnded (address _holder, address _recipient, uint256 actionAmount) {
uint index ; //inject UNINIT LOCAL/STATE VAR
if (index == 0) {
bool freezed;
uint groupId;
(freezed, groupId) = isFreezed(_holder);
if (freezed) {
if (lockup[groupId-1].until < block.timestamp)
_;
else if (getFullMonthAfterIco() != 0) {
uint256 available ; //inject UNINIT LOCAL/STATE VAR
if (actionAmount > available)
revert("Your holdings are freezed and your trying to use amount more than available");
else
_;
}
else
revert("Your holdings are freezed, wait until transfers become allowed");
}
else
_;
}
else
_;
}
/**
* @dev in timestamp
*/
function changeEndOfIco (uint256 _date) public onlyOwner returns (bool) {
endOfIco = _date;
}
function addGofindAllowedAddress (address _newAddress) public onlyOwner returns (bool) {
require(indexOf(_newAddress, gofindAllowedAddresses) == 0, "that address already exists");
gofindAllowedAddresses.push(_newAddress);
return true;
}
/**
* @param _holder address of token holder to check
* @return bool - status of freezing and group
*/
function isFreezed (address _holder) public view returns(bool, uint) {
bool freezed ; //inject UNINIT LOCAL/STATE VAR
uint i ; //inject UNINIT LOCAL/STATE VAR
while (i < groups) {
uint index ; //inject UNINIT LOCAL/STATE VAR
if (index == 0) {
if (checkZeroIndex(_holder, i)) {
freezed = true;
i++;
continue;
}
else {
i++;
continue;
}
}
if (index != 0) {
freezed = true;
i++;
continue;
}
i++;
}
if (!freezed) i = 0;
return (freezed, i);
}
/**
* @dev internal usage to get index of holder in group
* @param element address of token holder to check
* @param at array of addresses that is group of holders
* @return index of holder at array
*/
function indexOf (address element, address[] memory at) internal pure returns (uint) {
for (uint i; i < at.length; i++) { //inject UNINIT LOCAL/STATE VAR
if (at[i] == element) return i;
}
return 0;
}
/**
* @dev internal usage to check that 0 is 0 index or it means that address not exists
* @param _holder address of token holder to check
* @param lockGroup id of group to check address existance in it
* @return true if holder at zero index at group false if holder doesn't exists
*/
function checkZeroIndex (address _holder, uint lockGroup) internal view returns (bool) {
if (lockup[lockGroup].holders[0] == _holder)
return true;
else
return false;
}
/**
* @dev returns available tokens amount after linear release for msg.sender
*/
function getAvailableAmount () internal view returns (uint256) {
uint256 monthes ; //inject UNINIT LOCAL/STATE VAR
uint256 balance ; //inject UNINIT LOCAL/STATE VAR
uint256 monthShare ; //inject UNINIT LOCAL/STATE VAR
uint256 available ; //inject UNINIT LOCAL/STATE VAR
return available;
}
/**
* @dev calculate how much month have gone after end of ICO
*/
function getFullMonthAfterIco () internal view returns (uint256) {
uint256 currentTime ; //inject UNINIT LOCAL/STATE VAR
if (currentTime < endOfIco)
return 0;
else {
uint256 delta ; //inject UNINIT LOCAL/STATE VAR
uint256 step ; //inject UNINIT LOCAL/STATE VAR
if (delta > step) {
uint256 times ; //inject UNINIT LOCAL/STATE VAR
return times;
}
else {
return 0;
}
}
}
/**
* @dev Will set group of addresses that will be under lock. When locked address can't
do some actions with token
* @param _holders array of addresses to lock
* @param _until timestamp until that lock up will last
* @return bool result of operation
*/
function setGroup (address[] memory _holders, uint _until) public onlyOwner returns (bool) {
lockup[groups].holders = _holders;
lockup[groups].until = _until;
groups++;
return true;
}
}
/**
* @dev This contract needed for inheritance of StandardToken interface,
but with freezing modifiers. So, it have exactly same methods, but with
lockupEnded(msg.sender) modifier.
* @notice Inherit from it at ERC20, to make freezing functionality works
*/
contract PausableToken is Freeze {
function transfer(address _to, uint256 _value) public lockupEnded(msg.sender, _to, _value) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public lockupEnded(msg.sender, _to, _value) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public lockupEnded(msg.sender, _spender, _value) returns (bool) {
return super.approve(_spender, _value);
}
function increaseAllowance(address _spender, uint256 _addedValue)
public lockupEnded(msg.sender, _spender, _addedValue) returns (bool success)
{
return super.increaseAllowance(_spender, _addedValue);
}
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public lockupEnded(msg.sender, _spender, _subtractedValue) returns (bool success)
{
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
contract SingleToken is PausableToken {
using SafeMath for uint256;
event TokensBurned(address from, uint256 value);
event TokensMinted(address to, uint256 value);
string public constant name = "Gofind XR";
string public constant symbol = "XR";
uint32 public constant decimals = 8;
uint256 public constant maxSupply = 13E16;
constructor() public {
totalSupply().add(maxSupply);
super._mint(msg.sender, maxSupply);
}
function burn (address account, uint256 value) public onlyOwner returns (bool) {
super._burn(account, value);
return true;
}
function burnFrom (address account, uint256 value) public onlyOwner returns (bool) {
super._burnFrom(account, value);
return true;
}
function mint (address account, uint256 value) public onlyOwner returns (bool) {
super._mint(account, value);
return true;
}
} | * @param _holder address of token holder to check @return bool - status of freezing and group/ | function isFreezed (address _holder) public view returns(bool, uint) {
while (i < groups) {
if (index == 0) {
if (checkZeroIndex(_holder, i)) {
freezed = true;
i++;
continue;
}
else {
i++;
continue;
}
}
if (index != 0) {
freezed = true;
i++;
continue;
}
i++;
}
if (!freezed) i = 0;
return (freezed, i);
}
| 2,503,584 | [
1,
67,
4505,
1758,
434,
1147,
10438,
358,
866,
327,
1426,
300,
1267,
434,
4843,
94,
310,
471,
1041,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
9194,
94,
329,
261,
2867,
389,
4505,
13,
1071,
1476,
1135,
12,
6430,
16,
2254,
13,
288,
203,
203,
203,
3639,
1323,
261,
77,
411,
3252,
13,
288,
203,
203,
203,
5411,
309,
261,
1615,
422,
374,
13,
288,
203,
7734,
309,
261,
1893,
7170,
1016,
24899,
4505,
16,
277,
3719,
288,
203,
10792,
4843,
94,
329,
273,
638,
31,
203,
10792,
277,
9904,
31,
203,
10792,
1324,
31,
203,
7734,
289,
21281,
7734,
469,
288,
203,
10792,
277,
9904,
31,
203,
10792,
1324,
31,
203,
7734,
289,
203,
5411,
289,
7010,
540,
203,
5411,
309,
261,
1615,
480,
374,
13,
288,
203,
7734,
4843,
94,
329,
273,
638,
31,
203,
7734,
277,
9904,
31,
203,
7734,
1324,
31,
203,
5411,
289,
203,
5411,
277,
9904,
31,
203,
3639,
289,
203,
3639,
309,
16051,
9156,
94,
329,
13,
277,
273,
374,
31,
203,
540,
203,
3639,
327,
261,
9156,
94,
329,
16,
277,
1769,
203,
565,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/42/0x171F02BAa6213Dc4aDdb259257b495F8BF42eA59/sources/Pool.sol | member selection duration for round robin, default 60 mins
| uint public selectionDuration = 60 minutes; | 3,481,923 | [
1,
5990,
4421,
3734,
364,
3643,
721,
4757,
16,
805,
4752,
26381,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1071,
4421,
5326,
273,
4752,
6824,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x476556fAb1E5B7111740BFdAfC7c8809118B800f/sources/Token.sol | * @dev Creates `amount` tokens and assigns them to owner, 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 payable account, uint256 amount) internal {
require(!_minted);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| 5,114,599 | [
1,
2729,
1375,
8949,
68,
2430,
471,
22698,
2182,
358,
3410,
16,
21006,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
2080,
68,
444,
358,
326,
3634,
1758,
18,
29076,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
81,
474,
12,
2867,
8843,
429,
2236,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
5,
67,
81,
474,
329,
1769,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1289,
12,
8949,
1769,
203,
3639,
389,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
1289,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x2399e275a35b9562f7fc93869abe9948e7b509bb
//Contract name: SKToken
//Balance: 0 Ether
//Verification Date: 5/14/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns(uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns(uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns(uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract SKToken is Pausable {
using SafeMath for uint256;
string public version = "1.0.0";
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
bool public mintingFinished = false;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Burn(address indexed from, uint256 value);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event FrozenFunds(address indexed target, bool frozen);
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function SKToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
name = tokenName;
symbol = tokenSymbol;
// Update total supply with the decimal amount
totalSupply = initialSupply.mul(10 ** uint256(decimals));
// Give the creator all initial tokens
balanceOf[msg.sender] = totalSupply;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint256 _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if sender is frozen
require(!frozenAccount[_from]);
// Check if recipient is frozen
require(!frozenAccount[_to]);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint256 previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] = balanceOf[_from].sub(_value);
// Add the same to the recipient
balanceOf[_to] = balanceOf[_to].add(_value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
emit Transfer(_from, _to, _value);
}
/**
* 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) whenNotPaused onlyPayloadSize(2*32) public returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused onlyPayloadSize(3*32) public returns (bool success) {
require(!frozenAccount[msg.sender]);
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) whenNotPaused onlyPayloadSize(2*32) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) whenNotPaused onlyPayloadSize(2*32) public returns (bool) {
allowance[msg.sender][_spender] = allowance[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) whenNotPaused onlyPayloadSize(2*32) public returns (bool) {
uint oldValue = allowance[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowance[msg.sender][_spender] = 0;
} else {
allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) whenNotPaused onlyPayloadSize(32) public returns (bool success) {
require(!frozenAccount[msg.sender]);
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) whenNotPaused onlyPayloadSize(2*32) public returns (bool success) {
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_from]);
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Function to mint tokens
* @param target The address that will receive the minted tokens.
* @param mintedAmount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address target, uint256 mintedAmount) onlyOwner canMint onlyPayloadSize(2*32) public returns (bool) {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(address(0), target, mintedAmount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/**
* @dev Function to freeze account
* @param target Address to be frozen.
* @param freeze either to freeze it or not.
* @return A boolean that indicates if the operation was successful.
*/
function freezeAccount(address target, bool freeze) onlyOwner public returns (bool) {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
return true;
}
}
| Check if the targeted balance is enough
| require(balanceOf[_from] >= _value); | 5,449,083 | [
1,
1564,
309,
326,
20715,
11013,
353,
7304,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
12296,
951,
63,
67,
2080,
65,
1545,
389,
1132,
1769,
9079,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x077E10AF63dA2B0459cd9002202dFc4552365605/sources/contracts/PaymentsProcessor.sol | Function to add a new ERC20 token to mapping of available tokens Returns true on success | function addERC20Token(address token_address) public onlyOwner returns (bool) {
require(!available_tokens[token_address].exists, "Token address already exists");
available_tokens[token_address] = TokenData(ERC20(token_address), true);
return true;
}
| 4,837,038 | [
1,
2083,
358,
527,
279,
394,
4232,
39,
3462,
1147,
358,
2874,
434,
2319,
2430,
2860,
638,
603,
2216,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
527,
654,
39,
3462,
1345,
12,
2867,
1147,
67,
2867,
13,
1071,
1338,
5541,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
5,
5699,
67,
7860,
63,
2316,
67,
2867,
8009,
1808,
16,
315,
1345,
1758,
1818,
1704,
8863,
203,
565,
2319,
67,
7860,
63,
2316,
67,
2867,
65,
273,
3155,
751,
12,
654,
39,
3462,
12,
2316,
67,
2867,
3631,
638,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import "./abstract/HasSecondarySaleFees.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract BlueprintV7 is
ERC721Upgradeable,
HasSecondarySaleFees,
AccessControlEnumerableUpgradeable
{
using StringsUpgradeable for uint256;
uint32 public defaultPlatformPrimaryFeePercentage;
uint32 public defaultBlueprintSecondarySalePercentage;
uint32 public defaultPlatformSecondarySalePercentage;
uint64 public latestErc721TokenIndex;
uint256 public blueprintIndex;
address public asyncSaleFeesRecipient;
address public platform;
address public minterAddress;
mapping(uint256 => uint256) tokenToBlueprintID;
mapping(address => uint256) failedTransferCredits;
mapping(uint256 => Blueprints) public blueprints;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
enum SaleState {
not_prepared,
not_started,
started,
paused
}
struct Blueprints {
bool tokenUriLocked;
uint32 mintAmountArtist;
uint32 mintAmountPlatform;
uint64 capacity;
uint64 erc721TokenIndex;
uint64 maxPurchaseAmount;
uint128 price;
address artist;
address ERC20Token;
string baseTokenUri;
bytes32 merkleroot;
SaleState saleState;
uint32[] primaryFeeBPS;
uint32[] secondaryFeeBPS;
address[] primaryFeeRecipients;
address[] secondaryFeeRecipients;
mapping(address => bool) claimedWhitelistedPieces;
}
event BlueprintSeed(uint256 blueprintID, string randomSeed);
event BlueprintMinted(
uint256 blueprintID,
address artist,
address purchaser,
uint128 tokenId,
uint64 newCapacity,
bytes32 seedPrefix
);
event BlueprintPrepared(
uint256 blueprintID,
address artist,
uint64 capacity,
string blueprintMetaData,
string baseTokenUri
);
event BlueprintSettingsUpdated(
uint256 blueprintID,
uint128 price,
uint32 newMintAmountArtist,
uint32 newMintAmountPlatform,
uint32 newSaleState,
uint64 newMaxPurchaseAmount,
bytes32 newMerkleRoot
);
event SaleStarted(uint256 blueprintID);
event SalePaused(uint256 blueprintID);
event SaleUnpaused(uint256 blueprintID);
event BlueprintTokenUriUpdated(uint256 blueprintID, string newBaseTokenUri);
modifier isBlueprintPrepared(uint256 _blueprintID) {
require(
blueprints[_blueprintID].saleState != SaleState.not_prepared,
"blueprint not prepared"
);
_;
}
modifier hasSaleStarted(uint256 _blueprintID) {
require(_hasSaleStarted(_blueprintID), "Sale not started");
_;
}
modifier BuyerWhitelistedOrSaleStarted(
uint256 _blueprintID,
uint32 _quantity,
bytes32[] calldata proof
) {
require(
_hasSaleStarted(_blueprintID) ||
(_isBlueprintPreparedAndNotStarted(_blueprintID) &&
userWhitelisted(_blueprintID, uint256(_quantity), proof)),
"not available to purchase"
);
_;
}
modifier isQuantityAvailableForPurchase(
uint256 _blueprintID,
uint32 _quantity
) {
require(
blueprints[_blueprintID].capacity >= _quantity,
"quantity exceeds capacity"
);
_;
}
///
///Initialize the implementation
///
function initialize(
string memory name_,
string memory symbol_,
address minter
) public initializer {
// Intialize parent contracts
ERC721Upgradeable.__ERC721_init(name_, symbol_);
HasSecondarySaleFees._initialize();
AccessControlUpgradeable.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, minter);
platform = msg.sender;
minterAddress = minter;
defaultPlatformPrimaryFeePercentage = 2000; // 20%
defaultBlueprintSecondarySalePercentage = 750; // 7.5%
defaultPlatformSecondarySalePercentage = 250; // 2.5%
asyncSaleFeesRecipient = msg.sender;
}
function _hasSaleStarted(uint256 _blueprintID)
internal
view
returns (bool)
{
return blueprints[_blueprintID].saleState == SaleState.started;
}
function _isBlueprintPreparedAndNotStarted(uint256 _blueprintID)
internal
view
returns (bool)
{
return blueprints[_blueprintID].saleState == SaleState.not_started;
}
function _getFeePortion(uint256 _totalSaleAmount, uint256 _percentage)
internal
pure
returns (uint256)
{
return (_totalSaleAmount * (_percentage)) / 10000;
}
function userWhitelisted(
uint256 _blueprintID,
uint256 _quantity,
bytes32[] calldata proof
) internal view returns (bool) {
require(proof.length != 0, "no proof provided");
require(
!blueprints[_blueprintID].claimedWhitelistedPieces[msg.sender],
"already claimed"
);
bytes32 _merkleroot = blueprints[_blueprintID].merkleroot;
return _verify(_leaf(msg.sender, _quantity), _merkleroot, proof);
}
function feesApplicable(
address[] memory _feeRecipients,
uint32[] memory _feeBPS
) internal pure returns (bool) {
if (_feeRecipients.length != 0 || _feeBPS.length != 0) {
require(
_feeRecipients.length == _feeBPS.length,
"mismatched recipients & Bps"
);
uint32 totalPercent;
for (uint256 i = 0; i < _feeBPS.length; i++) {
totalPercent = totalPercent + _feeBPS[i];
}
require(totalPercent <= 10000, "Fee Bps exceed maximum");
return true;
}
return false;
}
function setBlueprintPrepared(
uint256 _blueprintID,
string memory _blueprintMetaData
) internal {
blueprints[_blueprintID].saleState = SaleState.not_started;
//assign the erc721 token index to the blueprint
blueprints[_blueprintID].erc721TokenIndex = latestErc721TokenIndex;
uint64 _capacity = blueprints[_blueprintID].capacity;
latestErc721TokenIndex += _capacity;
blueprintIndex++;
emit BlueprintPrepared(
_blueprintID,
blueprints[_blueprintID].artist,
_capacity,
_blueprintMetaData,
blueprints[_blueprintID].baseTokenUri
);
}
function setErc20Token(uint256 _blueprintID, address _erc20Token) internal {
if (_erc20Token != address(0)) {
blueprints[_blueprintID].ERC20Token = _erc20Token;
}
}
function _setupBlueprint(
uint256 _blueprintID,
address _erc20Token,
string memory _baseTokenUri,
bytes32 _merkleroot,
uint32 _mintAmountArtist,
uint32 _mintAmountPlatform,
uint32 _maxPurchaseAmount
) internal {
setErc20Token(_blueprintID, _erc20Token);
blueprints[_blueprintID].baseTokenUri = _baseTokenUri;
if (_merkleroot != 0) {
blueprints[_blueprintID].merkleroot = _merkleroot;
}
blueprints[_blueprintID].mintAmountArtist = _mintAmountArtist;
blueprints[_blueprintID].mintAmountPlatform = _mintAmountPlatform;
if (_maxPurchaseAmount != 0) {
blueprints[_blueprintID].maxPurchaseAmount = _maxPurchaseAmount;
}
}
function prepareBlueprint(
address _artist,
uint64 _capacity,
uint128 _price,
address _erc20Token,
string memory _blueprintMetaData,
string memory _baseTokenUri,
bytes32 _merkleroot,
uint32 _mintAmountArtist,
uint32 _mintAmountPlatform,
uint32 _maxPurchaseAmount
) external onlyRole(MINTER_ROLE) {
uint256 _blueprintID = blueprintIndex;
blueprints[_blueprintID].artist = _artist;
blueprints[_blueprintID].capacity = _capacity;
blueprints[_blueprintID].price = _price;
_setupBlueprint(
_blueprintID,
_erc20Token,
_baseTokenUri,
_merkleroot,
_mintAmountArtist,
_mintAmountPlatform,
_maxPurchaseAmount
);
setBlueprintPrepared(_blueprintID, _blueprintMetaData);
}
function updateBlueprintSettings (
uint256 _blueprintID,
uint128 _price,
uint32 _mintAmountArtist,
uint32 _mintAmountPlatform,
uint32 _newSaleState,
uint64 _newMaxPurchaseAmount,
bytes32 _merkleroot
) external onlyRole(MINTER_ROLE) {
blueprints[_blueprintID].price = _price;
blueprints[_blueprintID].mintAmountArtist = _mintAmountArtist;
blueprints[_blueprintID].mintAmountPlatform = _mintAmountPlatform;
blueprints[_blueprintID].saleState = SaleState (_newSaleState);
blueprints[_blueprintID].merkleroot = _merkleroot;
blueprints[_blueprintID].maxPurchaseAmount = _newMaxPurchaseAmount;
emit BlueprintSettingsUpdated(_blueprintID, _price, _mintAmountArtist, _mintAmountPlatform, _newSaleState, _newMaxPurchaseAmount, _merkleroot);
}
function setFeeRecipients(
uint256 _blueprintID,
address[] memory _primaryFeeRecipients,
uint32[] memory _primaryFeeBPS,
address[] memory _secondaryFeeRecipients,
uint32[] memory _secondaryFeeBPS
) external onlyRole(MINTER_ROLE) {
require(
blueprints[_blueprintID].saleState == SaleState.not_started,
"sale started or not prepared"
);
if (feesApplicable(_primaryFeeRecipients, _primaryFeeBPS)) {
blueprints[_blueprintID]
.primaryFeeRecipients = _primaryFeeRecipients;
blueprints[_blueprintID].primaryFeeBPS = _primaryFeeBPS;
}
if (feesApplicable(_secondaryFeeRecipients, _secondaryFeeBPS)) {
blueprints[_blueprintID]
.secondaryFeeRecipients = _secondaryFeeRecipients;
blueprints[_blueprintID].secondaryFeeBPS = _secondaryFeeBPS;
}
}
function beginSale(uint256 blueprintID) external onlyRole(MINTER_ROLE) {
require(
blueprints[blueprintID].saleState == SaleState.not_started,
"sale started or not prepared"
);
blueprints[blueprintID].saleState = SaleState.started;
emit SaleStarted(blueprintID);
}
function pauseSale(uint256 blueprintID)
external
onlyRole(MINTER_ROLE)
hasSaleStarted(blueprintID)
{
blueprints[blueprintID].saleState = SaleState.paused;
emit SalePaused(blueprintID);
}
function unpauseSale(uint256 blueprintID) external onlyRole(MINTER_ROLE) {
require(
blueprints[blueprintID].saleState == SaleState.paused,
"Sale not paused"
);
blueprints[blueprintID].saleState = SaleState.started;
emit SaleUnpaused(blueprintID);
}
function purchaseBlueprintsTo(
uint256 blueprintID,
uint32 quantity,
uint256 tokenAmount,
bytes32[] calldata proof,
address nftRecipient
)
external
payable
BuyerWhitelistedOrSaleStarted(blueprintID, quantity, proof)
isQuantityAvailableForPurchase(blueprintID, quantity)
{
require(
blueprints[blueprintID].maxPurchaseAmount == 0 ||
quantity <= blueprints[blueprintID].maxPurchaseAmount,
"user cannot buy more than maxPurchaseAmount in single tx"
);
require (tx.origin == msg.sender, "purchase cannot be called from another contract");
address _artist = blueprints[blueprintID].artist;
_confirmPaymentAmountAndSettleSale(
blueprintID,
quantity,
tokenAmount,
_artist
);
if (blueprints[blueprintID].saleState == SaleState.not_started) {
blueprints[blueprintID].claimedWhitelistedPieces[msg.sender] = true;
}
_mintQuantity(blueprintID, quantity, nftRecipient);
}
function purchaseBlueprints(
uint256 blueprintID,
uint32 quantity,
uint256 tokenAmount,
bytes32[] calldata proof
)
external
payable
BuyerWhitelistedOrSaleStarted(blueprintID, quantity, proof)
isQuantityAvailableForPurchase(blueprintID, quantity)
{
require(
blueprints[blueprintID].maxPurchaseAmount == 0 ||
quantity <= blueprints[blueprintID].maxPurchaseAmount,
"user cannot buy more than maxPurchaseAmount in single tx"
);
require (tx.origin == msg.sender, "purchase cannot be called from another contract");
address _artist = blueprints[blueprintID].artist;
_confirmPaymentAmountAndSettleSale(
blueprintID,
quantity,
tokenAmount,
_artist
);
if (blueprints[blueprintID].saleState == SaleState.not_started) {
blueprints[blueprintID].claimedWhitelistedPieces[msg.sender] = true;
}
_mintQuantity(blueprintID, quantity, msg.sender);
}
function preSaleMint(uint256 blueprintID, uint32 quantity) external {
require(
_isBlueprintPreparedAndNotStarted(blueprintID),
"Must be prepared and not started"
);
require(
minterAddress == msg.sender ||
blueprints[blueprintID].artist == msg.sender,
"user cannot mint presale"
);
if (minterAddress == msg.sender) {
require(
quantity <= blueprints[blueprintID].mintAmountPlatform,
"cannot mint quantity"
);
blueprints[blueprintID].mintAmountPlatform -= quantity;
} else if (blueprints[blueprintID].artist == msg.sender) {
require(
quantity <= blueprints[blueprintID].mintAmountArtist,
"cannot mint quantity"
);
blueprints[blueprintID].mintAmountArtist -= quantity;
}
_mintQuantity(blueprintID, quantity, msg.sender);
}
/*
* Iterate and mint each blueprint for user
*/
function _mintQuantity(uint256 _blueprintID, uint32 _quantity, address _nftRecipient) private {
uint128 newTokenId = blueprints[_blueprintID].erc721TokenIndex;
uint64 newCap = blueprints[_blueprintID].capacity;
for (uint16 i = 0; i < _quantity; i++) {
require(newCap > 0, "blueprint out of capacity");
_mint(_nftRecipient, newTokenId + i);
tokenToBlueprintID[newTokenId + i] = _blueprintID;
bytes32 prefixHash = keccak256(
abi.encodePacked(
block.number,
block.timestamp,
block.coinbase,
newCap
)
);
emit BlueprintMinted(
_blueprintID,
blueprints[_blueprintID].artist,
_nftRecipient,
newTokenId + i,
newCap,
prefixHash
);
--newCap;
}
blueprints[_blueprintID].erc721TokenIndex += _quantity;
blueprints[_blueprintID].capacity = newCap;
}
function _confirmPaymentAmountAndSettleSale(
uint256 _blueprintID,
uint32 _quantity,
uint256 _tokenAmount,
address _artist
) internal {
address _erc20Token = blueprints[_blueprintID].ERC20Token;
uint128 _price = blueprints[_blueprintID].price;
if (_erc20Token == address(0)) {
require(_tokenAmount == 0, "cannot specify token amount");
require(
msg.value == _quantity * _price,
"Purchase amount must match price"
);
_payFeesAndArtist(_blueprintID, _erc20Token, msg.value, _artist);
} else {
require(msg.value == 0, "cannot specify eth amount");
require(
_tokenAmount == _quantity * _price,
"Purchase amount must match price"
);
IERC20(_erc20Token).transferFrom(
msg.sender,
address(this),
_tokenAmount
);
_payFeesAndArtist(_blueprintID, _erc20Token, _tokenAmount, _artist);
}
}
////////////////////////////////////
////// MERKLEROOT FUNCTIONS ////////
////////////////////////////////////
/**
* Create a merkle tree with address: quantity pairs as the leaves.
* The msg.sender will be verified if it has a corresponding quantity value in the merkletree
*/
function _leaf(address account, uint256 quantity)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account, quantity));
}
function _verify(
bytes32 leaf,
bytes32 merkleroot,
bytes32[] memory proof
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleroot, leaf);
}
////////////////////////////
/// ONLY ADMIN functions ///
////////////////////////////
function updateBlueprintTokenUri(
uint256 blueprintID,
string memory newBaseTokenUri
) external onlyRole(MINTER_ROLE) isBlueprintPrepared(blueprintID) {
require(
!blueprints[blueprintID].tokenUriLocked,
"blueprint URI locked"
);
blueprints[blueprintID].baseTokenUri = newBaseTokenUri;
emit BlueprintTokenUriUpdated(blueprintID, newBaseTokenUri);
}
function lockBlueprintTokenUri(uint256 blueprintID)
external
onlyRole(DEFAULT_ADMIN_ROLE)
isBlueprintPrepared(blueprintID)
{
require(
!blueprints[blueprintID].tokenUriLocked,
"blueprint URI locked"
);
blueprints[blueprintID].tokenUriLocked = true;
}
function _baseURIForBlueprint(uint256 tokenId) internal view returns (string memory) {
return blueprints[tokenToBlueprintID[tokenId]].baseTokenUri;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURIForBlueprint(tokenId);
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(
baseURI,
"/",
tokenId.toString(),
"/",
"token.json"
)
)
: "";
}
function revealBlueprintSeed(uint256 blueprintID, string memory randomSeed)
external
onlyRole(MINTER_ROLE)
isBlueprintPrepared(blueprintID)
{
emit BlueprintSeed(blueprintID, randomSeed);
}
function setAsyncFeeRecipient(address _asyncSaleFeesRecipient)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
asyncSaleFeesRecipient = _asyncSaleFeesRecipient;
}
function changeDefaultPlatformPrimaryFeePercentage(uint32 _basisPoints)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_basisPoints <= 10000);
defaultPlatformPrimaryFeePercentage = _basisPoints;
}
function changeDefaultBlueprintSecondarySalePercentage(uint32 _basisPoints)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_basisPoints + defaultPlatformSecondarySalePercentage <= 10000);
defaultBlueprintSecondarySalePercentage = _basisPoints;
}
function changeDefaultPlatformSecondarySalePercentage(uint32 _basisPoints)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
_basisPoints + defaultBlueprintSecondarySalePercentage <= 10000
);
defaultPlatformSecondarySalePercentage = _basisPoints;
}
function updatePlatformAddress(address _platform)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(DEFAULT_ADMIN_ROLE, _platform);
revokeRole(DEFAULT_ADMIN_ROLE, platform);
platform = _platform;
}
// Allows the platform to change the minter address
function updateMinterAddress(address newMinterAddress)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(MINTER_ROLE, newMinterAddress);
revokeRole(MINTER_ROLE, minterAddress);
minterAddress = newMinterAddress;
}
////////////////////////////////////
/// Secondary Fees implementation //
////////////////////////////////////
function _payFeesAndArtist(
uint256 _blueprintID,
address _erc20Token,
uint256 _amount,
address _artist
) internal {
address[] memory _primaryFeeRecipients = getPrimaryFeeRecipients(
_blueprintID
);
uint32[] memory _primaryFeeBPS = getPrimaryFeeBps(_blueprintID);
uint256 feesPaid;
for (uint256 i = 0; i < _primaryFeeRecipients.length; i++) {
uint256 fee = _getFeePortion(_amount, _primaryFeeBPS[i]);
feesPaid = feesPaid + fee;
_payout(_primaryFeeRecipients[i], _erc20Token, fee);
}
if (_amount - feesPaid > 0) {
_payout(_artist, _erc20Token, (_amount - feesPaid));
}
}
function _payout(
address _recipient,
address _erc20Token,
uint256 _amount
) internal {
if (_erc20Token != address(0)) {
IERC20(_erc20Token).transfer(_recipient, _amount);
} else {
// attempt to send the funds to the recipient
(bool success, ) = payable(_recipient).call{
value: _amount,
gas: 20000
}("");
// if it failed, update their credit balance so they can pull it later
if (!success) {
failedTransferCredits[_recipient] =
failedTransferCredits[_recipient] +
_amount;
}
}
}
function withdrawAllFailedCredits(address payable recipient) external {
uint256 amount = failedTransferCredits[msg.sender];
require(amount != 0, "no credits to withdraw");
failedTransferCredits[msg.sender] = 0;
(bool successfulWithdraw, ) = recipient.call{value: amount, gas: 20000}(
""
);
require(successfulWithdraw, "withdraw failed");
}
function getPrimaryFeeRecipients(uint256 id)
public
view
returns (address[] memory)
{
if (blueprints[id].primaryFeeRecipients.length == 0) {
address[] memory primaryFeeRecipients = new address[](1);
primaryFeeRecipients[0] = (asyncSaleFeesRecipient);
return primaryFeeRecipients;
} else {
return blueprints[id].primaryFeeRecipients;
}
}
function getPrimaryFeeBps(uint256 id)
public
view
returns (uint32[] memory)
{
if (blueprints[id].primaryFeeBPS.length == 0) {
uint32[] memory primaryFeeBPS = new uint32[](1);
primaryFeeBPS[0] = defaultPlatformPrimaryFeePercentage;
return primaryFeeBPS;
} else {
return blueprints[id].primaryFeeBPS;
}
}
function getFeeRecipients(uint256 id)
public
view
override
returns (address[] memory)
{
if (blueprints[id].secondaryFeeRecipients.length == 0) {
address[] memory feeRecipients = new address[](2);
feeRecipients[0] = (asyncSaleFeesRecipient);
feeRecipients[1] = (blueprints[id].artist);
return feeRecipients;
} else {
return blueprints[id].secondaryFeeRecipients;
}
}
function getFeeBps(uint256 id)
public
view
override
returns (uint32[] memory)
{
if (blueprints[id].secondaryFeeBPS.length == 0) {
uint32[] memory feeBPS = new uint32[](2);
feeBPS[0] = defaultPlatformSecondarySalePercentage;
feeBPS[1] = defaultBlueprintSecondarySalePercentage;
return feeBPS;
} else {
return blueprints[id].secondaryFeeBPS;
}
}
////////////////////////////////////
/// Required function overide //////
////////////////////////////////////
function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
return
super.isApprovedForAll(account, operator) ||
hasRole(DEFAULT_ADMIN_ROLE, operator);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(
ERC721Upgradeable,
ERC165StorageUpgradeable,
AccessControlEnumerableUpgradeable
)
returns (bool)
{
return
ERC721Upgradeable.supportsInterface(interfaceId) ||
ERC165StorageUpgradeable.supportsInterface(interfaceId) ||
AccessControlEnumerableUpgradeable.supportsInterface(interfaceId);
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol";
abstract contract HasSecondarySaleFees is ERC165StorageUpgradeable {
event SecondarySaleFees(
uint256 tokenId,
address[] recipients,
uint256[] bps
);
/*
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
*
* => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;
function _initialize() public initializer {
_registerInterface(_INTERFACE_ID_FEES);
}
function getFeeRecipients(uint256 id)
public
view
virtual
returns (address[] memory);
function getFeeBps(uint256 id)
public
view
virtual
returns (uint32[] memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
}
// 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/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165Storage.sol)
pragma solidity ^0.8.0;
import "./ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Storage based implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable {
function __ERC165Storage_init() internal initializer {
__ERC165_init_unchained();
__ERC165Storage_init_unchained();
}
function __ERC165Storage_init_unchained() internal initializer {
}
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
// 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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
} | * @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;
}
uint256[49] private __gap;
| 62,589 | [
1,
10277,
326,
6835,
487,
392,
2348,
264,
434,
326,
1560,
2553,
635,
1375,
5831,
548,
8338,
13619,
434,
326,
3214,
4232,
39,
28275,
1560,
353,
5859,
471,
22845,
2097,
1560,
612,
353,
486,
1931,
18,
2164,
288,
45,
654,
39,
28275,
17,
28064,
1358,
5496,
29076,
30,
300,
1375,
5831,
548,
68,
2780,
506,
326,
4232,
39,
28275,
2057,
1560,
21863,
20,
28857,
68,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4861,
1358,
12,
3890,
24,
1560,
548,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
5831,
548,
480,
374,
28857,
16,
315,
654,
39,
28275,
30,
2057,
1560,
612,
8863,
203,
3639,
389,
4127,
10273,
63,
5831,
548,
65,
273,
638,
31,
203,
565,
289,
203,
565,
2254,
5034,
63,
7616,
65,
3238,
1001,
14048,
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
] |
./full_match/80001/0xF120b7f6d7D9E57A905FFe5D6d6d92bd0cbDE0a8/sources/project_/con2/SyntheticToken/MintableBurnableERC20.sol | * @notice Self renounce the address calling the function from admin role/ | function renounceAdmin() public virtual override {
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| 5,619,820 | [
1,
10084,
1654,
8386,
326,
1758,
4440,
326,
445,
628,
3981,
2478,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1654,
8386,
4446,
1435,
1071,
5024,
3849,
288,
203,
3639,
1654,
8386,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./TradeableERC721Token.sol";
/**
* @title ClockAuction
* ClockAuction - a contract for my non-fungible creatures.
*/
contract ClockAuction is ERC721Tradable{
uint256 public constant maxSupply = 6400;
uint256 public constant MAX_PREMINT = 64;
uint256 public constant maxPerAddr = 16;
uint256 public minPrice = 40000000000000000;
uint256 public maxPrice = 129000000000000000;
uint256 public premintCount;
uint256 public maxPresaleSupply = 2000;
uint256 public maxPerPresale = 2;
uint256 public maxPerTxn = 8;
uint256 public auctionEnds;
uint256 public reclaimEnds;
address private constant _adminSigner = 0x7F668e4597B6DA8256C67AB80100b2474266735F;
address payable public treasury = payable(0x90BB2FBC33600277C5184816D32230d6279daF28);
address payable public technician = payable(0xeCA7676e3D770B8EFe6BB66f8AbC920Da23A621c);
bool public yeeYee;
bool public auctionLive;
bool public reclaimLive;
bool public uriFrozen;
bool public saleNumFrozen;
bool public limitFrozen;
struct Bid {
uint256 numTokens; // number of desired tokens
uint256 totalBid; // total bid price
bool won;
bool claimed; // indicator if the user has claimed against their bid
}
mapping(address => Bid) public bids;
mapping(address => uint256) private addrMintCount;
mapping(bytes32 => bool) public signatureUsed;
event Bidder(address user);
event SaleMode(bool publicOn);
event SupplyCount(uint256 supplyCount);
string private metadataURL = "https://sejb7xxndg.execute-api.us-west-1.amazonaws.com/api/metadata/";
constructor(address _proxyRegistryAddress) ERC721Tradable("enclock", "CLCK", _proxyRegistryAddress) { }
/**
* @dev Override the baseTokenURI to return the metadata
*/
function baseTokenURI() override public view returns (string memory) {
return metadataURL;
}
/**
* @dev Set new base URL to return the metadata
* @param _metadataURL str of the new metadataURL
* @param _freeze boolean whether or not to freeze the baseTokenURI
*/
function setBaseTokenURI(string calldata _metadataURL, bool _freeze) external onlyOwner {
require(!uriFrozen, "Metadata URL frozen");
metadataURL = _metadataURL;
uriFrozen = _freeze;
}
// auction functions
/**
* @dev Submit bid
* @param _numTokens uint256 number of tokens to bid on
*/
function submitBid(uint256 _numTokens) payable external {
require(auctionLive, "Not live yet");
require(block.timestamp <= auctionEnds, "Auction ended");
require(_numTokens <= maxPerTxn, "Exceeds limit");
require(0 < _numTokens, "Min. 1 token");
Bid storage userBid = bids[msg.sender];
uint256 newTotal = userBid.totalBid + msg.value;
require(minPrice <= (newTotal / _numTokens), "Below min. bid");
require((newTotal / _numTokens) <= maxPrice, "Exceeds max bid");
if (userBid.numTokens == 0){
emit Bidder(msg.sender);
}
userBid.totalBid = newTotal;
userBid.numTokens = _numTokens;
}
/**
* @dev Assign winners
* @param _winners address[] winning addresses
*/
function assignWinners(address[] calldata _winners) external onlyOwner {
for (uint256 i = 0; i < _winners.length; i++){
bids[_winners[i]].won = true;
}
}
/**
* @dev Winners claim their tokens
*/
function claimTokens() external {
Bid storage bid = bids[msg.sender];
require(bid.won, "Not a winner");
require(!bid.claimed, "Already claimed");
bid.claimed = true;
uint256 ts = totalSupply();
for (uint256 i = 0; i < bid.numTokens; i++){
_safeMint(msg.sender, ts++);
}
}
/**
* @dev Reclaim losing bids
*/
function reclaim() external {
Bid storage bid = bids[msg.sender];
require(reclaimLive, "Cannot reclaim yet");
require(!bid.won, "Winners cannot reclaim");
require(!bid.claimed, "Already claimed");
bid.claimed = true;
payable(msg.sender).transfer(bid.totalBid);
}
// minting functions
/**
* @dev Creator's preminting function
* @param _to address of where the premint will go
*/
function creatorMint(address _to, uint256 amount) external onlyOwner {
premintCount += amount;
require(premintCount <= MAX_PREMINT, "No premints left");
uint256 ts = totalSupply();
for (uint256 i = 0; i < amount; i++){
_safeMint(_to, ts++);
}
}
/**
* @dev whitelist minting
* @param amount number of tokens to mint
* @param _hash bytes32 message hash from a signed message
* @param _r bytes32 from a signed message (first 32 bytes of signature)
* @param _s bytes32 from a signed message (second 32 bytes of a signature)
* @param _v uint8 from a signed message (final bytes of signature)
*/
function whitelistMint(uint256 amount, bytes32 _hash, bytes32 _r, bytes32 _s, uint8 _v) payable external {
require(0 < amount, "Cannot mint 0");
require(minPrice * amount <= msg.value, "Not enough ether");
require(amount <= maxPerPresale, "Minting beyond wallet limit");
address signer = ecrecover(_hash, _v, _r, _s);
require(signer == _adminSigner, "Forged signature");
require(!signatureUsed[_hash], "Signature already used");
signatureUsed[_hash] = true;
uint256 ts = totalSupply();
require(ts + amount <= maxPresaleSupply, "Beyond presale limit");
for (uint256 i = 0; i < amount; i++){
_safeMint(msg.sender, ts++);
}
emit SupplyCount(totalSupply());
}
/**
* @dev YEEYUH
* must be live
* cannot exceed txn limits
* must be within wallet allowance
* must not exceed max maxSupply
* @param amount uint256 number of clocks to mint
*/
function yeeYeeMint(uint256 amount) payable external {
require(yeeYee, "Not active yet");
require(amount <= maxPerTxn, "Exceeds limit");
require(minPrice * amount <= msg.value, "Not enough ether");
require(addrMintCount[msg.sender] + amount <= maxPerAddr, "Minting beyond wallet limit");
uint256 ts = totalSupply();
require(ts + amount <= maxSupply, "Not enough left to mint");
addrMintCount[msg.sender] += amount;
for (uint256 i = 0; i < amount; i++){
_safeMint(msg.sender, ts++);
}
emit SupplyCount(totalSupply());
}
// --------------------
// phase toggling:
// --------------------
/**
* @dev public launch
*/
function setPublicLive() external onlyOwner {
yeeYee = true;
emit SaleMode(yeeYee);
}
/**
* @dev Auction launch
* @param _auctionEnds uint256 timestamp (seconds) of when the auction ends
*/
function setAuctionLive(uint256 _auctionEnds) external onlyOwner {
auctionLive = true;
auctionEnds = _auctionEnds;
}
/**
* @dev Enable reclaim
* @param _reclaimEnds uint256 timestamp (seconds) of when reclaim is over
* @param _reclaimLive bool whether or not reclaim is live
*/
function setReclaimLive(uint256 _reclaimEnds, bool _reclaimLive) external onlyOwner {
reclaimEnds = _reclaimEnds;
reclaimLive = _reclaimLive;
}
// --------------------
// sale configuration:
// --------------------
/**
* @dev Set sale numbers
* @param _minPrice uint256 the minimum price for whitelist, FCFS, or auction
* @param _maxPrice uint256 the maximumm price for auctions
* @param _freeze bool whether or not these numbers are changeable afterwards
*/
function setSaleNumbers(uint256 _minPrice, uint256 _maxPrice, bool _freeze) external onlyOwner {
require(!saleNumFrozen, "Numbers Frozen");
minPrice = _minPrice;
maxPrice = _maxPrice;
saleNumFrozen = _freeze;
}
/**
* @dev Set limits for minting
* @param _maxPerPresale uint256 maximum amount of tokens for presale per address
* @param _maxPerTxn uint256 maximum amount of tokens for FCFS / auction bids
* @param _maxPresaleSupply uint256 global maximum amount of presale tokens
* @param _freeze bool whether or not these numbers are changeable afterwards
*/
function setLimits(uint256 _maxPerPresale, uint256 _maxPerTxn, uint256 _maxPresaleSupply, bool _freeze) external onlyOwner {
require(!limitFrozen, "Numbers Frozen");
maxPerPresale = _maxPerPresale;
maxPerTxn = _maxPerTxn;
maxPresaleSupply = _maxPresaleSupply;
limitFrozen = _freeze;
}
// --------------------
// treasury stuff:
// --------------------
/**
* @dev Set the treasury address for withdrawing proceeds
* @param _treasury address, the treasury
* @param _technician address, the technician's addrress
*/
function setWithdrawAddresses(address payable _treasury, address payable _technician) external onlyOwner {
treasury = _treasury;
technician = _technician;
}
/**
* @dev Withdraw to the treasury and technician
*/
function withdraw() external onlyOwner{
require(reclaimLive, "Reclaim must be enabled");
require(reclaimEnds <= block.timestamp, "Cannot withdraw before reclaim period");
require(technician != address(0x0), "technician cannot be 0x0");
require(treasury != address(0x0), "treasury cannot be 0x0");
technician.transfer(address(this).balance / 4);
treasury.transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
//import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./ClockERC721Enumerable.sol";
import "./ContentMixin.sol";
import "./NativeMetaTransaction.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
abstract contract ERC721Tradable is ContextMixin, ClockERC721Enumerable, NativeMetaTransaction, Ownable{
using SafeMath for uint256;
address proxyRegistryAddress;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
function baseTokenURI() virtual public view returns (string memory);
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {EIP712Base} from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import {Initializable} from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ClockERC721Enumerable is ERC721, IERC721Enumerable {
uint256 private _total;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
/**
* @dev 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 _total;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return 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 {
if (from == address(0)) {
_total++;
} else {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
_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].push(tokenId);
_ownedTokensIndex[tokenId] = length;
}
/**
* @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];
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];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | -------------------- phase toggling: --------------------* @dev public launch/ | function setPublicLive() external onlyOwner {
yeeYee = true;
emit SaleMode(yeeYee);
}
| 5,988,050 | [
1,
1271,
553,
6855,
6316,
75,
2456,
30,
12146,
6062,
225,
1071,
8037,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
27467,
12328,
1435,
3903,
1338,
5541,
288,
203,
3639,
677,
1340,
61,
1340,
273,
638,
31,
203,
3639,
3626,
348,
5349,
2309,
12,
93,
1340,
61,
1340,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xEe9c34E6D0A835BbB4dF1Db902D6F1B923481fC3/sources/browser/XDef.sol | * @dev Decrease the amount of tokens that an owner has allowed to a spender. @param spender The address which will spend the funds. @param subtractedValue The amount of tokens to decrease the allowance by./ | function decreaseAllowance(address spender, uint256 subtractedValue)
public
override
returns (bool)
{
require(
!transfersPaused || transferPauseExemptList[msg.sender],
"paused"
);
uint256 oldValue = _allowedXdef[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedXdef[msg.sender][spender] = 0;
_allowedXdef[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedXdef[msg.sender][spender]);
return true;
}
| 8,449,930 | [
1,
23326,
448,
326,
3844,
434,
2430,
716,
392,
3410,
711,
2935,
358,
279,
17571,
264,
18,
225,
17571,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
225,
10418,
329,
620,
1021,
3844,
434,
2430,
358,
20467,
326,
1699,
1359,
635,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
10418,
329,
620,
13,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
401,
2338,
18881,
28590,
747,
7412,
19205,
424,
5744,
682,
63,
3576,
18,
15330,
6487,
203,
5411,
315,
8774,
3668,
6,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
11144,
273,
389,
8151,
60,
536,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
15533,
203,
3639,
309,
261,
1717,
1575,
329,
620,
1545,
11144,
13,
288,
203,
5411,
389,
8151,
60,
536,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
374,
31,
203,
5411,
389,
8151,
60,
536,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
11144,
18,
1717,
12,
1717,
1575,
329,
620,
1769,
203,
3639,
289,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
389,
8151,
60,
536,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
19226,
203,
3639,
327,
638,
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
] |
pragma solidity ^0.5.0;
// AggregatorInterface specifies ChainLink aggregator interface.
import "./AggregatorInterface.sol";
// ChainLinkPriceReferenceAggregator implements aggregation for set of ChainLink
// reference price oracles redirecting price requests to their target price
// oracle based on the denomination address.
contract ChainLinkPriceReferenceAggregator {
// TokenInformation represents a single token handled by the reference aggregator.
// The De-Fi API uses this reference to do on-chain tokens tracking.
struct TokenInformation {
address addr; // address of the token (unique identifier)
bytes32 name; // Name fo the token
bytes32 symbol; // symbol of the token
string logo; // URL address of the token logo
uint decimals; // number of decimals the token's price oracle uses
bool isActive; // is this token active in DeFi?
bool canDeposit; // is this token available for deposit?
bool canBorrow; // is this token available for fLend?
bool canTrade; // is this token available for direct fTrade?
uint volatility; // what is the index of volatility of the token in 8 decimals
}
// owner represents the manager address of the oracle aggregator.
address public owner;
// ChainLink aggregator interface references by denomination.
// The left side is the token identifier, the right side
// is the ChainLink aggregator address.
mapping(address => AggregatorInterface) public aggregators;
// tokens is the list of tokens handled by the DeFi reference aggregator.
TokenInformation[] public tokens;
// AggregatorChanged event is emitted when a new price oracle aggregator is set for a token.
event AggregatorChanged(address indexed token, address aggregator, uint timestamp);
// TokenInformationAdded event is emitted when a new token information is added to the contract.
event TokenInformationAdded(address indexed token, uint index, bytes32 name, uint timestamp);
// TokenInformationUpdated event is emitted when an existing token information is updated.
event TokenInformationChanged(address indexed token, uint index, uint timestamp);
// install new aggregator instance
constructor() public {
// remember the manager address
owner = msg.sender;
}
// -----------------------------------------------
// aggregators per token address management
// -----------------------------------------------
// setAggregator sets a new aggregator reference for the given token.
function setAggregator(address token, address aggregator) external {
// only owner can make the change
require(msg.sender == owner, "access restricted");
// make the change
aggregators[token] = AggregatorInterface(aggregator);
// emit notification to express the change
emit AggregatorChanged(token, aggregator, now);
}
// -----------------------------------------------
// current price and time stamp
// -----------------------------------------------
// getPrice returns the latest price available for the token specified.
function getPrice(address token) public view returns (int256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer from the aggregator of the given token
return aggregators[token].latestAnswer();
}
// getTimeStamp returns the time stamp the latest price was made available
// by the ChainLink aggregator oracle for the token specified.
function getTimeStamp(address token) public view returns (uint256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer from the aggregator of the given token
return aggregators[token].latestTimestamp();
}
// -----------------------------------------------
// prices and time stamps history
// -----------------------------------------------
// getPreviousPrice returns the price available for the token specified
// from the ChainLink aggregator oracle <_back> update cycles before the most recent one.
function getPreviousPrice(address token, uint256 _back) public view returns (int256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer round from the aggregator of the given token
// we make sure the requested round is valid
uint256 latest = aggregators[token].latestRound();
require(_back <= latest, "not enough history");
// get the price back then
return aggregators[token].getAnswer(latest - _back);
}
// getTimeStamp returns the time stamp the price was made available
// by the ChainLink aggregator oracle <_back> update cycles before the most recent one.
function getPreviousTimeStamp(address token, uint256 _back) public view returns (uint256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer round from the aggregator of the given token
// we make sure the requested round is valid
uint256 latest = aggregators[token].latestRound();
require(_back <= latest, "not enough history");
// get the time stamp back then
return aggregators[token].getTimestamp(latest - _back);
}
// -----------------------------------------------
// tokens registry related functions below this
// -----------------------------------------------
// tokensCount returns the total number of tokens' details in the registry.
function tokensCount() public view returns (uint256) {
return tokens.length;
}
// findTokenIndex finds an index of a token in the tokens list by address; returns -1 if not found.
function findTokenIndex(address _addr) public view returns (int256) {
// loop the list and try to find the token
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i].addr == _addr) {
return int256(i);
}
}
return - 1;
}
// addToken adds new token into the reference contract.
function addToken(
address _addr,
address _aggregator,
bytes32 _name,
bytes32 _symbol,
string calldata _logo,
uint _decimals,
bool _isActive,
bool _canDeposit,
bool _canBorrow,
bool _canTrade,
uint _volatility
) external {
// make sure only owner can do this
require(msg.sender == owner, "access restricted");
// try to find the address
require(0 > findTokenIndex(_addr), "token already known");
// set the price aggregator
aggregators[_addr] = AggregatorInterface(_aggregator);
emit AggregatorChanged(_addr, _aggregator, now);
// add the token to the list
tokens.push(TokenInformation({
addr : _addr,
name : _name,
symbol : _symbol,
logo: _logo,
decimals : _decimals,
isActive : _isActive,
canDeposit : _canDeposit,
canBorrow : _canBorrow,
canTrade : _canTrade,
volatility : _volatility
})
);
// inform
emit TokenInformationAdded(_addr, tokens.length - 1, _name, now);
}
// updateToken modifies existing token in the reference contract.
function updateToken(
address _addr,
string calldata _logo,
uint _decimals,
bool _isActive,
bool _canDeposit,
bool _canBorrow,
bool _canTrade,
uint _volatility
) external {
// make sure only owner can do this
require(msg.sender == owner, "access restricted");
// try to find the address in the tokens list
int256 ix = findTokenIndex(_addr);
require(0 <= ix, "token not known");
// update token details in the contract
tokens[uint256(ix)].logo = _logo;
tokens[uint256(ix)].decimals = _decimals;
tokens[uint256(ix)].isActive = _isActive;
tokens[uint256(ix)].canDeposit = _canDeposit;
tokens[uint256(ix)].canBorrow = _canBorrow;
tokens[uint256(ix)].canTrade = _canTrade;
tokens[uint256(ix)].volatility = _volatility;
// inform
emit TokenInformationChanged(_addr, uint256(ix), now);
}
}
| address of the token (unique identifier)
| address addr; | 1,060,170 | [
1,
2867,
434,
326,
1147,
261,
6270,
2756,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1758,
3091,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
// * Samurai Quest - Levelling game that pay ether. Version 1.
//
// * Developer - Studio California
// "You can check out any time you like, but you can never leave"
//
// * Uses Linked List to store player level
//
// * Refer to https://samurai-quest.hostedwiki.co/ for detailed description.
contract SamuraiQuest {
using SafeMath for uint256;
using LinkedListLib for LinkedListLib.LinkedList;
// ***Event Section
event NewSamuraiIncoming(uint256 id, bytes32 name);
event TheLastSamuraiBorn(uint256 id, bytes32 name, uint256 winning);
event Retreat(uint256 id, bytes32 name, uint256 balance);
address public owner;
uint256 public currentSamuraiId;
uint256 public totalProcessingFee;
uint256 public theLastSamuraiPot;
uint256 public theLastSamuraiEndTime;
// ***Constant Section
uint256 private constant MAX_LEVEL = 8;
uint256 private constant JOINING_FEE = 0.03 ether;
uint256 private constant PROCESSING_FEE = 0.001 ether;
uint256 private constant REFERRAL_FEE = 0.002 ether;
uint256 private constant THE_LAST_SAMURAI_FEE = 0.002 ether;
uint256 private constant THE_LAST_SAMURAI_COOLDOWN = 1 days;
struct Samurai {
uint256 level;
uint256 supporterWallet;
uint256 referralWallet;
uint256 theLastSamuraiWallet;
bytes32 name;
address addr;
bool isRetreat;
bool autoLevelUp;
}
mapping (address => uint256) public addressToId;
mapping (uint256 => Samurai) public idToSamurai;
mapping (uint256 => uint256) public idToSamuraiHeadId;
mapping (uint256 => uint256) public idToAffiliateId;
mapping (uint256 => uint256) public supporterCount;
mapping (uint256 => uint256) public referralCount;
mapping (uint256 => LinkedListLib.LinkedList) private levelChain; // level up chain
uint256[9] public levelUpFee; // level up fees
// Constructor. Deliberately does not take any parameters.
constructor() public {
// Set the contract owner
owner = msg.sender;
totalProcessingFee = 0;
theLastSamuraiPot = 0;
currentSamuraiId = 1;
// Level up fee
levelUpFee[1] = 0.02 ether; // 0 > 1
levelUpFee[2] = 0.04 ether; // 1 > 2
levelUpFee[3] = 0.08 ether; // 2 > 3
levelUpFee[4] = 0.16 ether; // 3 > 4
levelUpFee[5] = 0.32 ether; // 4 > 5
levelUpFee[6] = 0.64 ether; // 5 > 6
levelUpFee[7] = 1.28 ether; // 6 > 7
levelUpFee[8] = 2.56 ether; // 7 > 8
}
modifier onlyOwner() {
require(msg.sender == owner, "OnlyOwner method called by non owner");
_;
}
// Fund withdrawal to cover costs of operation
function withdrawProcessingFee() public onlyOwner {
require(totalProcessingFee <= address(this).balance, "not enough fund");
uint256 amount = totalProcessingFee;
totalProcessingFee = 0;
owner.transfer(amount);
}
// Fallback function deliberately left empty.
function () public payable { }
/// *** join Logic
// Set the samurai info and level to 0, then level up it
// _name - Name of the samurai
// _affiliateId - Affiliate Id, affiliate will get 0.002ETH of each action
// performed by it's referral
// _autoLevelUp - Let player control the level up type
function join(bytes32 _name, uint256 _affiliateId, bool _autoLevelUp) public payable {
require(msg.value == JOINING_FEE, "you have no enough courage");
require(addressToId[msg.sender] == 0, "you're already in");
require(_affiliateId >= 0 && _affiliateId < currentSamuraiId, "invalid affiliate");
Samurai storage samurai = idToSamurai[currentSamuraiId];
samurai.level = 0;
samurai.addr = msg.sender;
samurai.referralWallet = 0;
samurai.theLastSamuraiWallet = 0;
samurai.name = _name;
samurai.isRetreat = false;
samurai.autoLevelUp = _autoLevelUp;
samurai.supporterWallet = JOINING_FEE;
addressToId[msg.sender] = currentSamuraiId;
if (_affiliateId > 0) {
idToAffiliateId[currentSamuraiId] = _affiliateId;
referralCount[_affiliateId] = referralCount[_affiliateId].add(1);
}
levelUp(currentSamuraiId);
emit NewSamuraiIncoming(currentSamuraiId, samurai.name);
// Increase the count for next samurai
currentSamuraiId = currentSamuraiId.add(1);
theLastSamuraiEndTime = now.add(THE_LAST_SAMURAI_COOLDOWN);
}
/// *** levelUp Logic
// Level up the samurai, push it to the next level chain
// Help checking the last samurai pot
// Distribute the fund to corresponding accounts
// Help levelling up the head of samurai
// _samuraiId - Id of the samurai to be levelled up
function levelUp(uint256 _samuraiId) public {
bool exist;
uint256 samuraiHeadId;
Samurai storage samurai = idToSamurai[_samuraiId];
require(canLevelUp(_samuraiId), "cannot level up");
uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet);
require(
balance >= levelUpFee[samurai.level.add(1)].add(PROCESSING_FEE).add(THE_LAST_SAMURAI_FEE).add(REFERRAL_FEE),
"not enough fund to level up"
);
// level up
samurai.level = samurai.level.add(1);
// help checking the last samurai pot
distributeTheLastSamuraiPot();
// push the samurai Id to the corresponding level chain
push(levelChain[samurai.level], _samuraiId);
supporterCount[_samuraiId] = 0;
// Check if head exist, and get it's Id
(exist, samuraiHeadId) = levelChain[samurai.level].getAdjacent(0, true);
// Distribute 0.001 ETH to poor developer
samurai.supporterWallet = samurai.supporterWallet.sub(PROCESSING_FEE);
totalProcessingFee = totalProcessingFee.add(PROCESSING_FEE);
// Distribute 0.002 ETH to the last samurai pot
samurai.supporterWallet = samurai.supporterWallet.sub(THE_LAST_SAMURAI_FEE);
theLastSamuraiPot = theLastSamuraiPot.add(THE_LAST_SAMURAI_FEE);
// Distribute 0.002 ETH to affiliate/the last samurai pot
uint256 affiliateId = idToAffiliateId[_samuraiId];
samurai.supporterWallet = samurai.supporterWallet.sub(REFERRAL_FEE);
if (affiliateId == 0) {
theLastSamuraiPot = theLastSamuraiPot.add(REFERRAL_FEE);
} else {
Samurai storage affiliate = idToSamurai[affiliateId];
affiliate.referralWallet = affiliate.referralWallet.add(REFERRAL_FEE);
}
// check if samuraiHead exist and it should not be Samurai itself
if (exist && samuraiHeadId != _samuraiId) {
Samurai storage samuraiHead = idToSamurai[samuraiHeadId];
// Distribute the level up fee to samuraiHead
samurai.supporterWallet = samurai.supporterWallet.sub(levelUpFee[samurai.level]);
samuraiHead.supporterWallet = samuraiHead.supporterWallet.add(levelUpFee[samurai.level]);
// Map the samuraiId to samuraiHead struct
idToSamuraiHeadId[_samuraiId] = samuraiHeadId;
// Add up the supporter count of samuraiHead
supporterCount[samuraiHeadId] = supporterCount[samuraiHeadId].add(1);
// nested loop to level up samuraiHead
if(canLevelUp(samuraiHeadId)) {
// pop the samurai headoff the leve chain
pop(levelChain[samuraiHead.level]);
if(samuraiHead.autoLevelUp) {
levelUp(samuraiHeadId);
} else {
return;
}
} else {
return;
}
}
}
/// *** retreat Logic
// Retreat the samurai, pop it off the level chain
// Help checking the last samurai pot
// Distribute the fund to corresponding accounts
// _samuraiId - Id of the samurai to be retreat
function retreat(uint256 _samuraiId) public {
Samurai storage samurai = idToSamurai[_samuraiId];
require(!samurai.isRetreat, "you've already quit!");
require(samurai.addr == msg.sender, "you must be a yokai spy!");
uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet);
require(balance >= 0.005 ether, "fee is required, even when retreating");
// Clear the balance, prevent re-entrancy
samurai.supporterWallet = 0;
samurai.theLastSamuraiWallet = 0;
samurai.referralWallet = 0;
// pop the player off the level chain and mark the retreat flag
remove(levelChain[samurai.level], _samuraiId);
samurai.isRetreat = true;
// Transfer the processing fee to poor developer
balance = balance.sub(PROCESSING_FEE);
totalProcessingFee = totalProcessingFee.add(PROCESSING_FEE);
balance = balance.sub(THE_LAST_SAMURAI_FEE);
theLastSamuraiPot = theLastSamuraiPot.add(THE_LAST_SAMURAI_FEE);
balance = balance.sub(REFERRAL_FEE);
uint256 affiliateId = idToAffiliateId[_samuraiId];
// No affiliate, distribute the referral fee to the last samurai pot
if (affiliateId == 0) {
theLastSamuraiPot = theLastSamuraiPot.add(REFERRAL_FEE);
} else {
Samurai storage affiliate = idToSamurai[affiliateId];
affiliate.referralWallet = affiliate.referralWallet.add(REFERRAL_FEE);
}
// transfer balance to account holder
samurai.addr.transfer(balance);
// help checking the last samurai pot
distributeTheLastSamuraiPot();
emit Retreat(_samuraiId, samurai.name, balance);
}
/// *** withdraw Logic
// Withdraw the left over fund in wallet after retreat
// _samuraiId - Id of the samurai
function withdraw(uint256 _samuraiId) public {
Samurai storage samurai = idToSamurai[_samuraiId];
require(samurai.addr == msg.sender, "you must be a yokai spy!");
uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet);
require(balance <= address(this).balance, "not enough fund");
// Prevent re-entrancy
samurai.supporterWallet = 0;
samurai.theLastSamuraiWallet = 0;
samurai.referralWallet = 0;
// transfer balance to account holder
samurai.addr.transfer(balance);
}
/// *** distributeTheLastSamuraiPot Logic
// Distribute the last samurai pot to winner when no joining after 24 hours
// Distribute the fund to corresponding accounts
// _samuraiId - Id of the samurai to be retreat
function distributeTheLastSamuraiPot() public {
require(theLastSamuraiPot <= address(this).balance, "not enough fund");
// When the remaining time is over
if (theLastSamuraiEndTime <= now) {
uint256 samuraiId = currentSamuraiId.sub(1);
Samurai storage samurai = idToSamurai[samuraiId];
uint256 total = theLastSamuraiPot;
// again, prevent re-entrancy
theLastSamuraiPot = 0;
samurai.theLastSamuraiWallet = samurai.theLastSamuraiWallet.add(total);
emit TheLastSamuraiBorn(samuraiId, samurai.name, total);
}
}
/// *** toggleAutoLevelUp Logic
// Toggle auto level up, for those who don't intend to play longer,
// can set the auto level up to false
// _samuraiId - Id of the samurai
function toggleAutoLevelUp(uint256 _samuraiId) public {
Samurai storage samurai = idToSamurai[_samuraiId];
require(!samurai.isRetreat, "you've already quit!");
require(msg.sender == samurai.addr, "you must be a yokai spy");
samurai.autoLevelUp = !samurai.autoLevelUp;
}
//*** For UI
// Returns - Id
function getSamuraiId() public view returns(uint256) {
return addressToId[msg.sender];
}
// Returns - 0: id, 1: level, 2: name, 3: isRetreat, 4: autoLevelUp, 5: isHead
function getSamuraiInfo(uint256 _samuraiId) public view
returns(uint256, uint256, bytes32, bool, bool, bool)
{
Samurai memory samurai = idToSamurai[_samuraiId];
bool isHead = isHeadOfSamurai(_samuraiId);
return (_samuraiId, samurai.level, samurai.name, samurai.isRetreat, samurai.autoLevelUp, isHead);
}
// Returns - 0: supperterWallet, 1: theLastSamuraiWallet, 2: referralWallet
function getSamuraiWallet(uint256 _samuraiId) public view
returns(uint256, uint256, uint256)
{
Samurai memory samurai = idToSamurai[_samuraiId];
return (samurai.supporterWallet, samurai.theLastSamuraiWallet, samurai.referralWallet);
}
// Returns - 0: affiliateId, 1: affiliateName
function getAffiliateInfo(uint256 _samuraiId) public view returns(uint256, bytes32) {
uint256 affiliateId = idToAffiliateId[_samuraiId];
Samurai memory affiliate = idToSamurai[affiliateId];
return (affiliateId, affiliate.name);
}
// Returns - 0: samuraiHeadId, 1: samuraiHeadName
function contributeTo(uint256 _samuraiId) public view returns(uint256, bytes32) {
uint256 samuraiHeadId = idToSamuraiHeadId[_samuraiId];
Samurai memory samuraiHead = idToSamurai[samuraiHeadId];
return (samuraiHeadId, samuraiHead.name);
}
// Returns - 0: theLastSamuraiEndTime, 1: theLastSamuraiPot, 2: lastSamuraiId, 3: lastSamuraiName
function getTheLastSamuraiInfo() public view returns(uint256, uint256, uint256, bytes32) {
uint256 lastSamuraiId = currentSamuraiId.sub(1);
return (theLastSamuraiEndTime, theLastSamuraiPot, lastSamuraiId, idToSamurai[lastSamuraiId].name);
}
// Returns - canLevelUp
function canLevelUp(uint256 _id) public view returns(bool) {
Samurai memory samurai = idToSamurai[_id];
return !samurai.isRetreat && (samurai.level == 0 || (supporterCount[_id] == 2 ** samurai.level && samurai.level <= MAX_LEVEL));
}
// Returns - canRetreat
function canRetreat(uint256 _id) public view returns(bool) {
Samurai memory samurai = idToSamurai[_id];
uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet);
return !samurai.isRetreat && (balance >= 0.005 ether);
}
// Returns - canWithdraw
function canWithdraw(uint256 _id) public view returns(bool) {
Samurai memory samurai = idToSamurai[_id];
uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet);
return samurai.isRetreat && (balance > 0);
}
// Returns - isHeadOfSamurai
function isHeadOfSamurai(uint256 _id) public view returns(bool) {
Samurai memory samurai = idToSamurai[_id];
bool exist;
uint256 samuraiHeadId;
(exist, samuraiHeadId) = levelChain[samurai.level].getAdjacent(0, true);
return (exist && samuraiHeadId == _id);
}
// For linked list manipulation
function push(LinkedListLib.LinkedList storage _levelChain, uint256 _samuraiId) private {
_levelChain.push(_samuraiId, false);
}
function pop(LinkedListLib.LinkedList storage _levelChain) private {
_levelChain.pop(true);
}
function remove(LinkedListLib.LinkedList storage _levelChain, uint256 _samuraiId) private {
_levelChain.remove(_samuraiId);
}
}
/**
* @title LinkedListLib
* @author Darryl Morris (o0ragman0o) and Modular.network
*
* This utility library was forked from https://github.com/o0ragman0o/LibCLL
* into the Modular-Network ethereum-libraries repo at https://github.com/Modular-Network/ethereum-libraries
* It has been updated to add additional functionality and be more compatible with solidity 0.4.18
* coding patterns.
*
* version 1.0.0
* Copyright (c) 2017 Modular Inc.
* The MIT License (MIT)
* https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE
*
* The LinkedListLib provides functionality for implementing data indexing using
* a circlular linked list.
*
* Modular provides smart contract services and security reviews for contract
* deployments in addition to working on open source projects in the Ethereum
* community. Our purpose is to test, document, and deploy reusable code onto the
* blockchain and improve both security and usability. We also educate non-profits,
* schools, and other community members about the application of blockchain
* technology. For further information: modular.network.
*
*
* 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 LinkedListLib {
uint256 private constant NULL = 0;
uint256 private constant HEAD = 0;
bool private constant PREV = false;
bool private constant NEXT = true;
struct LinkedList {
mapping (uint256 => mapping (bool => uint256)) list;
}
/// @dev returns true if the list exists
/// @param self stored linked list from contract
function listExists(LinkedList storage self)
internal
view returns (bool)
{
// if the head nodes previous or next pointers both point to itself, then there are no items in the list
if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) {
return true;
} else {
return false;
}
}
/// @dev returns true if the node exists
/// @param self stored linked list from contract
/// @param _node a node to search for
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool)
{
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/// @dev Returns the number of elements in the list
/// @param self stored linked list from contract
function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) {
bool exists;
uint256 i;
(exists, i) = getAdjacent(self, HEAD, NEXT);
while (i != HEAD) {
(exists, i) = getAdjacent(self, i, NEXT);
numElements++;
}
return;
}
/// @dev Returns the links of a node as a tuple
/// @param self stored linked list from contract
/// @param _node id of the node to get
function getNode(LinkedList storage self, uint256 _node)
internal view returns (bool, uint256, uint256)
{
if (!nodeExists(self, _node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
/// @dev Returns the link of a node `_node` in direction `_direction`.
/// @param self stored linked list from contract
/// @param _node id of the node to step from
/// @param _direction direction to step in
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
internal view returns (bool, uint256)
{
if (!nodeExists(self, _node)) {
return (false, 0);
} else {
return (true, self.list[_node][_direction]);
}
}
/// @dev Can be used before `insert` to build an ordered list
/// @param self stored linked list from contract
/// @param _node an existing node to search from, e.g. HEAD.
/// @param _value value to seek
/// @param _direction direction to seek in
// @return next first node beyond '_node' in direction `_direction`
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
internal view returns (uint256)
{
if (sizeOf(self) == 0) {
return 0;
}
require((_node == 0) || nodeExists(self, _node));
bool exists;
uint256 next;
(exists, next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) {
next = self.list[next][_direction];
}
return next;
}
/// @dev Creates a bidirectional link between two nodes on direction `_direction`
/// @param self stored linked list from contract
/// @param _node first node for linking
/// @param _link node to link to in the _direction
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction)
internal
{
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
/// @dev Insert node `_new` beside existing node `_node` in direction `_direction`.
/// @param self stored linked list from contract
/// @param _node existing node
/// @param _new new node to insert
/// @param _direction direction to insert node in
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) {
if (!nodeExists(self, _new) && nodeExists(self, _node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
return true;
} else {
return false;
}
}
/// @dev removes an entry from the linked list
/// @param self stored linked list from contract
/// @param _node node to remove from the list
function remove(LinkedList storage self, uint256 _node) internal returns (uint256) {
if ((_node == NULL) || (!nodeExists(self, _node))) {
return 0;
}
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
return _node;
}
/// @dev pushes an entry to the head of the linked list
/// @param self stored linked list from contract
/// @param _node new entry to push to the head
/// @param _direction push to the head (NEXT) or tail (PREV)
function push(LinkedList storage self, uint256 _node, bool _direction)
internal returns (bool)
{
return insert(self, HEAD, _node, _direction);
}
/// @dev pops the first entry from the linked list
/// @param self stored linked list from contract
/// @param _direction pop from the head (NEXT) or the tail (PREV)
function pop(LinkedList storage self, bool _direction)
internal returns (uint256)
{
bool exists;
uint256 adj;
(exists, adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
/**
* @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;
}
} | Distribute the last samurai pot to winner when no joining after 24 hours Distribute the fund to corresponding accounts _samuraiId - Id of the samurai to be retreat When the remaining time is over again, prevent re-entrancy | function distributeTheLastSamuraiPot() public {
require(theLastSamuraiPot <= address(this).balance, "not enough fund");
if (theLastSamuraiEndTime <= now) {
uint256 samuraiId = currentSamuraiId.sub(1);
Samurai storage samurai = idToSamurai[samuraiId];
uint256 total = theLastSamuraiPot;
theLastSamuraiPot = 0;
samurai.theLastSamuraiWallet = samurai.theLastSamuraiWallet.add(total);
emit TheLastSamuraiBorn(samuraiId, samurai.name, total);
}
}
| 13,088,937 | [
1,
1669,
887,
326,
1142,
16260,
295,
10658,
5974,
358,
5657,
1224,
1347,
1158,
21239,
1839,
4248,
7507,
3035,
887,
326,
284,
1074,
358,
4656,
9484,
389,
20353,
295,
10658,
548,
300,
3124,
434,
326,
16260,
295,
10658,
358,
506,
325,
6150,
5203,
326,
4463,
813,
353,
1879,
3382,
16,
5309,
283,
17,
8230,
12514,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25722,
1986,
3024,
55,
301,
295,
10658,
18411,
1435,
1071,
288,
203,
3639,
2583,
12,
5787,
3024,
55,
301,
295,
10658,
18411,
1648,
1758,
12,
2211,
2934,
12296,
16,
315,
902,
7304,
284,
1074,
8863,
203,
203,
3639,
309,
261,
5787,
3024,
55,
301,
295,
10658,
25255,
1648,
2037,
13,
288,
203,
5411,
2254,
5034,
16260,
295,
10658,
548,
273,
783,
55,
301,
295,
10658,
548,
18,
1717,
12,
21,
1769,
203,
5411,
348,
301,
295,
10658,
2502,
16260,
295,
10658,
273,
612,
774,
55,
301,
295,
10658,
63,
20353,
295,
10658,
548,
15533,
203,
203,
5411,
2254,
5034,
2078,
273,
326,
3024,
55,
301,
295,
10658,
18411,
31,
203,
2398,
203,
5411,
326,
3024,
55,
301,
295,
10658,
18411,
273,
374,
31,
203,
5411,
16260,
295,
10658,
18,
5787,
3024,
55,
301,
295,
10658,
16936,
273,
16260,
295,
10658,
18,
5787,
3024,
55,
301,
295,
10658,
16936,
18,
1289,
12,
4963,
1769,
203,
203,
5411,
3626,
1021,
3024,
55,
301,
295,
10658,
38,
14245,
12,
20353,
295,
10658,
548,
16,
16260,
295,
10658,
18,
529,
16,
2078,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x002Fd2C8fD1C55Ce157684Ed2121346a32CB18F5/sources/contracts/bhnk.sol | SPDX-License-Identifier: MIT* @dev Wrappers over Solidity's arithmetic operations with added overflow checks. Arithmetic operations in Solidity wrap on overflow. This can easily result in bugs, because programmers usually assume that an overflow raises an error, which is the standard behavior in high level programming languages. `SafeMath` restores this intuition by reverting the transaction when an operation overflows. Using this library instead of the unchecked operations eliminates an entire class of bugs, so it's recommended to use it always./ | library SafeMath {
function 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 mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a <= b ? a : b;
}
function abs(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return b - a;
}
return a - b;
}
function abs(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return b - a;
}
return a - b;
}
}
| 8,144,883 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
225,
4266,
10422,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
12083,
14060,
10477,
288,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
2583,
12,
71,
1545,
279,
16,
315,
9890,
10477,
30,
2719,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
720,
12,
69,
16,
324,
16,
315,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
565,
289,
203,
203,
565,
445,
720,
12,
203,
3639,
2254,
5034,
279,
16,
203,
3639,
2254,
5034,
324,
16,
203,
3639,
533,
3778,
9324,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
70,
1648,
279,
16,
9324,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
2
] |
// Copyright 2019 Cartesi Pte. Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
/// @title StandAloneInstructions
pragma solidity ^0.7.0;
import "../MemoryInteractor.sol";
import "../RiscVDecoder.sol";
library StandAloneInstructions {
//AUIPC forms a 32-bit offset from the 20-bit U-immediate, filling in the
// lowest 12 bits with zeros, adds this offset to pc and store the result on rd.
// Reference: riscv-spec-v2.2.pdf - Page 14
function executeAuipc(
MemoryInteractor mi,
uint32 insn,
uint64 pc
) public
{
uint32 rd = RiscVDecoder.insnRd(insn);
if (rd != 0) {
mi.writeX(rd, pc + uint64(RiscVDecoder.insnUImm(insn)));
}
//return advanceToNextInsn(mi, pc);
}
// LUI (i.e load upper immediate). Is used to build 32-bit constants and uses
// the U-type format. LUI places the U-immediate value in the top 20 bits of
// the destination register rd, filling in the lowest 12 bits with zeros
// Reference: riscv-spec-v2.2.pdf - Section 2.5 - page 13
function executeLui(
MemoryInteractor mi,
uint32 insn
) public
{
uint32 rd = RiscVDecoder.insnRd(insn);
if (rd != 0) {
mi.writeX(rd, uint64(RiscVDecoder.insnUImm(insn)));
}
//return advanceToNextInsn(mi, pc);
}
// JALR (i.e Jump and Link Register). uses the I-type encoding. The target
// address is obtained by adding the 12-bit signed I-immediate to the register
// rs1, then setting the least-significant bit of the result to zero.
// The address of the instruction following the jump (pc+4) is written to register rd
// Reference: riscv-spec-v2.2.pdf - Section 2.5 - page 16
function executeJalr(
MemoryInteractor mi,
uint32 insn,
uint64 pc
)
public returns (bool, uint64)
{
uint64 newPc = uint64(int64(mi.readX(RiscVDecoder.insnRs1(insn))) + int64(RiscVDecoder.insnIImm(insn))) & ~uint64(1);
if ((newPc & 3) != 0) {
return (false, newPc);
//return raiseMisalignedFetchException(mi, newPc);
}
uint32 rd = RiscVDecoder.insnRd(insn);
if (rd != 0) {
mi.writeX(rd, pc + 4);
}
return (true, newPc);
//return executeJump(mi, newPc);
}
// JAL (i.e Jump and Link). JImmediate encondes a signed offset in multiples
// of 2 bytes. The offset is added to pc and JAL stores the address of the jump
// (pc + 4) to the rd register.
// Reference: riscv-spec-v2.2.pdf - Section 2.5 - page 16
function executeJal(
MemoryInteractor mi,
uint32 insn,
uint64 pc
)
public returns (bool, uint64)
{
uint64 newPc = pc + uint64(RiscVDecoder.insnJImm(insn));
if ((newPc & 3) != 0) {
return (false, newPc);
//return raiseMisalignedFetchException(mi, newPc);
}
uint32 rd = RiscVDecoder.insnRd(insn);
if (rd != 0) {
mi.writeX(rd, pc + 4);
}
return (true, newPc);
//return executeJump(mi, newPc);
}
}
| JAL (i.e Jump and Link). JImmediate encondes a signed offset in multiples of 2 bytes. The offset is added to pc and JAL stores the address of the jump (pc + 4) to the rd register. Reference: riscv-spec-v2.2.pdf - Section 2.5 - page 16return raiseMisalignedFetchException(mi, newPc); | function executeJal(
MemoryInteractor mi,
uint32 insn,
uint64 pc
)
public returns (bool, uint64)
{
uint64 newPc = pc + uint64(RiscVDecoder.insnJImm(insn));
if ((newPc & 3) != 0) {
return (false, newPc);
}
uint32 rd = RiscVDecoder.insnRd(insn);
if (rd != 0) {
mi.writeX(rd, pc + 4);
}
return (true, newPc);
| 2,575,689 | [
1,
46,
1013,
261,
77,
18,
73,
804,
2801,
471,
4048,
2934,
804,
22651,
570,
591,
5489,
279,
6726,
1384,
316,
3309,
6089,
434,
576,
1731,
18,
1021,
1384,
353,
3096,
358,
6125,
471,
804,
1013,
9064,
326,
1758,
434,
326,
11833,
261,
2436,
397,
1059,
13,
358,
326,
9437,
1744,
18,
6268,
30,
436,
291,
19774,
17,
2793,
17,
90,
22,
18,
22,
18,
7699,
300,
225,
10092,
576,
18,
25,
300,
1363,
2872,
2463,
1002,
11729,
20677,
5005,
503,
12,
9197,
16,
394,
28136,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1836,
46,
287,
12,
203,
3639,
9251,
2465,
3362,
12837,
16,
203,
3639,
2254,
1578,
29821,
16,
203,
3639,
2254,
1105,
6125,
203,
565,
262,
203,
565,
1071,
1135,
261,
6430,
16,
2254,
1105,
13,
203,
565,
288,
203,
3639,
2254,
1105,
394,
28136,
273,
6125,
397,
2254,
1105,
12,
54,
291,
71,
58,
7975,
18,
2679,
82,
46,
1170,
81,
12,
2679,
82,
10019,
203,
203,
3639,
309,
14015,
2704,
28136,
473,
890,
13,
480,
374,
13,
288,
203,
5411,
327,
261,
5743,
16,
394,
28136,
1769,
203,
3639,
289,
203,
3639,
2254,
1578,
9437,
273,
534,
291,
71,
58,
7975,
18,
2679,
82,
54,
72,
12,
2679,
82,
1769,
203,
203,
3639,
309,
261,
13623,
480,
374,
13,
288,
203,
5411,
12837,
18,
2626,
60,
12,
13623,
16,
6125,
397,
1059,
1769,
203,
3639,
289,
203,
3639,
327,
261,
3767,
16,
394,
28136,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.25 < 0.7.0;
contract FlightSuretyData {
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
// The state variables for Airlines
struct Airline {
string name;
bool isActive;
bool funded;
}
mapping(address => Airline) public airlines;
mapping(address => address[]) private airlineToVote;
struct AirlineList {
string name;
address addr;
}
AirlineList[] private airlinesList;
// The state variables for Flight
struct Flight {
string name;
uint8 statusCode;
uint256 departureTime;
uint256 updatedTimestamp;
address airline;
uint256[] tickets;
}
mapping(bytes32 => Flight) private flights;
struct FlightList {
string name;
bytes32 key;
}
FlightList[] private flightsList;
// The state variables for Insurance
struct Insurance {
uint256 ticket;
string flight;
address buyer;
uint256 amount;
}
mapping(bytes32 => Insurance[]) private insureList;
mapping(address => uint256) private payoutList;
// The flight status code from the oracle
uint8 private constant STATUS_CODE_UNKNOWN = 0;
/********************************************************************************************/
/* Constructor */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
address firstAirline
)
public
{
registerFirstAirline(firstAirline);
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(this.isOperational(), "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");
_;
}
/********************************************************************************************/
/* FUNCTIONS FOR MODIFIERS */
/********************************************************************************************/
/**
* @dev To check if the airline is an active and funded member
*/
function isActiveAndFunded
(
address airline
)
external
view
returns(bool)
{
return this.isActive(airline) && this.isFunded(airline);
}
/**
* @dev To check if the airline is an active and funded member
*/
function isActive
(
address airline
)
external
view
returns(bool)
{
return airlines[airline].isActive;
}
/**
* @dev To check if the airline is an active and funded member
*/
function isFunded
(
address airline
)
external
view
returns(bool)
{
return airlines[airline].funded;
}
/**
* @dev To check that the airline to be a new one
*/
function isAirline
(
address airline
)
external
view
returns(bool)
{
bytes memory name = bytes(airlines[airline].name);
return name.length > 0;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
external
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
{
require(this.isOperational() != mode, "Nothing to change");
operational = mode;
}
/**
* @dev Modifier that requires the airline to be a new one
*/
function getAirlineByName
(
string calldata name
)
external
view
returns(address)
{
address airlineAddress = address(0);
for (uint i = 0; i < airlinesList.length; i++) {
if (keccak256(bytes(airlinesList[i].name)) == keccak256(bytes(name))) {
airlineAddress = airlinesList[i].addr;
}
}
return airlineAddress;
}
function getFlightKeyByName
(
string memory flight
)
internal
view
returns(bytes32 key)
{
key = '';
for (uint8 i = 0; i < flightsList.length; i++) {
if (keccak256(bytes(flight)) == keccak256(bytes(flightsList[i].name))) {
key = flightsList[i].key;
}
}
}
function stringToBytes32
(
string memory source
)
public
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/***************************************** Airlines Starts **********************************/
/**
* @dev Register the first airline
* It is automatically done by at the time of contract deployment
*/
function registerFirstAirline
(
address airline
)
internal
{
airlines[airline] = Airline({
name: "First Flight",
isActive: true,
funded: false
});
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*/
function registerAirline
(
string calldata name,
address airline
)
external
returns(bool success, string memory message)
{
success = false;
airlines[airline] = Airline({
name: name,
isActive: false,
funded: false
});
if (airlinesList.length > 0 && airlinesList.length <=4) {
airlines[airline].isActive = true;
success = true;
message = "Airline registered successfully";
} else {
address[] memory blankArray;
airlineToVote[airline] = blankArray;
success = true;
message = "Airline waiting to be voted";
}
}
/**
* @dev Add an airline to the registration queue
*/
function voteAirline
(
address airline,
address voter
)
external
returns(uint)
{
bool alreadyVoted = false;
for(uint8 i = 0; i < airlineToVote[airline].length; i++) {
if (airlineToVote[airline][i] == voter) {
alreadyVoted = true;
}
}
if (!alreadyVoted) {
airlineToVote[airline].push(voter);
}
if (airlineToVote[airline].length > airlinesList.length/2) {
airlines[airline].isActive = true;
delete(airlineToVote[airline]);
}
return airlineToVote[airline].length;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*/
function fund
(
address airline
)
public
payable
{
airlines[airline].funded = true;
airlinesList.push(AirlineList({
name: airlines[airline].name,
addr: airline
}));
}
/**
* @dev Get Airline information
*/
function getAirlineInfo
(
address airline
)
external
view
returns(string memory, bool, bool, uint256)
{
return (
airlines[airline].name,
airlines[airline].funded,
airlines[airline].isActive,
airlineToVote[airline].length
);
}
/**
* @dev Get all Airline name
*/
function getAirlineTotal()
external
view
returns(uint)
{
return airlinesList.length;
}
/**
* @dev Get all Airline name
*/
function getAllAirlineName()
external
view
returns(bytes32[] memory)
{
bytes32[] memory allAirlines = new bytes32[](airlinesList.length);
for(uint i = 0; i < airlinesList.length; i++) {
allAirlines[i] = stringToBytes32(airlinesList[i].name);
}
return allAirlines;
}
/****************************************** Airlines Ends ***********************************/
/****************************************** Flight Starts ***********************************/
/**
* @dev register a new flight by an active airline
*/
function registerFlight
(
address airline,
string calldata flight,
uint256 timestamp,
uint256[] calldata tickets
)
external
returns(bool success, string memory message)
{
success = false;
bytes32 key = getFlightKey(airline, flight, timestamp);
flights[key] = Flight({
name: flight,
statusCode: STATUS_CODE_UNKNOWN,
departureTime: timestamp,
updatedTimestamp: now,
airline: airline,
tickets: tickets
});
flightsList.push(FlightList({
name: flight,
key: key
}));
success = true;
message = "Flight registered successfully";
}
/**
* @dev Get all Airline name
*/
function getAllFlightsName()
external
view
returns(bytes32[] memory)
{
bytes32[] memory allFlights;
for(uint i = 0; i < flightsList.length; i++) {
allFlights[i] = stringToBytes32(flightsList[i].name);
}
return allFlights;
}
/**
* @dev Add tickets to a flight
*/
function addTicketsToFlight
(
string calldata flight,
uint256[] calldata tickets
)
external
returns(bool success)
{
success = false;
bytes32 key = getFlightKeyByName(flight);
for(uint i = 0; i < tickets.length; i++) {
flights[key].tickets.push(tickets[i]);
}
success = true;
}
/**
* @dev Supporting functions to get the keys for saving the flight
*/
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/******************************************* Flight Ends ************************************/
/**************************************** Insurance Starts **********************************/
/**
* @dev Buy insurance for a flight
*/
function buy
(
string calldata flight,
uint256 ticket,
address payable buyer
)
external
payable
{
bytes32 key = getFlightKeyByName(flight);
require(flights[key].departureTime > now, "Flight should be in future");
Insurance memory insurance = Insurance({
ticket: ticket,
flight: flight,
buyer: buyer,
amount: msg.value
});
insureList[key].push(insurance);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
string calldata flight
)
external
{
bytes32 key = getFlightKeyByName(flight);
Insurance[] memory insurances = insureList[key];
for(uint i = 0; i < insurances.length; i++) {
address customer = insurances[i].buyer;
uint256 amount = insurances[i].amount * 150 / 100;
if (payoutList[customer] == 0) {
payoutList[customer] = amount;
} else {
payoutList[customer] += amount;
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*/
function pay
(
address payable receiver
)
external
payable
returns(uint256 amount)
{
require(payoutList[receiver] > 0, "Nothing to payout");
amount = payoutList[receiver];
payoutList[receiver] = 0;
receiver.transfer(amount);
}
/***************************************** Insurance Ends ***********************************/
/**
* @dev Fallback function for funding smart contract.
*/
function()
external
payable
{
fund(msg.sender);
}
}
| * @dev To check that the airline to be a new one/ | function isAirline
(
address airline
)
external
view
returns(bool)
{
bytes memory name = bytes(airlines[airline].name);
return name.length > 0;
}
| 12,764,296 | [
1,
774,
866,
716,
326,
23350,
1369,
358,
506,
279,
394,
1245,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25997,
481,
1369,
203,
565,
261,
203,
3639,
1758,
23350,
1369,
203,
565,
262,
203,
565,
3903,
203,
565,
1476,
203,
565,
1135,
12,
6430,
13,
203,
565,
288,
203,
3639,
1731,
3778,
508,
273,
1731,
12,
1826,
3548,
63,
1826,
1369,
8009,
529,
1769,
203,
3639,
327,
508,
18,
2469,
405,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-14
*/
pragma solidity ^0.7.2;
/**
* @dev Provides data about the current execution setting, including the
* sender of the exchange and its information. While these are commonly accessible
* through msg.sender and msg.data, they ought not be gotten to in such a direct
* way, since when managing GSN meta-exchanges the record sending and
* paying for execution may not be the real sender (to the extent an application
* is concerned).
*
* This agreement is just needed for middle, library-like agreements.
*/
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 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) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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 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) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
/**
* @dev Contract module which gives a fundamental access control system, where
* there is a record (a proprietor) that can be conceded selective admittance to
* explicit capacities.
*
* By default, the proprietor record will be the one that conveys the agreement. This
* can later be changed with {transferOwnership}.
*
* This module is utilized through legacy. It will make accessible the modifier
* 'onlyOwner', which can be applied to your capacities to confine their utilization to
* the proprietor.
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed _to);
constructor(address _owner) public {
owner = _owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() external {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(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);
}
abstract contract ERC20 is IERC20, Owned {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalSupply;
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
abstract contract StakeVXP {
/**
* @dev stakes amount of tokens to the liquidity provider pool
*/
function _stake(address to, uint256 amount) internal{}
/**
* @dev redeems the amount of the current user
*/
function _redeem(address to, uint256 amount) internal{}
/**
* @dev claims rewards transfer to his account.
*/
function _claimRewards(address to, uint256 amount) internal{}
}
/**
* @dev VAULTXP Contract is completely unique and adheres to the traditional
* allowance mechanism. The contract is made by 2 devs ken and XP
*/
contract VaultXP is ERC20, StakeVXP {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public burnedToken;
uint256 public presaleToken;
uint256 public presaleTarget;
uint256 public presalePool;
bool public presaleEvent;
address private stakeContractAddress;
constructor() public Owned(msg.sender) {
name = "VAULTXP.FINANCE";
symbol = "VAULTXP";
decimals = 18;
_totalSupply = 15000000000000000000000; // 15,000 supply
_balances[msg.sender] = _totalSupply;
burnedToken = 0;
presaleToken = 14500;
presaleTarget = 650000000000000000000; // 650
emit Transfer(address(0), msg.sender, _totalSupply);
}
function burn(uint256 _amount) external returns (bool) {
super._burn(msg.sender, _amount);
burnedToken = burnedToken.add(_amount);
return true;
}
function transfer(address _recipient, uint256 _amount) public override returns (bool) {
if(totalSupply() <= 3000) {
super._transfer(msg.sender, _recipient, _amount);
return true;
}
uint _burnAmount = _amount.mul(100).div(10000); // 1 percent burning
_burn(msg.sender, _burnAmount);
burnedToken = burnedToken.add(_burnAmount);
uint _transferAmount = _amount.sub(_burnAmount);
super._transfer(msg.sender, _recipient, _transferAmount);
return true;
}
function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) {
super._transferFrom(_sender, _recipient, _amount);
return true;
}
function buyPresaleToken() public payable{
require(presaleEvent);
transferToPresalePool();
uint256 value = msg.value;
require(value > 0);
uint _tokenEquivalent = value.mul(22);
_balances[owner] = _balances[owner].sub(_tokenEquivalent);
_balances[msg.sender] = _balances[msg.sender].add(_tokenEquivalent);
// update Presale Pool Value
presalePool = presalePool.add(value);
}
function transferToPresalePool() private{
address payable _to = address(uint160(owner));
_to.transfer(getBalance());
}
function getBalance() private view returns(uint){
return address(this).balance;
}
function getContractBalance() public view onlyOwner returns(uint){
return getBalance();
}
function startPresaleEvent() public onlyOwner{
presaleEvent = true;
}
function endPresaleEvent() public onlyOwner{
presaleEvent = false;
}
function getTokenBalance() public view returns(uint){
return _balances[msg.sender];
}
function setStakeContractAddress(address _stakeContractAddress) public onlyOwner{
stakeContractAddress = _stakeContractAddress;
}
function getStakeContractAddress() public view onlyOwner returns(address){
return stakeContractAddress;
}
function stake(address _stakeToContract, address _to, uint256 _amount) public{
require(_stakeToContract == stakeContractAddress);
_stake(_to, _amount);
}
function redeem(address _stakeToContract, address _to, uint256 _amount) public{
require(_stakeToContract == stakeContractAddress);
_redeem(_to, _amount);
}
function _claimRewards(address _stakeToContract, address _to, uint256 _amount) public{
require(_stakeToContract == stakeContractAddress);
_claimRewards(_to, _amount);
}
} | * @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) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
| 2,367,132 | [
1,
1356,
326,
720,
25693,
434,
2795,
9088,
12321,
16,
15226,
310,
598,
1679,
883,
603,
9391,
261,
13723,
326,
563,
353,
6092,
2934,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
17,
68,
3726,
18,
29076,
30,
300,
2592,
25693,
2780,
9391,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
70,
1648,
279,
16,
315,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
3639,
327,
276,
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
] |
./full_match/43113/0xcd46bAEC69BEB8F125274A18a5Cc88Fa14Ec4757/sources/AmaCLClient.sol | bytes32 _ethaddressHash = keccakHash(_ethaddress); | function claimCustomSubDomain(
string calldata _differentLabel)
external {
Response memory _response = results[msg.sender];
require(_response.verifiedOnChain, "Address is not yet verified onChain");
(,string memory nameOnTwitter, string memory profileImage, string memory twitterID, bool isTwitterVerified) =
decode_data(_response.data);
bytes memory _new = abi.encode(_differentLabel,nameOnTwitter,profileImage,twitterID,isTwitterVerified);
(bytes32 nodehash, ) = _registerNode(msg.sender, _new, _response.twitterUsername);
_setLabel(msg.sender, _differentLabel);
_setNodeHashToAddress(nodehash, msg.sender);
_setTwitterUsernameToAddress(_response.twitterUsername, msg.sender);
}
| 13,194,681 | [
1,
3890,
1578,
389,
546,
2867,
2310,
273,
417,
24410,
581,
2310,
24899,
546,
2867,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
3802,
1676,
3748,
12,
7010,
10792,
533,
745,
892,
389,
30738,
2224,
13,
203,
10792,
3903,
225,
288,
203,
203,
3639,
2306,
3778,
389,
2740,
273,
1686,
63,
3576,
18,
15330,
15533,
203,
3639,
2583,
24899,
2740,
18,
19685,
1398,
3893,
16,
315,
1887,
353,
486,
4671,
13808,
603,
3893,
8863,
203,
203,
203,
203,
3639,
261,
16,
1080,
3778,
508,
1398,
23539,
6132,
16,
533,
3778,
3042,
2040,
16,
533,
3778,
18530,
734,
16,
1426,
353,
23539,
6132,
24369,
13,
273,
7010,
3639,
2495,
67,
892,
24899,
2740,
18,
892,
1769,
203,
203,
203,
3639,
1731,
3778,
389,
2704,
273,
24126,
18,
3015,
24899,
30738,
2224,
16,
529,
1398,
23539,
6132,
16,
5040,
2040,
16,
19406,
734,
16,
291,
23539,
6132,
24369,
1769,
203,
3639,
261,
3890,
1578,
756,
2816,
16,
262,
273,
389,
4861,
907,
12,
3576,
18,
15330,
16,
389,
2704,
16,
389,
2740,
18,
19406,
8575,
1769,
203,
203,
203,
3639,
389,
542,
2224,
12,
3576,
18,
15330,
16,
389,
30738,
2224,
1769,
203,
203,
3639,
389,
542,
907,
2310,
774,
1887,
12,
2159,
2816,
16,
1234,
18,
15330,
1769,
203,
3639,
389,
542,
23539,
6132,
8575,
774,
1887,
24899,
2740,
18,
19406,
8575,
16,
1234,
18,
15330,
1769,
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
] |
./full_match/1/0xe261B138cfd46FdC12A039cF6690645f35DCFA37/sources/contracts/DropFactory/DropFactory.sol | * ____________________________________________________________________________________________________________________ -->MODULES @dev (function) updateAntiSybilOffOnModules Allow platform admin to turn off anti-sybil protection on modules --------------------------------------------------------------------------------------------------------------------- @param moduleAddresses_ An array of module addresses --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/ | function updateAntiSybilOffOnModules(
address[] calldata moduleAddresses_
) external onlyPlatformAdmin {
for (uint256 i = 0; i < moduleAddresses_.length; i++) {
IPrimarySaleModule(moduleAddresses_[i]).setAntiSybilOff();
}
emit ModuleAntiSybilOff(moduleAddresses_);
}
| 3,107,458 | [
1,
21157,
21157,
21157,
21157,
21157,
21157,
21157,
7198,
28524,
4766,
5411,
15431,
12194,
55,
225,
261,
915,
13,
1089,
14925,
77,
10876,
70,
330,
7210,
1398,
7782,
377,
7852,
4072,
3981,
358,
7005,
3397,
30959,
17,
9009,
70,
330,
17862,
603,
4381,
8879,
9634,
553,
225,
1605,
7148,
67,
4202,
1922,
526,
434,
1605,
6138,
8879,
9634,
553,
389,
21157,
21157,
21157,
21157,
21157,
21157,
21157,
7198,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1089,
14925,
77,
10876,
70,
330,
7210,
1398,
7782,
12,
203,
565,
1758,
8526,
745,
892,
1605,
7148,
67,
203,
225,
262,
3903,
1338,
8201,
4446,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1605,
7148,
27799,
2469,
31,
277,
27245,
288,
203,
1377,
467,
6793,
30746,
3120,
12,
2978,
7148,
67,
63,
77,
65,
2934,
542,
14925,
77,
10876,
70,
330,
7210,
5621,
203,
565,
289,
203,
565,
3626,
5924,
14925,
77,
10876,
70,
330,
7210,
12,
2978,
7148,
67,
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
] |
./partial_match/1/0x4cBf4E44FFf323890c16d4fecB00B1105a7ffA5b/sources/BoostCoin.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Boost", "BOOST") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyBoostLaunchFee = 30;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellBoostLaunchFee = 30;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1000000000 * 1e18;
maxTransactionAmount = totalSupply * 100 / 100;
maxWallet = totalSupply * 100 / 100;
swapTokensAtAmount = totalSupply * 1 / 10000;
buyBoostLaunchFee = _buyBoostLaunchFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyBoostLaunchFee + buyLiquidityFee + buyDevFee;
sellBoostLaunchFee = _sellBoostLaunchFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellBoostLaunchFee + sellLiquidityFee + sellDevFee;
BoostLaunchWallet = address(owner());
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
| 15,708,355 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
26653,
3113,
315,
5315,
4005,
7923,
288,
203,
540,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
540,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
540,
203,
3639,
2254,
5034,
389,
70,
9835,
26653,
9569,
14667,
273,
5196,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
14667,
273,
374,
31,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface IBeethovenxMasterChef {
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
function harvest(uint256 _pid, address _to) external;
function deposit(
uint256 _pid,
uint256 _amount,
address _to
) external;
function pendingBeets(uint256 _pid, address _user)
external
view
returns (uint256 pending);
function withdrawAndHarvest(
uint256 _pid,
uint256 _amount,
address _to
) external;
function userInfo(uint256 _pid, address _user)
external
view
returns (UserInfo memory);
}
interface IBeethovenVault {
enum SwapKind {
GIVEN_IN,
GIVEN_OUT
}
enum JoinKind {
INIT,
EXACT_TOKENS_IN_FOR_BPT_OUT,
TOKEN_IN_FOR_EXACT_BPT_OUT,
ALL_TOKENS_IN_FOR_EXACT_BPT_OUT
}
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
address assetIn;
address assetOut;
uint256 amount;
bytes userData;
}
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
struct JoinPoolRequest {
address[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
function getPoolTokens(bytes32 poolId)
external
view
returns (
address[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
}
/**
* @dev Simple contract that helps to compound farming of a specific balancer pool
* investment. The contract itself must hold the initial LP, farmed token (BEETS),
* or base token (wFTM).
*/
contract MonolithAutoCompounder is Ownable {
using SafeERC20 for IERC20;
uint256 private immutable pid = 37; // this is the masterchef pool id
IBeethovenxMasterChef private immutable beetsChef =
IBeethovenxMasterChef(0x8166994d9ebBe5829EC86Bd81258149B87faCfd3);
IBeethovenVault private immutable beetsVault =
IBeethovenVault(0x20dd72Ed959b6147912C2e529F0a0C651c33c9ce);
IERC20 private immutable beets = IERC20(0xF24Bcf4d1e507740041C9cFd2DddB29585aDCe1e);
IERC20 private immutable wftm = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IERC20 private immutable bptmnlt = IERC20(0xa216AA5d67Ef95DdE66246829c5103C7843d1AAB);
bytes32 private immutable beetsSwapPoolId =
0xcde5a11a4acb4ee4c805352cec57e236bdbc3837000200000000000000000019; // BEETS-wFTM pool
bytes32 private immutable monolithPoolId =
0xa216aa5d67ef95dde66246829c5103c7843d1aab000100000000000000000112; // MAI-wsEXOD-gOHM-EXOD-wFTM
/****** VIEW METHODS ******/
function beetsBalance() public view returns (uint256) {
return beets.balanceOf(address(this));
}
function lpBalance() public view returns (uint256) {
return bptmnlt.balanceOf(address(this));
}
function pendingBeets() public view returns (uint256) {
return beetsChef.pendingBeets(pid, address(this));
}
function wFTMBalance() public view returns (uint256) {
return wftm.balanceOf(address(this));
}
/****** OPERATIONS ******/
/**
* @dev It's rather simple:
*
* 1) First we harvest our BEETs from the MasterChef farm
* 2) Then we swap the BEETs for wFTM
* 3) Then we invest the wFTM back in the pool (single-asset style)
* 4) Then we deposit the resulting LP back into the MasterChef farm
*/
function compound() public {
_harvest();
_swapBeetsForwFTM();
_joinPool();
_farmBeets();
}
/**
* @dev Pulls everything out of the contract
*/
function withdraw() public onlyOwner {
_unfarmBeets();
_withdraw(wftm);
_withdraw(beets);
_withdraw(bptmnlt);
_withdrawNative();
}
/**
* @dev Pulls the balance of a specific token out of the contract
*/
function withdraw(address token) public onlyOwner {
_withdraw(IERC20(token));
}
/**
* @dev Pulls the native balance out of the contract
*/
function withdrawNative() public onlyOwner {
_withdrawNative();
}
/****** INTERNAL METHODS ******/
function _withdraw(IERC20 token) internal {
if (token.balanceOf(address(this)) != 0) {
token.transfer(msg.sender, token.balanceOf(address(this)));
}
}
function _withdrawNative() internal {
if (address(this).balance != 0) {
payable(_msgSender()).transfer(address(this).balance);
}
}
function _farmBeets() internal {
uint256 balance = lpBalance();
if (balance != 0) {
bptmnlt.approve(address(beetsChef), lpBalance()); // approve the chef to use our lp
beetsChef.deposit(pid, balance, address(this)); // deposit the lp into the farm
}
}
function _harvest() internal {
if (beetsChef.pendingBeets(pid, address(this)) != 0) {
beetsChef.harvest(pid, address(this)); // harvest our beets
}
}
function _joinPool() internal {
uint256 balance = wFTMBalance();
if (balance != 0) {
wftm.approve(address(beetsVault), wFTMBalance()); // approve the vault to spend the wFTM we have
(address[] memory poolAssets, , ) = beetsVault.getPoolTokens(monolithPoolId);
uint256[] memory amountsIn = new uint256[](poolAssets.length);
for (uint256 i = 0; i < poolAssets.length; i++) {
if (poolAssets[i] == address(wftm)) {
amountsIn[i] = balance; // found our match, that's the one, insert our balance
}
}
// invest the wFTM into the pool
beetsVault.joinPool(
monolithPoolId,
address(this),
address(this),
IBeethovenVault.JoinPoolRequest({
assets: poolAssets,
maxAmountsIn: amountsIn,
userData: abi.encode(
IBeethovenVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT,
amountsIn,
0
),
fromInternalBalance: false
})
);
}
}
function _swapBeetsForwFTM() internal {
uint256 balance = beetsBalance();
if (balance != 0) {
beets.approve(address(beetsVault), beetsBalance()); // approve the vault to spend the beets we have
// swap the beets to wFTM using the simple swap mechanism
beetsVault.swap(
IBeethovenVault.SingleSwap({
poolId: beetsSwapPoolId,
kind: IBeethovenVault.SwapKind.GIVEN_IN,
assetIn: address(beets),
assetOut: address(wftm),
amount: beetsBalance(),
userData: ""
}),
IBeethovenVault.FundManagement({
sender: address(this),
fromInternalBalance: false,
recipient: payable(address(this)),
toInternalBalance: false
}),
0, // we will take whatever we can get
type(uint256).max
);
}
}
function _unfarmBeets() internal {
IBeethovenxMasterChef.UserInfo memory info = beetsChef.userInfo(
pid,
address(this)
);
if (info.amount != 0) {
beetsChef.withdrawAndHarvest(pid, info.amount, address(this)); // withdraw our lp from the farm
}
}
receive() external payable {}
}
| this is the masterchef pool id
| uint256 private immutable pid = 37; | 925,250 | [
1,
2211,
353,
326,
4171,
343,
10241,
2845,
612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
3238,
11732,
4231,
273,
18091,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./ICryptoMonks.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
* @dev OSMigration is bridges an Open Sea 1155 into a new 721
*/
contract OSMigration is ERC1155Holder, Ownable, ReentrancyGuard {
/**
* @dev total bridged NFTs
*/
uint32 public totalBridged;
/**
* received NFTs (not yet claimed and transformed into 721)
*/
uint256[] public idsReceived;
/**
* @dev received and successfully claimed (this contains newly 721 ids)
*/
uint16[] public idsBridged;
/**
* @dev in case something goes bad, to stop claiming
*/
bool public bridgingEnabled;
/**
* @dev keeps all the ids that are sent and the owners of them
*/
mapping(uint256 => address) public idsAndSenders;
mapping(address => uint256[]) public sendersAndIds;
/**
* @dev olds OS ids bridged
*/
mapping(address => uint256[]) public oldsIdsBridgedBySender;
bytes32 private merkleRoot;
/**
* @dev OpenSea Shared contract
*/
IERC1155 public osContract;
ICryptoMonks public migContract;
event ReceivedFromOS(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId, uint256 _amount);
event ReceivedFrom721(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId);
event Minted721(address indexed _sender, uint256 indexed _tokenId);
event ToggleBridging(bool _enabled);
event Transferred1155(address indexed _to, uint256 indexed _tokenId);
constructor() {}
/**
* @dev triggered by 1155 transfer only from openSea
*/
function onERC1155Received(
address _sender,
address _receiver,
uint256 _tokenId,
uint256 _amount,
bytes memory _data
) public override nonReentrant returns (bytes4) {
require(msg.sender == address(osContract), "Forbidden");
require(!bridgingEnabled, "Bridging is stopped");
triggerReceived1155(_sender, _tokenId);
emit ReceivedFromOS(_sender, _receiver, _tokenId, _amount);
return super.onERC1155Received(_sender, _receiver, _tokenId, _amount, _data);
}
/***********External**************/
/**
* @dev a user can claim a token based on a merkle proof that was precomputed and that is part of the
* merkleRoot structure
*/
function claim(
uint256 _oldId,
uint16 _newId,
bytes32 _leaf,
bytes32[] calldata _merkleProof
) external nonReentrant {
require(!bridgingEnabled, "Bridging is stopped");
//construct merkle node
bytes32 node = keccak256(abi.encodePacked(_oldId, _newId));
require(node == _leaf, "Leaf not matching the node");
require(MerkleProof.verify(_merkleProof, merkleRoot, _leaf), "Invalid proof.");
require(idsAndSenders[_oldId] == msg.sender, "Not owner of OS id");
totalBridged++;
idsBridged.push(_newId);
oldsIdsBridgedBySender[msg.sender].push(_oldId);
mintOnClaiming(msg.sender, _newId);
}
/**
* @dev owner minting 721
*/
function mint721(uint16 _tokenId, address _to) external onlyOwner {
require(_to != address(0), "Mint to address 0");
require(!migContract.exists(_tokenId), "Token exists");
if (migContract.exists(_tokenId) && migContract.ownerOf(_tokenId) == address(this)) {
migContract.safeTransferFrom(address(this), _to, _tokenId);
return;
}
_mint721(_tokenId, _to);
}
/**
* @dev transfer MIG 721 from bridge in case token gets stuck or someone is sending by mistake
*/
function transfer721(uint256 _tokenId, address _owner) external onlyOwner {
require(_owner != address(0), "Can not send to address 0");
migContract.safeTransferFrom(address(this), _owner, _tokenId);
}
/***********Private**************/
/**
* @dev minting 721 to the owner
*/
function _mint721(uint16 _tokenId, address _owner) private {
migContract.mint(_owner, uint16(_tokenId));
emit Minted721(_owner, _tokenId);
}
/**
* @dev update params once we receive a transfer from 1155
* the sender can not be address(0) and tokenId needs to be allowed
*/
function triggerReceived1155(address _sender, uint256 _tokenId) internal {
require(_sender != address(0), "Update from address 0");
idsReceived.push(_tokenId);
idsAndSenders[_tokenId] = _sender;
sendersAndIds[_sender].push(_tokenId);
}
/**
* @dev when receive token from OS, it mints a 721
*/
function mintOnClaiming(address _sender, uint16 _tokenId) internal returns (bool) {
require(_sender != address(0), "Can not mint to address 0");
require(_tokenId != 0, "New token id !exists");
require(!migContract.exists(_tokenId), "Token already minted");
migContract.mint(_sender, _tokenId);
emit Minted721(_sender, _tokenId);
return true;
}
/***********Setters**************/
/**
* @dev sets 721 token
*/
function setMIGContract(address _contract) external onlyOwner {
require(_contract != address(0), "_contract !address 0");
migContract = ICryptoMonks(_contract);
}
/**
* @dev sets OS token
*/
function setOSContract(address _contract) external onlyOwner {
require(_contract != address(0), "_contract !address 0");
osContract = IERC1155(_contract);
}
/**
* @dev sets merkle root, should be called only once
*/
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
/***********Views**************/
/**
* @dev check a OS token balance
*/
function checkBalance(address _collector, uint256 _tokenId) external view returns (uint256) {
require(_collector != address(0), "_collector is address 0");
return osContract.balanceOf(_collector, _tokenId);
}
/**
* @dev get the ids already transferred by a collector
*/
function getTransferredByCollector(address _collector) external view returns (uint256[] memory) {
require(_collector != address(0), "_collector is address 0");
return sendersAndIds[_collector];
}
/**
* @dev get the ids that were bridged by collector
*/
function getBridgedByCollector(address _collector) external view returns (uint256[] memory) {
require(_collector != address(0), "_collector is address 0");
return oldsIdsBridgedBySender[_collector];
}
/***********Getters**************/
/**
* @dev get merkle root just by the owner
*/
function getMerkleRoot() external view onlyOwner returns (bytes32) {
return merkleRoot;
}
/**
* @dev get total transfer count
*/
function getTokenBridgedCount() external view returns (uint128) {
return totalBridged;
}
/**
* @dev get bridged ids (claimed already), this will be the new 721 ids
*/
function getBridgedTokens() external view returns (uint16[] memory) {
return idsBridged;
}
/**
* @dev get ids of tokens that were transfered to the bridge
*/
function getIdsTransfered() external view returns (uint256[] memory) {
return idsReceived;
}
/**
* @dev get 721 contract address
*/
function getMIGContract() external view returns (address) {
return address(migContract);
}
/**
* @dev get OpenSea contract address
*/
function getOSContract() external view returns (address) {
return address(osContract);
}
/***********Emergency**************/
/**
* @dev transfer MIG 1155 from bridge in case token gets stuck or someone is sending by mistake
*/
function transfer1155(uint256 _tokenId, address _owner) external onlyOwner nonReentrant {
require(_owner != address(0), "Can not send to address 0");
osContract.safeTransferFrom(address(this), _owner, _tokenId, 1, "");
emit Transferred1155(_owner, _tokenId);
}
/**
* @dev can enable/disable claiming and bridging
*/
function toggleBridging(bool _enabled) external onlyOwner {
bridgingEnabled = _enabled;
emit ToggleBridging(_enabled);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::;'............,::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::;,''''.............''''';:::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::;;'. .lxxxxxxxxxxxx; .;;:::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::'..',,,,:::::::::::::;,,,,...,::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::;....',;;;;;;;;;;;;;;;;;;;;;;,'...'::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::,.';:coodddddddddddddddddddddddddol:,.';:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::. .d0000OkkkOKXXXXKXXXXXKK0kkkk0KXXK: .,:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::;;..'d0KKOo::,cOXXXXXXXXXXXKxc:;;dKXXKc..,;;:::::::::::::::::::::::::::::
::::::::::::::::::::::::::,..;kOKKKKKOkc.;kXXXXXKXXXXXX0Od,.oKXXKOxl. ':::::::::::::::::::::::::::::
::::::::::::::::::::::::'..:lkKXXXXXKKKOxk0XXXXXXXXXXXXKK0xxOXXXKKKd. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::. .d00KXXXXXKXXXXXXXXXXXXXXXXXXXXXXXXXXXXKXx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::'..:lxKKXXXXXXXXXXXXXXXXXXXXXXXKXXXXXXXXXKXx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::::,. ;O0KXXXXXXXXXXXXXXXX0OOOOOOOOOOOOOOO0Xx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::::,. ;O0KXXXXXXXXXXXKKKKKl...............lKx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::::;,''';x0KXXXXXXXXKOxo;,;::c::ccc::cc:;,,,,'';:::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::. .d00XXXXXXXXK0kxlc;,,,,,,,,,,,,,'.. .,:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::'..:oxKKXXXXXXXXXXXKo,,''''''',''. ..;:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::,. ;dk0KKXXXXXXXXXXKKKKKKKKKKOxl. .;:::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::;....'x00KXXXXXXXXXKXXXXXXK0Oc....'::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::;'''',,,''o0KKXXXXXXXXXXXXKKk;'',,'''.';:::::::::::::::::::::::::::::::
::::::::::::::::::::::::::;,'''';::c:,',;lkKKKKKKKKK0KKd:;'';cc::,''',;:::::::::::::::::::::::::::::
::::::::::::::::::::::::::;'.'',;:ccccc,.'okxxkxkxxxkkx:..:cccc::;'''.,:::::::::::::::::::::::::::::
::::::::::::::::::::::;;;;;;;,..',;:cccccccccccccccccccccccccc:,,'..,;;;;;;:::::::::::::::::::::::::
:::::::::::::::::::::;'......','..',;:cccccccccccccccccccccc:;,..','.......,::::::::::::::::::::::::
::::::::::::::::;'......,;;;;::::;,...',;:cc;''''''',:c:;;''...,;:::;;;;,''....',:::::::::::::::::::
::::::::::::::::;.....,;:ccccccccc:,,,,'''',''',,'''',,'.',,,,;cccccccccc:;,....,:::::::::::::::::::
::::::::::::::;;,..',;ccccccccccccccccc;''..';:cc:::,...',:cccccccccccccccc:;,..',;:::::::::::::::::
::::::::::::::,....,ccccccc::cccccccccccc:'.,ccccccc:'.;ccccc:cccccc::ccccccc:.....;::::::::::::::::
::::::::::::::,..'';cccccc:'.',,:cccccccccc:cccccccccc:ccccc;,;:ccc:'.;cccccc:,'...;::::::::::::::::
:::::::::::;'....;:ccccccc:...',:ccccccccccccccccccccccccccc;',:ccc:..,ccccccc::'....,::::::::::::::
:::::::::::;....':cccccccc:...',:ccccccccccccccccccccccccccc:;;;;:c:..,ccccccccc,....,::::::::::::::
:::::::::::;..',;:cccccccc:..',;cccccccccccccccccccccccccccccc:,',:;..,ccccccccc:;,..,::::::::::::::
:::::::::::;..,ccccccccccc:..,cccccccccccccccccccccccccccccccc:;,,''..,:cccccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc:,'..,cccccccccccccccccccccccccccccccccc:;''...,;:cccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc;''..,ccccccccccccccccccccccccccccccccccc;''...',:cccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc;....;ccccccccccccccccccccccccccccccccccc;''....':cccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc,..'';ccccccccccccccccccccccccccccccccccc:,,,'...:cccccccc:..,::::::::::::::
:::::::::::;..,cccccccc:,..'';ccccccccccccccccccccccccccccccccccccc:;,...;cccccccc:..,::::::::::::::
:::::::::::;..,cccccc:;,...',;ccccccccccccccccccccccccccccccccccccccc:,...';cccccc:..,::::::::::::::
:::::::::::;..,cccccc:,'...;:cccccccccccccccccccccccccccccccccccccc:,'.....,;:cccc:..,::::::::::::::
:::::::::::;..'::cccc:'...',;:ccccccccccccccccccccccccccccccccc:;;;,''....',::cccc:..,::::::::::::::
:::::::::::;...,;:ccc:...'''';cccccccccccccccccccccccccccccccc:,''''''...'';cccccc:..,::::::::::::::
crypto monks.
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
abstract contract ICryptoMonks is Ownable, IERC721 {
function mint(address _owner, uint256 _tokenId) external virtual;
function exists(uint256 _tokenId) external view virtual returns (bool);
function getMaxSupply() external virtual returns (uint256);
function tokensOfOwner(address _owner) external view virtual returns (uint256[] memory);
} | * @dev These functions deal with verification of Merkle Trees proofs. The proofs can be generated using the JavaScript library Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. See `test/utils/cryptography/MerkleProof.test.js` for some examples./ | library MerkleProof {
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
}
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
}
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
}
} else {
return computedHash == root;
}
| 26,744 | [
1,
29690,
4186,
10490,
598,
11805,
434,
31827,
399,
5312,
14601,
87,
18,
1021,
14601,
87,
848,
506,
4374,
1450,
326,
11905,
5313,
3609,
30,
326,
24641,
4886,
1410,
506,
417,
24410,
581,
5034,
471,
3082,
9602,
1410,
506,
3696,
18,
2164,
1375,
3813,
19,
5471,
19,
22784,
15669,
19,
8478,
15609,
20439,
18,
3813,
18,
2924,
68,
364,
2690,
10991,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
31827,
20439,
288,
203,
565,
445,
3929,
12,
203,
3639,
1731,
1578,
8526,
3778,
14601,
16,
203,
3639,
1731,
1578,
1365,
16,
203,
3639,
1731,
1578,
7839,
203,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
8470,
2310,
273,
7839,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
14601,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1731,
1578,
14601,
1046,
273,
14601,
63,
77,
15533,
203,
203,
5411,
309,
261,
20307,
2310,
1648,
14601,
1046,
13,
288,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
20307,
2310,
16,
14601,
1046,
10019,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
24207,
1046,
16,
8470,
2310,
10019,
203,
5411,
289,
203,
3639,
289,
203,
203,
565,
289,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
8470,
2310,
273,
7839,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
14601,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1731,
1578,
14601,
1046,
273,
14601,
63,
77,
15533,
203,
203,
5411,
309,
261,
20307,
2310,
1648,
14601,
1046,
13,
288,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
20307,
2310,
16,
14601,
1046,
10019,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
24207,
1046,
16,
8470,
2310,
10019,
203,
5411,
289,
2
] |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "./libs/LibAccess.sol";
import "./libs/LibStorage.sol";
import "./Types.sol";
import "hardhat/console.sol";
abstract contract BaseAccess {
using LibAccess for Types.AccessControl;
//bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant ADMIN_ROLE = 0xa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c21775;
//bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant PAUSER_ROLE = 0x65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a;
//bytes32 public constant RELAY_ROLE = keccak256("RELAY_ROLE");
bytes32 public constant RELAY_ROLE = 0x077a1d526a4ce8a773632ab13b4fbbf1fcc954c3dab26cd27ea0e2a6750da5d7;
//bytes32 public constant ACTION_ROLE = keccak256("ACTION_ROLE");
bytes32 public constant ACTION_ROLE = 0xd95061bdf0c43d77b6cbe1c15072292976244ec8d5012de75baa36e42da4625e;
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function hasRole(bytes32 role, address actor) public view returns (bool) {
return LibStorage.getAccessStorage().hasRole(role, actor);
}
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "Not admin");
_;
}
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Not pauser");
_;
}
modifier onlyRelay() {
require(hasRole(RELAY_ROLE, _msgSender()), "Not relay");
_;
}
modifier initializer() {
Types.InitControls storage ic = LibStorage.getInitControls();
require(ic.initializing || !ic.initialized, "Already initialized");
bool tlc = !ic.initializing;
if(tlc) {
ic.initializing = true;
ic.initialized = true;
}
_;
if(tlc) {
ic.initializing = false;
}
}
modifier nonReentrant() {
require(!LibStorage.getAccessStorage().reentrantFlag, "Attempting to re-enter function recursively");
LibStorage.getAccessStorage().reentrantFlag = true;
_;
LibStorage.getAccessStorage().reentrantFlag = false;
}
//================ MUTATIONS ===============/
function addRole(bytes32 role, address actor) public onlyAdmin {
_setupRole(role, actor);
}
function revokeRole(bytes32 role, address actor) public onlyAdmin {
LibStorage.getAccessStorage()._revokeRole(role, actor);
}
function _setupRole(bytes32 role, address actor) internal {
LibStorage.getAccessStorage()._addRole(role, actor);
}
function initAccess() internal initializer {
address o = _msgSender();
_setupRole(ADMIN_ROLE, o);
_setupRole(PAUSER_ROLE, o);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "../Types.sol";
library LibAccess {
function hasRole(Types.AccessControl storage ac, bytes32 role, address actor) external view returns (bool) {
return ac.roles[role][actor];
}
function _addRole(Types.AccessControl storage ac, bytes32 role, address actor) internal {
ac.roles[role][actor] = true;
}
function _revokeRole(Types.AccessControl storage ac, bytes32 role, address actor) internal {
delete ac.roles[role][actor];
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../Types.sol";
library LibStorage {
//keccak256("com.buidlhub.config.ConfigStorage");
bytes32 constant CONFIG_STORAGE_KEY = 0xf5b4be0a744c821d14f78bf26d55a308f420d78cebbfac103f2618fba32917b9;
//keccak256("com.buidlhub.access.AccessControls");
bytes32 constant ACCESS_STORAGE_KEY = 0x3a83b1278d351a40f18bb9e8e77896e8c1dc812ffaed5ea63e0e837a6dae57e9;
//keccak256("com.buidlhub.init.InitControls");
bytes32 constant INIT_STORAGE_KEY = 0xd59dd79cfd4373c6c6547848d91fc2ea67c8aec9053f7028828216c5af1d4741;
//keccak256("com.buidlhub.gastank.GasStorage");
bytes32 constant GAS_STORAGE_KEY = 0x8c89fc81d9ea4103ca01a6b8674fdaec22ec47acad49dcba52ad9c3d556ea075;
//============= STORAGE ACCESSORS ==========/
function getConfigStorage() internal pure returns (Types.Config storage cs) {
assembly { cs.slot := CONFIG_STORAGE_KEY }
}
function getAccessStorage() internal pure returns (Types.AccessControl storage acs) {
assembly { acs.slot := ACCESS_STORAGE_KEY }
}
function getInitControls() internal pure returns (Types.InitControls storage ic) {
assembly { ic.slot := INIT_STORAGE_KEY }
}
function getGasStorage() internal pure returns (Types.GasBalances storage gs) {
assembly { gs.slot := GAS_STORAGE_KEY }
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library Types {
struct TokenAmount {
IERC20 token;
uint112 amount;
}
//status of order. Only tracked on action from user/miners
enum OrderStatus {
UNDEFINED,
PENDING,
FILLED,
CANCELLED,
PENALIZED
}
enum OrderType {
EXACT_IN,
EXACT_OUT
}
struct Order {
//fee offered (120+128 = 248)
uint128 fee;
//the fee that needs to be paid to a target DEX in ETH
uint128 dexFee;
//trader that owns the order
address trader;
//the type of trade being made
OrderType orderType;
//token being offered
TokenAmount input;
//token wanted
TokenAmount output;
}
/**
* A trader's gas tank balance and any amount that's
* thawing waiting for withdraw.
*/
struct Gas {
//available balance used to pay for fees
uint112 balance;
//amount user is asking to withdraw after a that period expires
uint112 thawing;
//the block at which any thawing amount can be withdrawn
uint256 thawingUntil;
}
//============== CONFIG STATE =============/
struct Config {
//dev team address (120b)
address devTeam;
//min fee amount (128b, 248b chunk)
uint128 minFee;
//penalty a user faces for removing assets or
//allowances before a trade
uint128 penaltyFee;
//number of blocks to lock stake and order cancellations
uint8 lockoutBlocks;
}
//============== ACCESS STATE =============/
//storage structure of access controls
struct AccessControl {
bool reentrantFlag;
mapping(bytes32 => mapping(address => bool)) roles;
}
//============== INITIALIZATION STATE =============/
struct InitControls {
bool initialized;
bool initializing;
}
//=============== GAS TANK STATE =============/
struct GasBalances {
mapping(address => Gas) balances;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: 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: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "hardhat/console.sol";
import "../../Types.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../IDexRouter.sol";
import "../../BaseAccess.sol";
// @dev The ZrxRouter is used by settlement to execute orders through 0x
contract ZrxRouter is BaseAccess, IDexRouter {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
function initialize() public initializer {
BaseAccess.initAccess();
}
// @dev Executes a call to 0x to make fill the order
// @param order - contains the order details from the Smart Order Router
// @param orderCallData - abi encoded swapTarget address and data from 0x API
function fill(Types.Order calldata order, bytes calldata orderCallData)
external override returns (bool success, string memory failReason) {
//call data contains the target address and data to pass to it to execute
(address swapTarget, address allowanceTarget, bytes memory data) = abi.decode(orderCallData, (address,address,bytes));
console.log("Going to swap target", swapTarget);
console.log("Approving allowance for", allowanceTarget);
//Settlement transferred token input amount so we can swap
uint256 balanceBefore = order.output.token.balanceOf(address(this));
console.log("Balance of input token b4", balanceBefore);
//for protocols that require zero-first approvals
require(order.input.token.approve(allowanceTarget, 0));
//make sure 0x target has approval to spend this contract's tokens
require(order.input.token.approve(allowanceTarget, order.input.amount));
//execute the swap, forwarding any ETH fee if needed. The ETH fee was
//transferred to this contract by Settlement if it was needed
console.log("Swapping...");
(bool _success,) = swapTarget.call{value: order.dexFee, gas: gasleft()}(data);
if(!_success) {
console.log("Failed to swap");
return (false, "SWAP_CALL_FAILED");
}
//make sure we received tokens
uint256 balanceAfter = order.output.token.balanceOf(address(this));
uint256 diff = balanceAfter.sub(balanceBefore);
console.log("Balance received", diff);
require(diff >= order.output.amount, "Insufficient output amount");
if(!order.output.token.transfer(order.trader, diff)) {
console.log("Could not transfer tokens to trader");
return (false, "Failed to transfer funds to trader");
}
return (true,"");
}
// Payable fallback to allow this contract to receive protocol fee refunds.
receive() external payable {}
}
// 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: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./Types.sol";
/**
* Abstraction of DEX integration with simple fill function.
*/
interface IDexRouter {
/**
* Fill an order using the given call data details.
*/
function fill(Types.Order memory order, bytes calldata swapData) external returns (bool status, string memory failReason);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IDexRouter.sol";
import "./GasTank.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Types.sol";
contract Settlement is GasTank {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint128;
using SafeMath for uint;
using SafeERC20 for IERC20;
//============= EVENT DEFS =================/
event TraderPenalized(address indexed trader, uint256 penalty, uint256 gasPaid, string reason);
event SwapFailed(address indexed trader, uint gasPaid, string reason);
event SwapSuccess(address indexed trader,
address indexed executor,
uint inputAmount,
uint outputAmount,
uint fee,
uint gasPaid);
//============== CONSTANTS ==============/
//estimate gas usage for testing a user's deposit
uint256 constant GAS_ESTIMATE = 450_000;
//extra overhead for transferring funds
uint256 constant GAS_OVERHEAD = 60_000;
//gas needed after action executes
uint256 constant OP_GAS = 80_000;
struct BalTracking {
uint256 inBal;
uint256 outBal;
uint256 afterIn;
uint256 afterOut;
}
/**
* Fill an order using the given router and forwarded call data.
*/
function fill(Types.Order memory order, IDexRouter router, bytes calldata data) public onlyRelay nonReentrant {
uint256 startGas = gasleft();
//pre-trade condition checks
BalTracking memory _tracker = _preCheck(order);
//execute action
(bool success, string memory failReason) = performFill(order, router, data);
//post-trade condition check
_postCheck(order, _tracker, success);
//post-trade actions to transfer fees, etc.
_postActions(order, success, failReason, _tracker, startGas);
}
// @dev initialize the settlement contract
function initialize(Types.Config memory config) public initializer {
BaseConfig.initConfig(config);
}
// @dev whether the trader has gas funds to support order at the given gas price
function _hasFunds(Types.Order memory order, uint256 gasPrice) internal view returns (bool) {
require(order.fee >= LibStorage.getConfigStorage().minFee, "Order has insufficient fee");
uint256 gas = GAS_ESTIMATE.mul(gasPrice);
uint256 total = gas.add(order.fee)
.add(order.dexFee)
.add(LibStorage.getConfigStorage().penaltyFee);
bool b = this.hasEnoughGas(order.trader, total);
return b;
}
// @dev whether the trader has a token balance to support input side of order
function _hasTokens(Types.Order memory order) internal view returns (bool) {
bool b = order.input.token.balanceOf(order.trader) >= order.input.amount;
return b;
}
// @dev whether the trader has approved this contract to spend enought for order
function _canSpend(Types.Order memory order) internal view returns (bool) {
bool b = order.input.token.allowance(order.trader, address(this)) >= order.input.amount;
return b;
}
function _preCheck(Types.Order memory order) internal view returns (BalTracking memory) {
require(_hasFunds(order, tx.gasprice), "Insufficient gas tank funds");
require(_hasTokens(order), "Insufficient input token balance to trade");
require(_canSpend(order), "Insufficient spend allowance on input token");
//before balances
return BalTracking(
order.input.token.balanceOf(order.trader),
order.output.token.balanceOf(order.trader),
0,0
);
}
function _preActions(Types.Order memory order, IDexRouter router) internal {
//transfer input tokens to router so it can perform dex trades
order.input.token.safeTransferFrom(order.trader, address(router), order.input.amount);
if(order.dexFee > 0) {
//pay ETH fee to DEX if rquired
payable(address(router)).transfer(order.dexFee);
}
}
function performFill(Types.Order memory order, IDexRouter router, bytes calldata data) internal returns (bool success, string memory failReason) {
//execute action. This is critical that we use our own internal call to actually
//perform swap inside trycatch. This way, transferred funds to script are
//reverted if swap fails
try this._trySwap{
gas: gasleft().sub(OP_GAS)
}(order, router, data) returns (bool _success, string memory _failReason) {
return (_success, _failReason);
} catch Error(string memory err) {
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
}
function _trySwap(Types.Order calldata order, IDexRouter router, bytes calldata data) external returns (bool success, string memory failReason) {
require(msg.sender == address(this), "Can only be called by settlement contract");
_preActions(order, router);
(bool s, string memory err) = router.fill(order, data);
if(!s) {
revert(err);
}
return (s, err);
}
function _postCheck(Types.Order memory order, BalTracking memory _tracking, bool success) internal view {
_tracking.afterIn = order.input.token.balanceOf(order.trader);
if(!success) {
//have to revert if funds were not refunded in order to roll everything back.
//in this case, the router is at fault, which is Dexible's fault and therefore
//Dexible relay address should eat the cost of failure
console.log("Input bal b4", _tracking.inBal);
console.log("Input bal after", _tracking.afterIn);
require(_tracking.afterIn == _tracking.inBal, "failed trade action did not refund input funds");
} else {
_tracking.afterOut = order.output.token.balanceOf(order.trader);
//if the in/out amounts don't line up, then transfers weren't made properly in the
//router.
console.log("Trader token balance before swap", _tracking.outBal);
console.log("New trader balance", _tracking.afterOut);
require(_tracking.afterOut.sub(_tracking.outBal) >= order.output.amount, "Trade action did not transfer output tokens to trader");
require(_tracking.afterIn < _tracking.inBal, "Input tokens not used!");
require(_tracking.inBal.sub(_tracking.afterIn) <= order.input.amount, "Used too many input tokens");
}
}
function _postActions(Types.Order memory order,
bool success,
string memory failReason,
BalTracking memory _tracking,
uint startGas) internal {
if(!success) {
//pay relayer back their gas but take no fee
uint256 totalGasUsed = startGas.sub(gasleft()).add(GAS_OVERHEAD);
uint256 gasFee = totalGasUsed.mul(tx.gasprice);
deduct(order.trader, uint112(gasFee));
//tell trader it failed
emit SwapFailed(order.trader, gasFee, failReason);
//console.log("Paying gas", gasFee);
_msgSender().transfer(gasFee);
} else {
//otherwise, pay fee and gas
uint256 totalGasUsed = startGas.sub(gasleft()).add(GAS_OVERHEAD);
uint256 gasFee = totalGasUsed.mul(tx.gasprice);
deduct(order.trader, uint112(gasFee.add(order.fee).add(order.dexFee)));
_msgSender().transfer(gasFee);
payable(LibStorage.getConfigStorage().devTeam).transfer(order.fee);
console.log("Successful swap");
emit SwapSuccess(order.trader,
_msgSender(),
_tracking.inBal.sub(_tracking.afterIn),
_tracking.afterOut.sub(_tracking.outBal),
order.fee.add(order.dexFee),
gasFee);
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./BaseConfig.sol";
import "./libs/LibGas.sol";
abstract contract GasTank is BaseConfig {
using LibGas for Types.GasBalances;
//========== VIEWS =============/
/**
* Determine how much of the gas tank balance is available for withdraw after having
* waited a sufficient thaw period.
*/
function availableGasForWithdraw(address owner) external view returns (uint256) {
return LibStorage.getGasStorage().availableForWithdraw(owner);
}
/**
* Determine the amount of eth available to use to pay for fees. This includes
* any thawing funds that have not yet reached the thaw expiration block.
*/
function availableForUse(address owner) external view returns (uint256) {
return LibStorage.getGasStorage().availableForUse(owner);
}
/**
* Determine the amount of funds actively awaiting the thaw period.
*/
function thawingFunds(address owner) external view returns (uint256) {
return LibStorage.getGasStorage().thawingFunds(owner);
}
// @dev check whether the given holder has enough gas to pay the bill
function hasEnoughGas(address holder, uint256 due) external view returns (bool) {
return LibStorage.getGasStorage().availableForUse(holder) >= due;
}
// ========= MUTATIONS =============/
/**
* Deposit funds into the gas tank
*/
function depositGas() external payable {
require(msg.value > 0, "No funds provided for gas deposit");
LibStorage.getGasStorage().deposit(_msgSender(), uint112(msg.value));
}
/**
* Request that funds be thawed and prepared for withdraw after thaw period expires.
*/
function requestWithdrawGas(uint112 amount) external {
require(amount > 0, "Cannot withdraw 0 amount");
LibStorage.getGasStorage().thaw(_msgSender(),amount);
}
/**
* Withdraw fully thawed funds.
*/
function withdrawGas(uint112 amount) external nonReentrant {
require(amount > 0, "Cannot withdraw 0 amount");
LibStorage.getGasStorage().withdraw(_msgSender(), amount);
_msgSender().transfer(amount);
}
/**
* Deduct the given amount from a trader's available funds.
*/
function deduct(address trader, uint112 amount) internal {
LibStorage.getGasStorage().deduct(trader, amount);
}
}
// 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: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./Types.sol";
import "./libs/LibStorage.sol";
import "./libs/LibConfig.sol";
import "./BaseAccess.sol";
abstract contract BaseConfig is BaseAccess {
using LibConfig for Types.Config;
/**
* Initialize config settings. This is called at initialization time when contracts
* are first deployed.
*/
function initConfig(Types.Config memory config) internal {
LibStorage.getConfigStorage().store(config);
BaseAccess.initAccess();
}
/**
* Get the current configuration struct
*/
function getConfig() external view returns (Types.Config memory) {
return LibStorage.getConfigStorage().copy();
}
//============== VIEWS ================/
/**
* Get the dev team wallet/multi-sig address
*/
function getDevTeam() external view returns (address) {
return LibStorage.getConfigStorage().devTeam;
}
/**
* Get the number of blocks to wait before trader can withdraw gas tank funds
* marked for withdraw.
*/
function getLockoutBlocks() external view returns (uint8) {
return LibStorage.getConfigStorage().lockoutBlocks;
}
/**
* Get the minimum fee required for all orders
*/
function getMinFee() external view returns (uint128) {
return LibStorage.getConfigStorage().minFee;
}
/**
* Get the penalty fee to asses when trader removes tokens or funds after
* Dexible submits orders on-chain.
*/
function getPenaltyFee() external view returns (uint128) {
return LibStorage.getConfigStorage().penaltyFee;
}
//=============== MUTATIONS ============/
/**
* Set the current configuration as a bulk setting
*/
function setConfig(Types.Config memory config) public onlyAdmin {
LibStorage.getConfigStorage().store(config);
}
/**
* Set the dev team wallet/multi-sig address
*/
function setDevTeam( address team) external onlyAdmin {
LibStorage.getConfigStorage().devTeam = team;
}
/**
* Set the number of blocks to wait before thawed withdraws are allowed
*/
function setLockoutBlocks(uint8 blocks) external onlyAdmin {
LibStorage.getConfigStorage().lockoutBlocks = blocks;
}
/**
* Set the minimum fee for an order execution
*/
function setMinFee(uint128 fee) external onlyAdmin {
LibStorage.getConfigStorage().minFee = fee;
}
/**
* Set the penalty assessed when a user removes tokens or gas tank funds
*/
function setPenaltyFee(uint128 fee) external onlyAdmin {
LibStorage.getConfigStorage().penaltyFee = fee;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./LibStorage.sol";
import "../Types.sol";
import "hardhat/console.sol";
library LibGas {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
//emitted when gas is deposited
event GasDeposit(address indexed trader, uint112 amount);
//emitted when gas is marked for thaw period
event GasThawing(address indexed trader, uint112 amount);
//emitted when gas is withdrawn
event GasWithdraw(address indexed trader, uint112 amount);
// ============ VIEWS ==============/
/**
* Determine how much of an account's gas tank balance can be withdrawn after a thaw period
* has expired.
*/
function availableForWithdraw(Types.GasBalances storage gs, address account) external view returns (uint256) {
Types.Gas storage gas = gs.balances[account];
if(gas.thawingUntil > 0 && gas.thawingUntil <= block.number) {
return gas.thawing;
}
return 0;
}
/**
* Determine how much of an account's gas tank balance is availble to pay for fees
*/
function availableForUse(Types.GasBalances storage gs, address account) internal view returns (uint256) {
Types.Gas storage gas = gs.balances[account];
//console.log("Current block", block.number);
//console.log("Expired block", gas.thawingUntil);
if(gas.thawingUntil > 0 && gas.thawingUntil > block.number) {
//we have some funds thawing, which are still usable up until its expiration block
return gas.balance.add(gas.thawing);
}
//otherwise we can only use balance funds
return gas.balance;
}
/**
* Determine how much of an account's gas tank is waiting for a thaw period before it's
* available for withdraw
*/
function thawingFunds(Types.GasBalances storage gs, address account) internal view returns (uint256) {
Types.Gas storage gas = gs.balances[account];
//so long as the thaw period hasn't expired
if(gas.thawingUntil > 0 && gas.thawingUntil > block.number) {
//the funds are not available for withdraw
return gas.thawing;
}
return 0;
}
/**
* Determine if the account has enough in the tank to pay for estimated usage for given price
*/
function hasEnough(Types.GasBalances storage gs, address account, uint256 estimateUse, uint112 price) internal view returns (bool) {
require(price > 0, "Cannot estimate with 0 gas price");
require(estimateUse > 0, "Cannot estimate with 0 gas use");
uint112 amount = uint112(estimateUse.mul(price));
uint112 _total = uint112(availableForUse(gs, account));
return _total > amount;
}
// ============ MUTATIONS ==========/
/**
* Deposit funds into the gas tank.
*/
function deposit(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
//add incoming amount to the current balance
gas.balance = uint112(gas.balance.add(amount));
//tell the world about it
emit GasDeposit(account, amount);
}
/**
* Mark
*/
function thaw(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
//following will fail if amount is more than gas tank balance so no need
//to check and waste cycles
gas.balance = uint112(gas.balance.sub(amount));
//add to thawing total
gas.thawing = uint112(gas.thawing.add(amount));
//set withdraw to next lockout period blocks. Note that this locks up any
//previously thawed funds as well.
gas.thawingUntil = block.number.add(LibStorage.getConfigStorage().lockoutBlocks);
//tell the world about it
emit GasThawing(account, amount);
}
/**
* Try to withdraw any fully thawed funds
*/
function withdraw(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
require(gas.thawingUntil > 0, "Must first request a withdraw");
require(gas.thawingUntil < block.number, "Cannot withdraw inside lockout period");
//this will fail if amount is more than thawing amount so no need to check amount
gas.thawing = uint112(gas.thawing.sub(amount));
}
/**
* Deduct from the trader's balance after an action is complete
*/
function deduct(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
if(amount == 0) {
return;
}
uint112 _total = uint112(availableForUse(gs, account));
require(_total > amount, "Insufficient gas to pay amount");
if(gas.balance >= amount) {
//if the balance has enough to pay, just remove it
gas.balance = uint112(gas.balance.sub(amount));
} else {
//otherwise, this means there are thawing funds that have not fully thawed yet
//but are stll available for use. So use them.
gas.thawing = uint112(gas.thawing.sub(amount.sub(gas.balance)));
gas.balance = 0;
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../Types.sol";
library LibConfig {
function store(Types.Config storage cs, Types.Config memory config) public {
cs.devTeam = config.devTeam;
cs.minFee = config.minFee;
cs.penaltyFee = config.penaltyFee;
cs.lockoutBlocks = config.lockoutBlocks;
require(cs.devTeam != address(0), "Invalid dev team address");
}
function copy(Types.Config storage config) public view returns(Types.Config memory) {
Types.Config memory cs;
cs.devTeam = config.devTeam;
cs.minFee = config.minFee;
cs.penaltyFee = config.penaltyFee;
cs.lockoutBlocks = config.lockoutBlocks;
require(cs.devTeam != address(0), "Invalid dev team address");
return cs;
}
//============== VIEWS ================/
function getDevTeam(Types.Config storage _config) external view returns (address) {
return _config.devTeam;
}
function getLockoutBlocks(Types.Config storage _config) external view returns (uint8) {
return _config.lockoutBlocks;
}
function getMinFee(Types.Config storage _config) external view returns (uint128) {
return _config.minFee;
}
function getPenaltyFee(Types.Config storage _config) external view returns (uint128) {
return _config.penaltyFee;
}
//=============== MUTATIONS ============/
function setDevTeam(Types.Config storage _config, address team) external{
_config.devTeam = team;
}
function setLockoutBlocks(Types.Config storage _config, uint8 blocks) external{
_config.lockoutBlocks = blocks;
}
function setMinFee(Types.Config storage _config, uint128 fee) external{
_config.minFee = fee;
}
function setPenaltyFee(Types.Config storage _config, uint128 fee) external{
_config.penaltyFee = fee;
}
}
// 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: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../Types.sol";
import "../../IDexRouter.sol";
import "../../BaseAccess.sol";
import "../../interfaces/uniswap/IPair.sol";
import "../../interfaces/uniswap/IPairFactory.sol";
import "../../interfaces/uniswap/IV2Router.sol";
import "hardhat/console.sol";
contract UniswapDex is BaseAccess, IDexRouter{
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
uint256 constant public MAX_INT_TYPE = type(uint256).max;
IPairFactory factory;
IV2Router router;
function initialize(IPairFactory uniFactory, IV2Router v2Router) public initializer {
BaseAccess.initAccess();
factory = uniFactory;
router = v2Router;
}
function revokeTokenAllowance(IERC20 token) external onlyAdmin {
token.approve(address(router), 0);
}
function fill(Types.Order calldata order, bytes calldata data) external override returns (bool success, string memory failReason) {
address[] memory path = abi.decode(data, (address[]));
verifyRouterAllowance(order.input.token, order.input.amount);
if(order.orderType == Types.OrderType.EXACT_IN) {
//console.log("Expecting output amount", order.output.amount);
try router.swapExactTokensForTokens{
gas: gasleft()
}(
order.input.amount,
order.output.amount,
path,
order.trader,
block.timestamp+1
)
{
success = true;
} catch Error(string memory err) {
//console.log("Problem in fill", err);
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
} else {
try router.swapTokensForExactTokens{
gas: gasleft()
}(
order.output.amount,
order.input.amount,
path,
order.trader,
block.timestamp + 1
)
{
success = true;
} catch Error(string memory err) {
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
}
}
function verifyRouterAllowance(IERC20 token, uint256 minAmount) internal {
uint allow = token.allowance(address(this), address(router));
if(allow < minAmount) {
token.approve(address(router), minAmount);
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
interface IPair {
function addLiquid(uint amount0, uint amount1) external;
function getReserves() external view returns (uint, uint, uint);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
interface IPairFactory {
function createPair(address a, address b) external returns (address);
function getPair(address tokenA, address tokenB) external view returns (address);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IV2Router {
function addLiquidity(IERC20 tokenA, uint aAmount, IERC20 tokenB, uint bAmount)
external
returns (address);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
external
view
returns (uint amount);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
external
view
returns (uint amount);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../Types.sol";
import "../../IDexRouter.sol";
import "../../BaseAccess.sol";
import "../../interfaces/uniswap/IPair.sol";
import "../../interfaces/uniswap/IPairFactory.sol";
import "../../interfaces/uniswap/IV2Router.sol";
import "hardhat/console.sol";
contract SushiswapDex is BaseAccess, IDexRouter{
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
uint256 constant public MAX_INT_TYPE = type(uint256).max;
IPairFactory factory;
IV2Router router;
function initialize(IPairFactory uniFactory, IV2Router v2Router) public initializer {
BaseAccess.initAccess();
factory = uniFactory;
router = v2Router;
}
function revokeTokenAllowance(IERC20 token) external onlyAdmin {
token.approve(address(router), 0);
}
function fill(Types.Order calldata order, bytes calldata data) external override returns (bool success, string memory failReason) {
address[] memory path = abi.decode(data, (address[]));
verifyRouterAllowance(order.input.token, order.input.amount);
if(order.orderType == Types.OrderType.EXACT_IN) {
console.log("Expecting output amount", order.output.amount);
console.log("Given input amount", order.input.amount);
try router.swapExactTokensForTokens{
gas: gasleft()
}(
order.input.amount,
order.output.amount,
path,
order.trader,
block.timestamp+1
)
{
success = true;
} catch Error(string memory err) {
console.log("Problem in Sushiswap", err);
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
} else {
try router.swapTokensForExactTokens{
gas: gasleft()
}(
order.output.amount,
order.input.amount,
path,
order.trader,
block.timestamp + 1
)
{
success = true;
} catch Error(string memory err) {
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
}
}
function verifyRouterAllowance(IERC20 token, uint256 minAmount) internal {
uint allow = token.allowance(address(this), address(router));
if(allow < minAmount) {
token.approve(address(router), minAmount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Proxy.sol";
import "../utils/Address.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./UpgradeableProxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is UpgradeableProxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin_);
}
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _admin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external virtual ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin {
_upgradeTo(newImplementation);
Address.functionDelegateCall(newImplementation, data);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/Ownable.sol";
import "./TransparentUpgradeableProxy.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev 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: Unlicense
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/proxy/ProxyAdmin.sol";
contract DeploymentAdmin is ProxyAdmin {
}
| * Withdraw fully thawed funds./ | function withdrawGas(uint112 amount) external nonReentrant {
require(amount > 0, "Cannot withdraw 0 amount");
LibStorage.getGasStorage().withdraw(_msgSender(), amount);
_msgSender().transfer(amount);
}
| 5,969,288 | [
1,
1190,
9446,
7418,
286,
2219,
329,
284,
19156,
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,
598,
9446,
27998,
12,
11890,
17666,
3844,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
4515,
598,
9446,
374,
3844,
8863,
203,
3639,
10560,
3245,
18,
588,
27998,
3245,
7675,
1918,
9446,
24899,
3576,
12021,
9334,
3844,
1769,
203,
3639,
389,
3576,
12021,
7675,
13866,
12,
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
] |
/**
* @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant.
* @author Axiom Zen (https://www.axiomzen.co)
* This code was taken from https://github.com/dapperlabs at
* https://github.com/dapperlabs/cryptokitties-bounty and is NOT kleros code.
*/
pragma solidity ^0.4.18;
import "./KittyBase.sol";
import "./ERC721.sol";
/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract KittyOwnership is KittyBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public name = "CryptoKitties";
string public symbol = "CK";
// bool public implementsERC721 = true;
//
function implementsERC721() public pure returns (bool)
{
return true;
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Kitty.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Kitty.
/// @param _claimant the address we are confirming kitten is approved for.
/// @param _tokenId kitten id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Kitties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
kittyIndexToApproved[_tokenId] = _approved;
}
/// @dev Transfers a kitty owned by this contract to the specified address.
/// Used to rescue lost kitties. (There is no "proper" flow where this contract
/// should be the owner of any Kitty. This function exists for us to reassign
/// the ownership of Kitties that users may have accidentally sent to our address.)
/// @param _kittyId - ID of kitty
/// @param _recipient - Address to send the cat to
function rescueLostKitty(uint256 _kittyId, address _recipient) public onlyCOO whenNotPaused {
require(_owns(this, _kittyId));
_transfer(this, _recipient, _kittyId);
}
/// @notice Returns the number of Kitties owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Kitty to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoKitties specifically) or your Kitty may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Kitty to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// You can only send your own cat.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Kitty via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Kitty owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Kitty to be transfered.
/// @param _to The address that should take ownership of the Kitty. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Kitty to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Kitties currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return kitties.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Kitty.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = kittyIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns the nth Kitty assigned to an address, with n specified by the
/// _index argument.
/// @param _owner The owner whose Kitties we are interested in.
/// @param _index The zero-based index of the cat within the owner's list of cats.
/// Must be less than balanceOf(_owner).
/// @dev This method MUST NEVER be called by smart contract code. It will almost
/// certainly blow past the block gas limit once there are a large number of
/// Kitties in existence. Exists only to allow off-chain queries of ownership.
/// Optional method for ERC-721.
function tokensOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256 tokenId)
{
uint256 count = 0;
for (uint256 i = 1; i <= totalSupply(); i++) {
if (kittyIndexToOwner[i] == _owner) {
if (count == _index) {
return i;
} else {
count++;
}
}
}
revert();
}
}
| @notice Returns the nth Kitty assigned to an address, with n specified by the _index argument. @param _owner The owner whose Kitties we are interested in. @param _index The zero-based index of the cat within the owner's list of cats. Must be less than balanceOf(_owner). @dev This method MUST NEVER be called by smart contract code. It will almost certainly blow past the block gas limit once there are a large number of Kitties in existence. Exists only to allow off-chain queries of ownership. Optional method for ERC-721. | function tokensOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256 tokenId)
{
uint256 count = 0;
for (uint256 i = 1; i <= totalSupply(); i++) {
if (kittyIndexToOwner[i] == _owner) {
if (count == _index) {
return i;
count++;
}
}
}
revert();
}
| 5,503,045 | [
1,
1356,
326,
20196,
1475,
305,
4098,
6958,
358,
392,
1758,
16,
598,
290,
1269,
635,
326,
225,
389,
1615,
1237,
18,
225,
389,
8443,
1021,
3410,
8272,
1475,
305,
88,
606,
732,
854,
20506,
316,
18,
225,
389,
1615,
1021,
3634,
17,
12261,
770,
434,
326,
6573,
3470,
326,
3410,
1807,
666,
434,
27525,
18,
225,
6753,
506,
5242,
2353,
11013,
951,
24899,
8443,
2934,
225,
1220,
707,
10685,
12901,
2204,
506,
2566,
635,
13706,
6835,
981,
18,
2597,
903,
23889,
225,
8626,
715,
324,
821,
8854,
326,
1203,
16189,
1800,
3647,
1915,
854,
279,
7876,
1300,
434,
225,
1475,
305,
88,
606,
316,
15782,
18,
17277,
1338,
358,
1699,
3397,
17,
5639,
6218,
434,
23178,
18,
225,
4055,
707,
364,
4232,
39,
17,
27,
5340,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2430,
951,
5541,
21268,
12,
2867,
389,
8443,
16,
2254,
5034,
389,
1615,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
1147,
548,
13,
203,
565,
288,
203,
3639,
2254,
5034,
1056,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
404,
31,
277,
1648,
2078,
3088,
1283,
5621,
277,
27245,
288,
203,
5411,
309,
261,
8691,
4098,
1016,
774,
5541,
63,
77,
65,
422,
389,
8443,
13,
288,
203,
7734,
309,
261,
1883,
422,
389,
1615,
13,
288,
203,
10792,
327,
277,
31,
203,
10792,
1056,
9904,
31,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
3639,
15226,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x30ac79B557973771c931D8d765E0728261A742a0/sources/Comptroller.sol | * @notice Transfer WPC to the user, if they are above the threshold @dev Note: If there is not enough WPC, we do not perform the transfer all. @param user The address of the user to transfer WPC to @param userAccrued The amount of WPC to (possibly) transfer @return The amount of WPC which was NOT transferred to the user/ | function transferWpc(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
uint wpcRemaining = piggy.balanceOf(address(this));
if (userAccrued <= wpcRemaining) {
piggy.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
| 3,604,204 | [
1,
5912,
678,
3513,
358,
326,
729,
16,
309,
2898,
854,
5721,
326,
5573,
225,
3609,
30,
971,
1915,
353,
486,
7304,
678,
3513,
16,
732,
741,
486,
3073,
326,
7412,
777,
18,
225,
729,
1021,
1758,
434,
326,
729,
358,
7412,
678,
3513,
358,
225,
729,
8973,
86,
5957,
1021,
3844,
434,
678,
3513,
358,
261,
917,
8781,
13,
7412,
327,
1021,
3844,
434,
678,
3513,
1492,
1703,
4269,
906,
4193,
358,
326,
729,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7412,
59,
2436,
12,
2867,
729,
16,
2254,
729,
8973,
86,
5957,
16,
2254,
5573,
13,
2713,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
1355,
8973,
86,
5957,
1545,
5573,
597,
729,
8973,
86,
5957,
405,
374,
13,
288,
203,
5411,
2254,
341,
2436,
11429,
273,
293,
360,
7797,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
309,
261,
1355,
8973,
86,
5957,
1648,
341,
2436,
11429,
13,
288,
203,
7734,
293,
360,
7797,
18,
13866,
12,
1355,
16,
729,
8973,
86,
5957,
1769,
203,
7734,
327,
374,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
729,
8973,
86,
5957,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/ConsiderationErrors.sol | Store left-padded selector with push4 (reduces bytecode), mem[28:32] = selector Store arguments. revert(abi.encodeWithSignature( "InvalidTime(uint256,uint256)", startTime, endTime )) | assembly {
mstore(0, InvalidTime_error_selector)
mstore(InvalidTime_error_startTime_ptr, startTime)
mstore(InvalidTime_error_endTime_ptr, endTime)
revert(Error_selector_offset, InvalidTime_error_length)
}
| 4,301,444 | [
1,
2257,
2002,
17,
6982,
785,
3451,
598,
1817,
24,
261,
1118,
89,
764,
22801,
3631,
1663,
63,
6030,
30,
1578,
65,
273,
3451,
4994,
1775,
18,
15226,
12,
21457,
18,
3015,
1190,
5374,
12,
377,
315,
1941,
950,
12,
11890,
5034,
16,
11890,
5034,
2225,
16,
377,
8657,
16,
377,
13859,
8623,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
19931,
288,
203,
3639,
312,
2233,
12,
20,
16,
1962,
950,
67,
1636,
67,
9663,
13,
203,
203,
3639,
312,
2233,
12,
1941,
950,
67,
1636,
67,
1937,
950,
67,
6723,
16,
8657,
13,
203,
3639,
312,
2233,
12,
1941,
950,
67,
1636,
67,
409,
950,
67,
6723,
16,
13859,
13,
203,
203,
3639,
15226,
12,
668,
67,
9663,
67,
3348,
16,
1962,
950,
67,
1636,
67,
2469,
13,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
pragma experimental ABIEncoderV2;
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
//BlackJack.sol
//Ricardo Peinado
//BlackJack smart contract
//03.13.2022
//RULES:
//This rules are based on the URL:
//https://www.lasvegasdirect.com/las-vegas-blackjack-rules-how-to-play-blackjack-and-win/
contract BlackJack is VRFConsumerBaseV2{
VRFCoordinatorV2Interface COORDINATOR;
// Your subscription ID.
uint64 s_subscriptionId;
// Rinkeby coordinator. For other networks,
// see https://docs.chain.link/docs/vrf-contracts/#configurations
address vrfCoordinator = 0x6168499c0cFfCaCD319c818142124B7A15E857ab;
// The gas lane to use, which specifies the maximum gas price to bump to.
// For a list of available gas lanes on each network,
// see https://docs.chain.link/docs/vrf-contracts/#configurations
bytes32 keyHash = 0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc;
// Depends on the number of requested values that you want sent to the
// fulfillRandomWords() function. Storing each word costs about 20,000 gas,
// so 100,000 is a safe default for this example contract. Test and adjust
// this limit based on the network that you select, the size of the request,
// and the processing of the callback request in the fulfillRandomWords()
// function.
uint32 callbackGasLimit = 100000;
// The default is 3, but you can set this higher.
uint16 requestConfirmations = 3;
// For this example, retrieve 2 random values in one request.
// Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
uint32 numWords = 2;
uint256[] public s_randomWords;
uint256 public s_requestId;
address s_owner;
string public card;
constructor(uint64 subscriptionId) VRFConsumerBaseV2(vrfCoordinator) {
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
s_owner = msg.sender;
s_subscriptionId = subscriptionId;
}
struct Player {
address player;
uint256 playerCard1;
uint256 playerCard2;
uint256 playerWager;
uint256 playerNextCard;
uint256 playerCardsValue;
uint256 playerCardsSplitValue;
}
struct Dealer {
uint256 dealerCard1;
uint256 dealerCard2;
uint256 dealerWager;
uint256 dealerNextCard;
uint256 dealerCardsValue;
uint256 dealerCardsSplitValue;
}
// Assumes the subscription is funded sufficiently.
function requestRandomWords() external onlyOwner {
// Will revert if subscription is not set and funded.
s_requestId = COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
}
function fulfillRandomWords(uint256 /* requestId */, uint256[] memory randomWords) internal override {
s_randomWords = randomWords;
}
modifier onlyOwner() {
require(msg.sender == s_owner);
_;
}
Player private player;
Dealer private dealer;
// deal one random card
function dealCard() public {
uint256 randCardNum;
uint256 randCardSuit;
uint256 numOfCards;
uint256 numOfSuits;
string[4] memory cardSuit;
string memory strCardNum;
string memory strCardSuit;
cardSuit = ["clubs","diamonds","hearts","spades"];
numOfCards = 13;
numOfSuits = 4;
randCardNum = _randModulus(numOfCards);
randCardSuit = _randModulus(numOfSuits);
strCardNum = _uint2str(randCardNum);
strCardSuit = cardSuit[randCardSuit];
if(randCardNum == 11) {
strCardNum = "Jack";
}
else if(randCardNum == 12) {
strCardNum = "Queen";
}
else if(randCardNum == 13) {
strCardNum = "King";
}
else if(randCardNum == 1) {
strCardNum = "Ace";
}
card = string(abi.encodePacked(strCardSuit, strCardNum));
}
// get random number function
function _randModulus(uint256 _maxRand) internal returns(uint256 rtnVal) {
uint256 randModulusVal = _maxRand;
s_requestId = COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
return rtnVal = (s_requestId % randModulusVal) + 1;
}
// convert interger to string
function _uint2str(uint256 _i ) internal pure returns (string memory str) {
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
}
| Your subscription ID. Rinkeby coordinator. For other networks, see https:docs.chain.link/docs/vrf-contracts/#configurations The gas lane to use, which specifies the maximum gas price to bump to. For a list of available gas lanes on each network, see https:docs.chain.link/docs/vrf-contracts/#configurations Depends on the number of requested values that you want sent to the fulfillRandomWords() function. Storing each word costs about 20,000 gas, so 100,000 is a safe default for this example contract. Test and adjust this limit based on the network that you select, the size of the request, and the processing of the callback request in the fulfillRandomWords() function. The default is 3, but you can set this higher. For this example, retrieve 2 random values in one request. Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS. | contract BlackJack is VRFConsumerBaseV2{
VRFCoordinatorV2Interface COORDINATOR;
uint64 s_subscriptionId;
address vrfCoordinator = 0x6168499c0cFfCaCD319c818142124B7A15E857ab;
bytes32 keyHash = 0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc;
uint32 callbackGasLimit = 100000;
uint16 requestConfirmations = 3;
uint32 numWords = 2;
uint256[] public s_randomWords;
uint256 public s_requestId;
address s_owner;
string public card;
pragma solidity ^0.8.12;
constructor(uint64 subscriptionId) VRFConsumerBaseV2(vrfCoordinator) {
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
s_owner = msg.sender;
s_subscriptionId = subscriptionId;
}
struct Player {
address player;
uint256 playerCard1;
uint256 playerCard2;
uint256 playerWager;
uint256 playerNextCard;
uint256 playerCardsValue;
uint256 playerCardsSplitValue;
}
struct Dealer {
uint256 dealerCard1;
uint256 dealerCard2;
uint256 dealerWager;
uint256 dealerNextCard;
uint256 dealerCardsValue;
uint256 dealerCardsSplitValue;
}
function requestRandomWords() external onlyOwner {
s_requestId = COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
}
function fulfillRandomWords(uint256 /* requestId */, uint256[] memory randomWords) internal override {
s_randomWords = randomWords;
}
modifier onlyOwner() {
require(msg.sender == s_owner);
_;
}
Player private player;
Dealer private dealer;
function dealCard() public {
uint256 randCardNum;
uint256 randCardSuit;
uint256 numOfCards;
uint256 numOfSuits;
string[4] memory cardSuit;
string memory strCardNum;
string memory strCardSuit;
cardSuit = ["clubs","diamonds","hearts","spades"];
numOfCards = 13;
numOfSuits = 4;
randCardNum = _randModulus(numOfCards);
randCardSuit = _randModulus(numOfSuits);
strCardNum = _uint2str(randCardNum);
strCardSuit = cardSuit[randCardSuit];
if(randCardNum == 11) {
strCardNum = "Jack";
}
else if(randCardNum == 12) {
strCardNum = "Queen";
}
else if(randCardNum == 13) {
strCardNum = "King";
}
else if(randCardNum == 1) {
strCardNum = "Ace";
}
card = string(abi.encodePacked(strCardSuit, strCardNum));
}
function dealCard() public {
uint256 randCardNum;
uint256 randCardSuit;
uint256 numOfCards;
uint256 numOfSuits;
string[4] memory cardSuit;
string memory strCardNum;
string memory strCardSuit;
cardSuit = ["clubs","diamonds","hearts","spades"];
numOfCards = 13;
numOfSuits = 4;
randCardNum = _randModulus(numOfCards);
randCardSuit = _randModulus(numOfSuits);
strCardNum = _uint2str(randCardNum);
strCardSuit = cardSuit[randCardSuit];
if(randCardNum == 11) {
strCardNum = "Jack";
}
else if(randCardNum == 12) {
strCardNum = "Queen";
}
else if(randCardNum == 13) {
strCardNum = "King";
}
else if(randCardNum == 1) {
strCardNum = "Ace";
}
card = string(abi.encodePacked(strCardSuit, strCardNum));
}
function dealCard() public {
uint256 randCardNum;
uint256 randCardSuit;
uint256 numOfCards;
uint256 numOfSuits;
string[4] memory cardSuit;
string memory strCardNum;
string memory strCardSuit;
cardSuit = ["clubs","diamonds","hearts","spades"];
numOfCards = 13;
numOfSuits = 4;
randCardNum = _randModulus(numOfCards);
randCardSuit = _randModulus(numOfSuits);
strCardNum = _uint2str(randCardNum);
strCardSuit = cardSuit[randCardSuit];
if(randCardNum == 11) {
strCardNum = "Jack";
}
else if(randCardNum == 12) {
strCardNum = "Queen";
}
else if(randCardNum == 13) {
strCardNum = "King";
}
else if(randCardNum == 1) {
strCardNum = "Ace";
}
card = string(abi.encodePacked(strCardSuit, strCardNum));
}
function dealCard() public {
uint256 randCardNum;
uint256 randCardSuit;
uint256 numOfCards;
uint256 numOfSuits;
string[4] memory cardSuit;
string memory strCardNum;
string memory strCardSuit;
cardSuit = ["clubs","diamonds","hearts","spades"];
numOfCards = 13;
numOfSuits = 4;
randCardNum = _randModulus(numOfCards);
randCardSuit = _randModulus(numOfSuits);
strCardNum = _uint2str(randCardNum);
strCardSuit = cardSuit[randCardSuit];
if(randCardNum == 11) {
strCardNum = "Jack";
}
else if(randCardNum == 12) {
strCardNum = "Queen";
}
else if(randCardNum == 13) {
strCardNum = "King";
}
else if(randCardNum == 1) {
strCardNum = "Ace";
}
card = string(abi.encodePacked(strCardSuit, strCardNum));
}
function dealCard() public {
uint256 randCardNum;
uint256 randCardSuit;
uint256 numOfCards;
uint256 numOfSuits;
string[4] memory cardSuit;
string memory strCardNum;
string memory strCardSuit;
cardSuit = ["clubs","diamonds","hearts","spades"];
numOfCards = 13;
numOfSuits = 4;
randCardNum = _randModulus(numOfCards);
randCardSuit = _randModulus(numOfSuits);
strCardNum = _uint2str(randCardNum);
strCardSuit = cardSuit[randCardSuit];
if(randCardNum == 11) {
strCardNum = "Jack";
}
else if(randCardNum == 12) {
strCardNum = "Queen";
}
else if(randCardNum == 13) {
strCardNum = "King";
}
else if(randCardNum == 1) {
strCardNum = "Ace";
}
card = string(abi.encodePacked(strCardSuit, strCardNum));
}
function _randModulus(uint256 _maxRand) internal returns(uint256 rtnVal) {
uint256 randModulusVal = _maxRand;
s_requestId = COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
return rtnVal = (s_requestId % randModulusVal) + 1;
}
function _uint2str(uint256 _i ) internal pure returns (string memory str) {
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
function _uint2str(uint256 _i ) internal pure returns (string memory str) {
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
function _uint2str(uint256 _i ) internal pure returns (string memory str) {
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
function _uint2str(uint256 _i ) internal pure returns (string memory str) {
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
}
| 12,791,913 | [
1,
15446,
4915,
1599,
18,
534,
754,
73,
1637,
24794,
18,
2457,
1308,
13884,
16,
2621,
2333,
30,
8532,
18,
5639,
18,
1232,
19,
8532,
19,
16825,
17,
16351,
87,
19,
25856,
1021,
16189,
328,
8806,
358,
999,
16,
1492,
11470,
326,
4207,
16189,
6205,
358,
23559,
358,
18,
2457,
279,
666,
434,
2319,
16189,
328,
304,
281,
603,
1517,
2483,
16,
2621,
2333,
30,
8532,
18,
5639,
18,
1232,
19,
8532,
19,
16825,
17,
16351,
87,
19,
25856,
4019,
5839,
603,
326,
1300,
434,
3764,
924,
716,
1846,
2545,
3271,
358,
326,
22290,
8529,
7363,
1435,
445,
18,
934,
6053,
1517,
2076,
22793,
2973,
4200,
16,
3784,
16189,
16,
1427,
2130,
16,
3784,
353,
279,
4183,
805,
364,
333,
3454,
6835,
18,
7766,
471,
5765,
333,
1800,
2511,
603,
326,
2483,
716,
1846,
2027,
16,
326,
963,
434,
326,
590,
16,
471,
326,
4929,
434,
326,
1348,
590,
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,
22467,
46,
484,
353,
776,
12918,
5869,
2171,
58,
22,
95,
203,
565,
776,
12918,
25307,
58,
22,
1358,
7910,
916,
21329,
3575,
31,
203,
203,
565,
2254,
1105,
272,
67,
25218,
31,
203,
203,
565,
1758,
20466,
25307,
273,
374,
92,
26,
2313,
5193,
2733,
71,
20,
71,
42,
74,
23508,
10160,
23,
3657,
71,
28,
2643,
29126,
24734,
38,
27,
37,
3600,
41,
7140,
27,
378,
31,
203,
203,
565,
1731,
1578,
498,
2310,
273,
374,
7669,
6675,
70,
22,
17156,
23014,
73,
23,
70,
29,
73,
3437,
6334,
8148,
5292,
73,
10321,
21,
19192,
29,
71,
378,
3247,
70,
3437,
311,
69,
20,
69,
8942,
24852,
3462,
69,
26,
3028,
29,
69,
7140,
952,
3672,
27,
952,
31,
203,
203,
565,
2254,
1578,
1348,
27998,
3039,
273,
25259,
31,
203,
203,
565,
2254,
2313,
590,
11269,
1012,
273,
890,
31,
203,
203,
565,
2254,
1578,
818,
7363,
273,
225,
576,
31,
203,
203,
565,
2254,
5034,
8526,
1071,
272,
67,
9188,
7363,
31,
203,
565,
2254,
5034,
1071,
272,
67,
2293,
548,
31,
203,
565,
1758,
272,
67,
8443,
31,
203,
203,
565,
533,
1071,
5270,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2138,
31,
203,
203,
203,
565,
3885,
12,
11890,
1105,
15107,
13,
776,
12918,
5869,
2171,
58,
22,
12,
16825,
25307,
13,
288,
203,
3639,
7910,
916,
21329,
3575,
273,
776,
12918,
25307,
58,
22,
1358,
12,
16825,
25307,
1769,
203,
3639,
272,
67,
8443,
273,
1234,
18,
15330,
31,
203,
3639,
2
] |
./full_match/421611/0x19103d0bC54c4934807e3a51F44ff77C726076B3/sources/_aave/core-v3/contracts/protocol/libraries/logic/BridgeLogic.sol | * @notice Mint unbacked aTokens to a user and updates the unbacked for the reserve. @dev Essentially a supply without transferring the underlying. @param reserve The reserve to mint to @param userConfig The user configuration to update @param asset The address of the asset @param amount The amount to mint @param onBehalfOf The address that will receive the aTokens @param referralCode Code used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-man/ | ) external {
DataTypes.ReserveCache memory reserveCache = reserve.cache();
reserve.updateState(reserveCache);
ValidationLogic.validateSupply(reserveCache, amount);
uint256 unbackedMintCap = reserveCache.reserveConfiguration.getUnbackedMintCap();
uint256 reserveDecimals = reserveCache.reserveConfiguration.getDecimals();
uint256 unbacked = reserve.unbacked = reserve.unbacked + Helpers.castUint128(amount);
require(
unbackedMintCap > 0 && unbacked / (10**reserveDecimals) < unbackedMintCap,
Errors.VL_UNBACKED_MINT_CAP_EXCEEDED
);
reserve.updateInterestRates(reserveCache, asset, 0, 0);
bool isFirstSupply = IAToken(reserveCache.aTokenAddress).mint(
onBehalfOf,
amount,
reserveCache.nextLiquidityIndex
);
if (isFirstSupply) {
userConfig.setUsingAsCollateral(reserve.id, true);
emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);
}
emit MintUnbacked(asset, msg.sender, onBehalfOf, amount, referralCode);
}
| 13,220,383 | [
1,
49,
474,
640,
823,
329,
279,
5157,
358,
279,
729,
471,
4533,
326,
640,
823,
329,
364,
326,
20501,
18,
225,
512,
1049,
11220,
279,
14467,
2887,
906,
74,
20245,
326,
6808,
18,
225,
20501,
1021,
20501,
358,
312,
474,
358,
225,
729,
809,
1021,
729,
1664,
358,
1089,
225,
3310,
1021,
1758,
434,
326,
3310,
225,
3844,
1021,
3844,
358,
312,
474,
225,
603,
1919,
20222,
951,
1021,
1758,
716,
903,
6798,
326,
279,
5157,
225,
1278,
370,
23093,
3356,
1399,
358,
1744,
326,
11301,
639,
4026,
1776,
326,
1674,
16,
364,
8555,
283,
6397,
18,
282,
374,
309,
326,
1301,
353,
7120,
5122,
635,
326,
729,
16,
2887,
1281,
7689,
17,
4728,
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,
225,
262,
3903,
288,
203,
565,
1910,
2016,
18,
607,
6527,
1649,
3778,
20501,
1649,
273,
20501,
18,
2493,
5621,
203,
203,
565,
20501,
18,
2725,
1119,
12,
455,
6527,
1649,
1769,
203,
203,
565,
5684,
20556,
18,
5662,
3088,
1283,
12,
455,
6527,
1649,
16,
3844,
1769,
203,
203,
565,
2254,
5034,
640,
823,
329,
49,
474,
4664,
273,
20501,
1649,
18,
455,
6527,
1750,
18,
588,
984,
823,
329,
49,
474,
4664,
5621,
203,
565,
2254,
5034,
20501,
31809,
273,
20501,
1649,
18,
455,
6527,
1750,
18,
588,
31809,
5621,
203,
203,
565,
2254,
5034,
640,
823,
329,
273,
20501,
18,
318,
823,
329,
273,
20501,
18,
318,
823,
329,
397,
17090,
18,
4155,
5487,
10392,
12,
8949,
1769,
203,
203,
565,
2583,
12,
203,
1377,
640,
823,
329,
49,
474,
4664,
405,
374,
597,
640,
823,
329,
342,
261,
2163,
636,
455,
6527,
31809,
13,
411,
640,
823,
329,
49,
474,
4664,
16,
203,
1377,
9372,
18,
58,
48,
67,
2124,
8720,
2056,
67,
49,
3217,
67,
17296,
67,
2294,
26031,
203,
565,
11272,
203,
203,
565,
20501,
18,
2725,
29281,
20836,
12,
455,
6527,
1649,
16,
3310,
16,
374,
16,
374,
1769,
203,
203,
565,
1426,
17447,
3088,
1283,
273,
467,
789,
969,
12,
455,
6527,
1649,
18,
69,
1345,
1887,
2934,
81,
474,
12,
203,
1377,
603,
1919,
20222,
951,
16,
203,
1377,
3844,
16,
203,
1377,
20501,
1649,
18,
4285,
48,
18988,
24237,
1016,
203,
565,
11272,
203,
203,
565,
309,
261,
291,
3759,
3088,
1283,
13,
288,
2
] |
pragma solidity ^0.4.19;
// last compiled with v0.4.19+commit.c4cbbb05;
contract SafeMath {
//internals
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c>=a && c>=b);
return c;
}
}
contract Token {
/// @return total amount of tokens
function totalSupply() public constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) public returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping(address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
uint256 public totalSupply;
}
contract ReserveToken is StandardToken, SafeMath {
string public name;
string public symbol;
uint public decimals = 18;
address public minter;
event Create(address account, uint amount);
event Destroy(address account, uint amount);
function ReserveToken(string name_, string symbol_) public {
name = name_;
symbol = symbol_;
minter = msg.sender;
}
function create(address account, uint amount) public {
require(msg.sender == minter);
balances[account] = safeAdd(balances[account], amount);
totalSupply = safeAdd(totalSupply, amount);
Create(account, amount);
}
function destroy(address account, uint amount) public {
require(msg.sender == minter);
require(balances[account] >= amount);
balances[account] = safeSub(balances[account], amount);
totalSupply = safeSub(totalSupply, amount);
Destroy(account, amount);
}
}
contract Challenge is SafeMath {
uint public fee = 10 * (10 ** 16); // fee percentage (100% = 10 ** 18)
uint public blockPeriod = 6000; // period of blocks for waiting until certain transactions can be sent
uint public blockNumber; // block number when this challenge was initiated
bool public funded; // has the initial challenger funded the contract?
address public witnessJury; // the WitnessJury smart contract
address public token; // the token of the prize pool
address public user1; // the initial challenger
address public user2; // the responding challenger
string public key1; // something to identify the initial challenger
string public key2; // something to identify the responding challenger
uint public amount; // the amount each challenger committed to prize pool
address public host; // the witness who agreed to host
string public hostKey; // something to identify the host
string public witnessJuryKey; // something the host used to identify the challenge specifics
uint public witnessJuryRequestNum; // the WitnessJury request number (in the WitnessJury smart contract)
uint public winner; // the winner (1 or 2)
bool public rescued; // has the contract been rescued?
bool public juryCalled; // has the jury been called?
address public referrer; // the referrer of the person who created the challenge (splits reward with host)
event NewChallenge(uint amount, address user1, string key1);
event Fund();
event Respond(address user2, string key2);
event Host(address host, string hostKey);
event SetWitnessJuryKey(uint witnessJuryRequestNum, string witnessJuryKey);
event RequestJury();
event Resolve(uint winner, bool wasContested, uint winnerAmount, uint hostAmount, uint witnessJuryAmount);
event Rescue();
function Challenge(address witnessJury_, address token_, uint amount_, address user1_, string key1_, uint blockPeriod_, address referrer_) public {
require(amount_ > 0);
blockPeriod = blockPeriod_;
witnessJury = witnessJury_;
token = token_;
user1 = user1_;
key1 = key1_;
amount = amount_;
referrer = referrer_;
blockNumber = block.number;
NewChallenge(amount, user1, key1);
}
function fund() public {
// remember to call approve() on the token first...
require(!funded);
require(!rescued);
require(msg.sender == user1);
require(Token(token).transferFrom(user1, this, amount));
funded = true;
blockNumber = block.number;
Fund();
}
function respond(address user2_, string key2_) public {
// remember to call approve() on the token first...
require(user2 == 0x0);
require(msg.sender == user2_);
require(funded);
require(!rescued);
user2 = user2_;
key2 = key2_;
blockNumber = block.number;
require(Token(token).transferFrom(user2, this, amount));
Respond(user2, key2);
}
function host(string hostKey_) public {
require(host == 0x0);
require(!rescued);
host = msg.sender;
hostKey = hostKey_;
blockNumber = block.number;
Host(host, hostKey);
}
function setWitnessJuryKey(string witnessJuryKey_) public {
require(witnessJuryRequestNum == 0);
require(msg.sender == host);
require(!rescued);
witnessJuryRequestNum = WitnessJury(witnessJury).numRequests() + 1;
witnessJuryKey = witnessJuryKey_;
blockNumber = block.number;
WitnessJury(witnessJury).newRequest(witnessJuryKey, this);
SetWitnessJuryKey(witnessJuryRequestNum, witnessJuryKey);
}
function requestJury() public {
require(!juryCalled);
require(msg.sender == user1 || msg.sender == user2);
require(!rescued);
require(winner == 0);
require(WitnessJury(witnessJury).getWinner1(witnessJuryRequestNum) != 0 && WitnessJury(witnessJury).getWinner2(witnessJuryRequestNum) != 0);
juryCalled = true;
blockNumber = block.number;
WitnessJury(witnessJury).juryNeeded(witnessJuryRequestNum);
RequestJury();
}
function resolve(uint witnessJuryRequestNum_, bool juryContested, address[] majorityJurors, uint winner_, address witness1, address witness2, uint witnessJuryRewardPercentage) public {
require(winner == 0);
require(witnessJuryRequestNum_ == witnessJuryRequestNum);
require(msg.sender == witnessJury);
require(winner_ == 1 || winner_ == 2);
require(!rescued);
require(block.number > blockNumber + blockPeriod);
uint totalFee = safeMul(safeMul(amount, 2), fee) / (1 ether);
uint winnerAmount = safeSub(safeMul(amount, 2), totalFee);
uint witnessJuryAmount = safeMul(totalFee, witnessJuryRewardPercentage) / (1 ether);
uint hostAmount = safeSub(totalFee, witnessJuryAmount);
uint flipWinner = winner_ == 1 ? 2 : 1;
winner = juryContested ? flipWinner : winner_;
if (winnerAmount > 0) {
require(Token(token).transfer(winner == 1 ? user1 : user2, winnerAmount));
}
if (referrer != 0x0 && hostAmount / 2 > 0) {
require(Token(token).transfer(host, hostAmount / 2));
require(Token(token).transfer(referrer, hostAmount / 2));
} else if (referrer == 0 && hostAmount > 0) {
require(Token(token).transfer(host, hostAmount));
}
if (!juryContested && witnessJuryAmount / 2 > 0) {
require(Token(token).transfer(witness1, witnessJuryAmount / 2));
require(Token(token).transfer(witness2, witnessJuryAmount / 2));
} else if (juryContested && witnessJuryAmount / majorityJurors.length > 0) {
for (uint i = 0; i < majorityJurors.length; i++) {
require(Token(token).transfer(majorityJurors[i], witnessJuryAmount / majorityJurors.length));
}
}
uint excessBalance = Token(token).balanceOf(this);
if (excessBalance > 0) {
require(Token(token).transfer(0x0, excessBalance));
}
Resolve(winner, juryContested, winnerAmount, hostAmount, witnessJuryAmount);
}
function rescue() public {
require(!rescued);
require(funded);
require(block.number > blockNumber + blockPeriod * 10);
require(msg.sender == user1 || msg.sender == user2);
require(winner == 0);
rescued = true;
if (user2 != 0x0) {
require(Token(token).transfer(user1, amount));
require(Token(token).transfer(user2, amount));
} else {
require(Token(token).transfer(user1, amount));
}
Rescue();
}
}
contract ChallengeFactory is SafeMath {
address witnessJury;
address token;
mapping(uint => Challenge) public challenges;
uint numChallenges;
event NewChallenge(address addr, uint amount, address user, string key);
function ChallengeFactory(address witnessJury_, address token_) public {
witnessJury = witnessJury_;
token = token_;
}
function newChallenge(uint amount, address user, string key, address referrer) public {
numChallenges = safeAdd(numChallenges, 1);
uint blockPeriod = 6000;
challenges[numChallenges] = new Challenge(witnessJury, token, amount, user, key, blockPeriod, referrer);
NewChallenge(address(challenges[numChallenges]), amount, user, key);
}
}
contract WitnessJury is SafeMath {
mapping(address => uint) public balances; // mapping of witness address to witness balance
uint public limit = 10 ** 16; // 1% = the max percentage of the overall witness pool one person can have
uint public numWitnessesBeforeLimit = 100; // the number of witnesses before the limit starts kicking in
uint public totalBalance; // the total of all witness balances
uint public numWitnesses; // count of total witnesses with non-zero balances
uint public blockPeriod = 6000; // 1 day at 14.4 seconds per block
uint public desiredWitnesses = 2; // desired number of witnesses to fulfill a request (witness a match)
uint public desiredJurors = 3; // desired number of jurors
uint public penalty = 50 * (10 ** 16); // penalty for witnesses if jury votes yes (penalty is sent back to the witnesses)
address public token; // the token being staked by witnesses
mapping(uint => Request) public requests; // mapping of requests that are partially or completely filled
uint public numRequests; // count of total number of partially or completely filled requests
mapping(uint => uint) public requestsPerBlockGroup; // map of number of requests per block group
uint public drmVolumeCap = 10000; // after this many matches per block group, fee stops increasing
uint public drmMinFee = 25 * (10 ** 16); // minimum witness reward percentage (100% = 10 ** 18)
uint public drmMaxFee = 50 * (10 ** 16); // maximum witness reward percentage (100% = 10 ** 18)
mapping(uint => bool) public juryNeeded; // mapping of requestNum to whether the jury is needed
mapping(uint => mapping(address => bool)) public juryVoted; // mapping of requestNum to juror addresses who already voted
mapping(uint => uint) public juryYesCount; // mapping of requestNum to number of yes votes
mapping(uint => uint) public juryNoCount; // mapping of requestNum to number of no votes
mapping(uint => address[]) public juryYesVoters; // mapping of requestNum to array of yes voters
mapping(uint => address[]) public juryNoVoters; // mapping of requestNum to array of no voters
struct Request {
string key; // the key, which should contain details about the request (for example, match ID)
address witness1; // the first witness
address witness2; // the second witness
string answer1; // the first witness' answer
string answer2; // the second witness' answer
uint winner1; // the first witness' winner
uint winner2; // the second witness' winner
uint fee; // percentage of match fee that will go to witness / jury pool (100% = 10 ** 18)
address challenge; // challenge smart contract
uint blockNumber; // block number when request was made
}
event Deposit(uint amount);
event Withdraw(uint amount);
event ReduceToLimit(address witness, uint amount);
event Report(uint requestNum, string answer, uint winner);
event NewRequest(uint requestNum, string key);
event JuryNeeded(uint requestNum);
event JuryVote(uint requestNum, address juror, bool vote);
event Resolve(uint requestNum);
event JuryContested(uint requestNum);
function WitnessJury(address token_) public {
token = token_;
}
function balanceOf(address user) public constant returns(uint) {
return balances[user];
}
function reduceToLimit(address witness) public {
require(witness == msg.sender);
uint amount = balances[witness];
uint limitAmount = safeMul(totalBalance, limit) / (1 ether);
if (amount > limitAmount && numWitnesses > numWitnessesBeforeLimit) {
uint excess = safeSub(amount, limitAmount);
balances[witness] = safeSub(amount, excess);
totalBalance = safeSub(totalBalance, excess);
require(Token(token).transfer(witness, excess));
ReduceToLimit(witness, excess);
}
}
function deposit(uint amount) public {
// remember to call approve() on the token first...
require(amount > 0);
if (balances[msg.sender] == 0) {
numWitnesses = safeAdd(numWitnesses, 1);
}
balances[msg.sender] = safeAdd(balances[msg.sender], amount);
totalBalance = safeAdd(totalBalance, amount);
require(Token(token).transferFrom(msg.sender, this, amount));
Deposit(amount);
}
function withdraw(uint amount) public {
require(amount > 0);
require(amount <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender], amount);
totalBalance = safeSub(totalBalance, amount);
if (balances[msg.sender] == 0) {
numWitnesses = safeSub(numWitnesses, 1);
}
require(Token(token).transfer(msg.sender, amount));
Withdraw(amount);
}
function isWitness(uint requestNum, address witness) public constant returns(bool) {
//random number from 0-999999999
bytes32 hash = sha256(this, requestNum, requests[requestNum].key);
uint rand = uint(sha256(requestNum, hash, witness)) % 1000000000;
return (
rand * totalBalance < 1000000000 * desiredWitnesses * balances[witness] ||
block.number > requests[requestNum].blockNumber + blockPeriod
);
}
function isJuror(uint requestNum, address juror) public constant returns(bool) {
//random number from 0-999999999
bytes32 hash = sha256(1, this, requestNum, requests[requestNum].key);
uint rand = uint(sha256(requestNum, hash, juror)) % 1000000000;
return (
rand * totalBalance < 1000000000 * desiredWitnesses * balances[juror]
);
}
function newRequest(string key, address challenge) public {
numRequests = safeAdd(numRequests, 1);
require(requests[numRequests].challenge == 0x0);
requests[numRequests].blockNumber = block.number;
requests[numRequests].challenge = challenge;
requests[numRequests].key = key;
requestsPerBlockGroup[block.number / blockPeriod] = safeAdd(requestsPerBlockGroup[block.number / blockPeriod], 1);
uint recentNumRequests = requestsPerBlockGroup[block.number / blockPeriod];
if (recentNumRequests < drmVolumeCap) {
requests[numRequests].fee = safeAdd(safeMul(safeMul(recentNumRequests, recentNumRequests), safeSub(drmMaxFee, drmMinFee)) / safeMul(drmVolumeCap, drmVolumeCap), drmMinFee);
} else {
requests[numRequests].fee = drmMaxFee;
}
NewRequest(numRequests, key);
}
function report(uint requestNum, string answer, uint winner) public {
require(requests[requestNum].challenge != 0x0);
require(requests[requestNum].witness1 == 0x0 || requests[requestNum].witness2 == 0x0);
require(requests[requestNum].witness1 != msg.sender);
require(isWitness(requestNum, msg.sender));
reportLogic(requestNum, answer, winner);
Report(requestNum, answer, winner);
}
function reportLogic(uint requestNum, string answer, uint winner) private {
reduceToLimit(msg.sender);
if (requests[requestNum].witness1 == 0x0) {
requests[requestNum].witness1 = msg.sender;
requests[requestNum].answer1 = answer;
requests[requestNum].winner1 = winner;
} else if (requests[requestNum].witness2 == 0x0) {
requests[requestNum].witness2 = msg.sender;
requests[requestNum].answer2 = answer;
requests[requestNum].winner2 = winner;
}
}
function juryNeeded(uint requestNum) public {
require(msg.sender == requests[requestNum].challenge);
require(!juryNeeded[requestNum]);
juryNeeded[requestNum] = true;
JuryNeeded(requestNum);
}
function juryVote(uint requestNum, bool vote) public {
require(!juryVoted[requestNum][msg.sender]);
require(juryNeeded[requestNum]);
require(safeAdd(juryYesCount[requestNum], juryNoCount[requestNum]) < desiredJurors);
require(isJuror(requestNum, msg.sender));
juryVoted[requestNum][msg.sender] = true;
if (vote) {
juryYesCount[requestNum] = safeAdd(juryYesCount[requestNum], 1);
juryYesVoters[requestNum].push(msg.sender);
} else {
juryNoCount[requestNum] = safeAdd(juryNoCount[requestNum], 1);
juryNoVoters[requestNum].push(msg.sender);
}
JuryVote(requestNum, msg.sender, vote);
}
function resolve(uint requestNum) public {
bool juryContested = juryYesCount[requestNum] > juryNoCount[requestNum] && safeAdd(juryYesCount[requestNum], juryNoCount[requestNum]) == desiredJurors;
Challenge(requests[requestNum].challenge).resolve(
requestNum,
juryContested,
juryYesCount[requestNum] > juryNoCount[requestNum] ? juryYesVoters[requestNum] : juryNoVoters[requestNum],
requests[requestNum].winner1,
requests[requestNum].witness1,
requests[requestNum].witness2,
requests[requestNum].fee
);
if (juryContested) {
uint penalty1 = safeMul(balances[requests[requestNum].witness1], penalty) / (1 ether);
uint penalty2 = safeMul(balances[requests[requestNum].witness2], penalty) / (1 ether);
balances[requests[requestNum].witness1] = safeSub(balances[requests[requestNum].witness1], penalty1);
balances[requests[requestNum].witness2] = safeSub(balances[requests[requestNum].witness2], penalty2);
require(Token(token).transfer(requests[requestNum].witness1, penalty1));
require(Token(token).transfer(requests[requestNum].witness2, penalty2));
JuryContested(requestNum);
}
Resolve(requestNum);
}
function getWinner1(uint requestNum) public constant returns(uint) {
return requests[requestNum].winner1;
}
function getWinner2(uint requestNum) public constant returns(uint) {
return requests[requestNum].winner2;
}
function getRequest(uint requestNum) public constant returns(string, address, address, string, string, uint, address) {
return (requests[requestNum].key,
requests[requestNum].witness1,
requests[requestNum].witness2,
requests[requestNum].answer1,
requests[requestNum].answer2,
requests[requestNum].fee,
requests[requestNum].challenge);
}
} | mapping of requestNum to array of yes voters
| mapping(uint => address[]) public juryYesVoters; | 1,754,834 | [
1,
6770,
434,
590,
2578,
358,
526,
434,
12465,
331,
352,
414,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2874,
12,
11890,
516,
1758,
63,
5717,
1071,
525,
22498,
22352,
58,
352,
414,
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
] |
./partial_match/1/0x1201FAa7258A48b820619dD57Cd8FdEb25D49b2c/sources/contracts/managed/vendor/BasePool.sol | Set immutable state variables - these cannot be read from during construction | {
_poolId = poolId;
_protocolFeesCollector = vault.getProtocolFeesCollector();
}
| 4,227,927 | [
1,
694,
11732,
919,
3152,
300,
4259,
2780,
506,
855,
628,
4982,
16171,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
389,
6011,
548,
273,
2845,
548,
31,
203,
3639,
389,
8373,
2954,
281,
7134,
273,
9229,
18,
588,
5752,
2954,
281,
7134,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.7.6;
import "@openzeppelin/contracts/access/Ownable.sol";
//@notice Ce contrat gère un système de vote pour une petite communauté. L'administrateur qui
//@notice déploie le contrat, est en charge d'ajouter les participants, et de démarrer et terminer
//@notice chaque phase du processus de vote. Les participants font des propositions et les votent.
//@notice github: https://github.com/brunolune/Vote-Alyra/blob/main/vote.sol
contract Voting is Ownable {
struct Voter {
bool isRegistered;
bool hasVoted;
uint votedProposalId;
}
struct Proposal {
string description;
uint voteCount;
}
uint private winningProposalId;
uint votersCount; //pour compter le nb d'électeurs ajoutés
uint votesCount; //pour compter le nb de votes
Proposal[] public proposals;
mapping(address => Voter) whitelist;
address[] public whitelistarray;
mapping (uint => uint[]) winningProposalIds;
enum WorkflowStatus {
RegisteringVoters,
ProposalsRegistrationStarted,
ProposalsRegistrationEnded,
VotingSessionStarted,
VotingSessionEnded,
VotesTallied
}
WorkflowStatus voteStatus = WorkflowStatus.RegisteringVoters;
event VoterRegistered(address voterAddress);
event ProposalsRegistrationStarted();
event ProposalsRegistrationEnded();
event ProposalRegistered(uint proposalId);
event VotingSessionStarted();
event VotingSessionEnded();
event Voted (address voter, uint proposalId);
event VotesTallied();
event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus);
constructor () {
whitelist[msg.sender].isRegistered = true;
whitelistarray.push(msg.sender);
votersCount = 1;
}
//@notice L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum.
function A_votersRegistration(address _address) public onlyOwner {
require(voteStatus==WorkflowStatus.RegisteringVoters, "Registration is over");
require(!whitelist[_address].isRegistered, "This address is already registered");
whitelist[_address].isRegistered = true;
whitelistarray.push(_address);
votersCount++;
emit VoterRegistered(_address);
}
//@notice L'administrateur du vote commence la session d'enregistrement des propositions.
function B_proposalsRegistrationStart() public onlyOwner{
require(voteStatus==WorkflowStatus.RegisteringVoters, "Proposals Registration already started!");
require(votersCount>2,"Please add at least 1 voter!");
emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters,WorkflowStatus.ProposalsRegistrationStarted);
emit ProposalsRegistrationStarted();
voteStatus = WorkflowStatus.ProposalsRegistrationStarted;
}
//@notice Les électeurs inscrits sont autorisés à enregistrer leurs propositions pendant que la session d'enregistrement est active.
function C_proposalRegistration(string memory _proposal) public {
require(keccak256(abi.encodePacked((_proposal)))!=keccak256(abi.encodePacked((""))),"Your proposal is empty!");
require(voteStatus==WorkflowStatus.ProposalsRegistrationStarted,"Proposals registration not open!");
require(whitelist[msg.sender].isRegistered, "You can't make a proposal cause you're not registered");
proposals.push(Proposal(_proposal,0));
emit ProposalRegistered(proposals.length-1);
}
//@notice L'administrateur met fin à la session d'enregistrement des propositions.
function D_proposalsRegistrationTermination() public onlyOwner{
require(voteStatus==WorkflowStatus.ProposalsRegistrationStarted,"Proposals registration not open!");
require(proposals.length!=0,"Please add more proposals!");
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted,WorkflowStatus.ProposalsRegistrationEnded);
voteStatus = WorkflowStatus.ProposalsRegistrationEnded;
emit ProposalsRegistrationEnded();
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded,WorkflowStatus.VotingSessionStarted);
}
//@notice L'administrateur commence la session de vote.
function E_votingTimeStart() public onlyOwner{
require(voteStatus==WorkflowStatus.ProposalsRegistrationEnded,"Proposals registration not ended!");
voteStatus = WorkflowStatus.VotingSessionStarted;
emit VotingSessionStarted();
}
//@notice Les électeurs inscrits votent pour leurs propositions préférées.
function F_vote(uint propId) public {
require(voteStatus == WorkflowStatus.VotingSessionStarted,"Vote not open!");
require(whitelist[msg.sender].isRegistered, "You can't vote cause you're not registered");
require(!whitelist[msg.sender].hasVoted, "You voted already");
whitelist[msg.sender].votedProposalId = propId;
whitelist[msg.sender].hasVoted = true;
proposals[propId].voteCount++;
votesCount++;
emit Voted(msg.sender, propId);
}
//@notice L'administrateur du vote met fin à la session de vote.
function G_votingTimeTermination() public onlyOwner{
require(voteStatus == WorkflowStatus.VotingSessionStarted,"Vote not open!");
require(votesCount>0,"Nobody has voted yet!");
voteStatus = WorkflowStatus.VotingSessionEnded;
emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted,WorkflowStatus.VotingSessionEnded);
emit VotingSessionEnded();
}
//@notice L'administrateur du vote comptabilise les votes.
function H_CountVotes() public onlyOwner {
require(voteStatus == WorkflowStatus.VotingSessionEnded,"Counting votes not open!");
//@dev on prend en compte la possibilité de plusieurs propositions gagnantes
//@dev dont les indexes sont stockés dans winningProposalIds
if (proposals[0].voteCount >= proposals[1].voteCount) winningProposalIds[0].push(0);
for (uint index = 1; index < proposals.length; index++) {
if (proposals[winningProposalId].voteCount < proposals[index].voteCount) {
winningProposalId = index ;
winningProposalIds[winningProposalId].push(winningProposalId);
}
else if (proposals[winningProposalId].voteCount == proposals[index].voteCount) {
winningProposalIds[winningProposalId].push(index) ;
}
}
emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded,WorkflowStatus.VotesTallied);
voteStatus = WorkflowStatus.VotesTallied;
emit VotesTallied();
}
//@notice Tout le monde peut vérifier les derniers détails de la proposition gagnante.
function I_WinningProposalIds() public view returns(uint[] memory) {
require(voteStatus == WorkflowStatus.VotesTallied,"Votes not counted yet!");
//@dev on retourne un tableau avec les indices des propositions gagnantes
return winningProposalIds[winningProposalId];
}
function getwhitelistarray() public view returns(address[] memory){
return whitelistarray;
}
//@dev retourne la phase du vote dans laquelle on se trouve
function getVoteStatus() public view returns (string memory) {
string[6] memory Status=[
"RegisteringVoters",
"ProposalsRegistrationStarted",
"ProposalsRegistrationEnded",
"VotingSessionStarted",
"VotingSessionEnded",
"VotesTallied"
];
return Status[uint(voteStatus)];
}
} | pour compter le nb de votes
| uint votesCount; | 1,020,455 | [
1,
84,
477,
532,
337,
264,
884,
4264,
443,
19588,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
19588,
1380,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xdbE5a8BBac5b3ba4e05BB9b9Ca51A6741bc81Bd1/sources/contracts/brokers/BrokersSignatureUtils.sol | ----------------------------------------------------------------------- Errors ----------------------------------------------------------------------- | enum BrokerSignatureUtilsErrorCodes {
INVALID_ASSET_INFO_SIGNATURE
}
error BrokerSignatureUtilsError(BrokerSignatureUtilsErrorCodes code);
bytes32 private immutable ASSET_DATA_TYPE_HASH;
bytes32 private immutable ASSETS_TYPE_HASH;
bytes32 private immutable FEES_TYPE_HASH;
bytes32 private immutable TRADE_INFO_TYPE_HASH;
| 17,074,762 | [
1,
5802,
17082,
9372,
24796,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2792,
20438,
5374,
1989,
668,
6295,
288,
203,
3639,
10071,
67,
3033,
4043,
67,
5923,
67,
26587,
203,
565,
289,
203,
203,
565,
555,
20438,
5374,
1989,
668,
12,
11194,
5374,
1989,
668,
6295,
981,
1769,
203,
203,
203,
565,
1731,
1578,
3238,
11732,
5355,
4043,
67,
4883,
67,
2399,
67,
15920,
31,
203,
565,
1731,
1578,
3238,
11732,
5355,
28092,
67,
2399,
67,
15920,
31,
203,
565,
1731,
1578,
3238,
11732,
16439,
3991,
67,
2399,
67,
15920,
31,
203,
565,
1731,
1578,
3238,
11732,
21492,
1639,
67,
5923,
67,
2399,
67,
15920,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.12;
// SPDX-License-Identifier: MIT
/**
* @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
interface ITreasury {
function notifyExternalReward(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
contract ProxyTreasury is ITreasury {
// governance
address public operator;
// flags
bool public initialized = false;
address public timelock = address(0x92a082Ad5A942140bCC791081F775900d0A514D9); // 24h timelock
address public dollar = address(0x190b589cf9Fb8DDEabBFeae36a813FFb2A702454); // BDO
address public uniRouterAddress = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); // Pancakeswap
address public treasury = address(0x15A90e6157a870CD335AF03c6df776d0B1ebf94F);
event Initialized(address indexed executor, uint256 at);
function initialize() public notInitialized {
timelock = address(0x92a082Ad5A942140bCC791081F775900d0A514D9);
dollar = address(0x190b589cf9Fb8DDEabBFeae36a813FFb2A702454);
uniRouterAddress = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);
treasury = address(0x15A90e6157a870CD335AF03c6df776d0B1ebf94F);
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
modifier onlyOperator() {
require(operator == msg.sender, "ProxyTreasury: caller is not the operator");
_;
}
modifier onlyTimelock() {
require(timelock == msg.sender, "ProxyTreasury: caller is not timelock");
_;
}
modifier notInitialized() {
require(!initialized, "ProxyTreasury: already initialized");
_;
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setUniRouterAddress(address _uniRouterAddress) external onlyOperator {
uniRouterAddress = _uniRouterAddress;
}
function setTreasury(address _treasury) external onlyOperator {
treasury = _treasury;
}
function notifyExternalReward(uint256 _amount) external override {
}
/* ========== EMERGENCY ========== */
function setTimelock(address _timelock) external onlyTimelock {
timelock = _timelock;
}
function inCaseTokensGetStuck(address _token, uint256 _amount, address _to) external onlyTimelock {
IERC20(_token).transfer(_to, _amount);
}
event ExecuteTransaction(address indexed target, uint value, string signature, bytes data);
/**
* @dev This is from Timelock contract.
*/
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public onlyTimelock returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value : value}(callData);
require(success, "ProxyTreasury::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
} | SPDX-License-Identifier: MIT governance flags | contract ProxyTreasury is ITreasury {
address public operator;
bool public initialized = false;
address public treasury = address(0x15A90e6157a870CD335AF03c6df776d0B1ebf94F);
event Initialized(address indexed executor, uint256 at);
function initialize() public notInitialized {
timelock = address(0x92a082Ad5A942140bCC791081F775900d0A514D9);
dollar = address(0x190b589cf9Fb8DDEabBFeae36a813FFb2A702454);
uniRouterAddress = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);
treasury = address(0x15A90e6157a870CD335AF03c6df776d0B1ebf94F);
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
modifier onlyOperator() {
require(operator == msg.sender, "ProxyTreasury: caller is not the operator");
_;
}
modifier onlyTimelock() {
require(timelock == msg.sender, "ProxyTreasury: caller is not timelock");
_;
}
modifier notInitialized() {
require(!initialized, "ProxyTreasury: already initialized");
_;
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setUniRouterAddress(address _uniRouterAddress) external onlyOperator {
uniRouterAddress = _uniRouterAddress;
}
function setTreasury(address _treasury) external onlyOperator {
treasury = _treasury;
}
function notifyExternalReward(uint256 _amount) external override {
}
function setTimelock(address _timelock) external onlyTimelock {
timelock = _timelock;
}
function inCaseTokensGetStuck(address _token, uint256 _amount, address _to) external onlyTimelock {
IERC20(_token).transfer(_to, _amount);
}
event ExecuteTransaction(address indexed target, uint value, string signature, bytes data);
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public onlyTimelock returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(success, "ProxyTreasury::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public onlyTimelock returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(success, "ProxyTreasury::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
} else {
(bool success, bytes memory returnData) = target.call{value : value}(callData);
} | 13,015,861 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
314,
1643,
82,
1359,
2943,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
7659,
56,
266,
345,
22498,
353,
24142,
266,
345,
22498,
288,
203,
565,
1758,
1071,
3726,
31,
203,
203,
565,
1426,
1071,
6454,
273,
629,
31,
203,
203,
565,
1758,
1071,
9787,
345,
22498,
273,
1758,
12,
20,
92,
3600,
37,
9349,
73,
26,
27985,
69,
28,
7301,
10160,
3707,
25,
6799,
4630,
71,
26,
2180,
4700,
26,
72,
20,
38,
21,
73,
17156,
11290,
42,
1769,
203,
203,
565,
871,
10188,
1235,
12,
2867,
8808,
6601,
16,
2254,
5034,
622,
1769,
203,
203,
565,
445,
4046,
1435,
1071,
486,
11459,
288,
203,
3639,
1658,
292,
975,
273,
1758,
12,
20,
92,
9975,
69,
6840,
22,
1871,
25,
37,
29,
9452,
27092,
70,
6743,
7235,
2163,
11861,
42,
4700,
6162,
713,
72,
20,
37,
25,
3461,
40,
29,
1769,
203,
3639,
302,
25442,
273,
1758,
12,
20,
92,
30454,
70,
25,
6675,
8522,
29,
42,
70,
28,
40,
1639,
378,
38,
2954,
8906,
5718,
69,
28,
3437,
2246,
70,
22,
37,
27,
3103,
24,
6564,
1769,
203,
3639,
7738,
8259,
1887,
273,
1758,
12,
20,
92,
6260,
74,
42,
22,
38,
20,
2290,
8148,
7950,
28,
37,
8642,
3361,
70,
2486,
13459,
24,
74,
29,
73,
3437,
69,
40,
72,
4848,
28,
39,
27,
42,
1769,
203,
3639,
9787,
345,
22498,
273,
1758,
12,
20,
92,
3600,
37,
9349,
73,
26,
27985,
69,
28,
7301,
10160,
3707,
25,
6799,
4630,
71,
26,
2180,
4700,
26,
72,
20,
38,
21,
73,
17156,
11290,
42,
1769,
203,
3639,
6454,
273,
638,
31,
203,
3639,
3726,
2
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "../contracts/libraries/Authorizable.sol";
import "../contracts/libraries/MerkleRewards.sol";
// A merkle rewards contract with an expiration time
contract Airdrop is MerkleRewards, Authorizable {
// The time after which the token cannot be claimed
uint256 public immutable expiration;
/// @notice Constructs the contract and sets state and immutable variables
/// @param _governance The address which can withdraw funds when the drop expires
/// @param _merkleRoot The root a keccak256 merkle tree with leaves which are address amount pairs
/// @param _token The erc20 contract which will be sent to the people with claims on the contract
/// @param _expiration The unix second timestamp when the airdrop expires
/// @param _lockingVault The governance vault which this deposits to on behalf of users
constructor(
address _governance,
bytes32 _merkleRoot,
IERC20 _token,
uint256 _expiration,
ILockingVault _lockingVault
) MerkleRewards(_merkleRoot, _token, _lockingVault) {
// Set expiration immutable and governance to the owner
expiration = _expiration;
setOwner(_governance);
}
/// @notice Allows governance to remove the funds in this contract once the airdrop is over.
/// Claims aren't blocked the airdrop ending at expiration is optional and gov has to
/// manually end it.
/// @param destination The treasury contract which will hold the freed tokens
function reclaim(address destination) external onlyOwner {
require(block.timestamp > expiration, "Not expired");
uint256 unclaimed = token.balanceOf(address(this));
token.transfer(destination, unclaimed);
}
}
| @notice Constructs the contract and sets state and immutable variables @param _governance The address which can withdraw funds when the drop expires @param _merkleRoot The root a keccak256 merkle tree with leaves which are address amount pairs @param _token The erc20 contract which will be sent to the people with claims on the contract @param _expiration The unix second timestamp when the airdrop expires @param _lockingVault The governance vault which this deposits to on behalf of users Set expiration immutable and governance to the owner | ) MerkleRewards(_merkleRoot, _token, _lockingVault) {
expiration = _expiration;
setOwner(_governance);
}
| 5,367,540 | [
1,
13262,
326,
6835,
471,
1678,
919,
471,
11732,
3152,
225,
389,
75,
1643,
82,
1359,
1021,
1758,
1492,
848,
598,
9446,
284,
19156,
1347,
326,
3640,
7368,
225,
389,
6592,
15609,
2375,
1021,
1365,
279,
417,
24410,
581,
5034,
30235,
2151,
598,
15559,
1492,
854,
1758,
3844,
5574,
225,
389,
2316,
1021,
6445,
71,
3462,
6835,
1492,
903,
506,
3271,
358,
326,
16951,
598,
11955,
603,
326,
6835,
225,
389,
19519,
1021,
9753,
2205,
2858,
1347,
326,
279,
6909,
1764,
7368,
225,
389,
739,
310,
12003,
1021,
314,
1643,
82,
1359,
9229,
1492,
333,
443,
917,
1282,
358,
603,
12433,
6186,
434,
3677,
1000,
7686,
11732,
471,
314,
1643,
82,
1359,
358,
326,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
262,
31827,
17631,
14727,
24899,
6592,
15609,
2375,
16,
389,
2316,
16,
389,
739,
310,
12003,
13,
288,
203,
3639,
7686,
273,
389,
19519,
31,
203,
3639,
31309,
24899,
75,
1643,
82,
1359,
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
] |
./full_match/1/0xF54b8AF506fcF09EDd0EC0673F6AadC7Df4EC3e6/sources/contracts/SeJoin.sol | 2 years from contract deployment
| return block.timestamp + 730 days; | 3,100,623 | [
1,
22,
11387,
628,
6835,
6314,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
327,
1203,
18,
5508,
397,
2371,
5082,
4681,
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
] |
./full_match/43113/0x4b2b37788c21F054A7B3AD33d3d544E60eAD9E56/sources/Copy_Woolf.sol | * mint a token - 90% Sheep, 10% Wolves The first 20% are free to claim, the remaining cost $WOOL Due to buffer considerations, staking is not possible immediately Minter has to wait for 10 mints/ - MAX_PER_MINT, because the last MAX_PER_MINT are mintable by an admin | function mint(uint256 amount) external payable whenNotPaused {
require(tx.origin == _msgSender(), "Only EOA");
require(
minted + amount <= MAX_TOKENS - MAX_PER_MINT,
"All tokens minted"
);
require(amount > 0 && amount <= MAX_PER_MINT, "Invalid mint amount");
if (minted < PAID_TOKENS) {
require(
minted + amount <= PAID_TOKENS,
"All tokens on-sale already sold"
);
require(amount * MINT_PRICE == msg.value, "Invalid payment amount");
require(msg.value == 0);
}
uint256 totalWoolCost = 0;
uint256 seed;
for (uint256 i = 0; i < amount; i++) {
minted++;
seed = entropy.random(minted);
generate(minted, seed);
address recipient = selectRecipient(seed);
totalWoolCost += mintCost(minted);
_safeMint(recipient, minted);
}
if (totalWoolCost > 0) wool.burn(_msgSender(), totalWoolCost);
}
| 7,153,805 | [
1,
81,
474,
279,
1147,
300,
8566,
9,
348,
580,
881,
16,
1728,
9,
678,
355,
3324,
1021,
1122,
4200,
9,
854,
4843,
358,
7516,
16,
326,
4463,
6991,
271,
59,
51,
1741,
463,
344,
358,
1613,
5260,
1012,
16,
384,
6159,
353,
486,
3323,
7636,
490,
2761,
711,
358,
2529,
364,
1728,
312,
28142,
19,
300,
4552,
67,
3194,
67,
49,
3217,
16,
2724,
326,
1142,
4552,
67,
3194,
67,
49,
3217,
854,
312,
474,
429,
635,
392,
3981,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
312,
474,
12,
11890,
5034,
3844,
13,
3903,
8843,
429,
1347,
1248,
28590,
288,
203,
3639,
2583,
12,
978,
18,
10012,
422,
389,
3576,
12021,
9334,
315,
3386,
512,
28202,
8863,
203,
3639,
2583,
12,
203,
5411,
312,
474,
329,
397,
3844,
1648,
4552,
67,
8412,
55,
300,
4552,
67,
3194,
67,
49,
3217,
16,
203,
5411,
315,
1595,
2430,
312,
474,
329,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
8949,
405,
374,
597,
3844,
1648,
4552,
67,
3194,
67,
49,
3217,
16,
315,
1941,
312,
474,
3844,
8863,
203,
3639,
309,
261,
81,
474,
329,
411,
15662,
734,
67,
8412,
55,
13,
288,
203,
5411,
2583,
12,
203,
7734,
312,
474,
329,
397,
3844,
1648,
15662,
734,
67,
8412,
55,
16,
203,
7734,
315,
1595,
2430,
603,
17,
87,
5349,
1818,
272,
1673,
6,
203,
5411,
11272,
203,
5411,
2583,
12,
8949,
380,
490,
3217,
67,
7698,
1441,
422,
1234,
18,
1132,
16,
315,
1941,
5184,
3844,
8863,
203,
5411,
2583,
12,
3576,
18,
1132,
422,
374,
1769,
203,
3639,
289,
203,
3639,
2254,
5034,
2078,
59,
1371,
8018,
273,
374,
31,
203,
3639,
2254,
5034,
5009,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
3844,
31,
277,
27245,
288,
203,
5411,
312,
474,
329,
9904,
31,
203,
5411,
5009,
273,
15943,
18,
9188,
12,
81,
474,
329,
1769,
203,
5411,
2103,
12,
81,
474,
329,
16,
5009,
1769,
203,
5411,
1758,
8027,
273,
2027,
18241,
12,
12407,
1769,
203,
5411,
2078,
59,
1371,
8018,
2
] |
./full_match/80001/0x14e39aDc79A7610c685143c4cd891F94dB3B40cD/sources/@aragon/osx/framework/dao/DAOFactory.sol | @title DAOFactory @author Aragon Association - 2022-2023 @notice This contract is used to create a DAO. | contract DAOFactory is ERC165, ProtocolVersion {
address public immutable daoBase;
DAORegistry public immutable daoRegistry;
PluginSetupProcessor public immutable pluginSetupProcessor;
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IProtocolVersion} from "../../utils/protocol/IProtocolVersion.sol";
import {ProtocolVersion} from "../../utils/protocol/ProtocolVersion.sol";
import {DAO} from "../../core/dao/DAO.sol";
import {PermissionLib} from "../../core/permission/PermissionLib.sol";
import {createERC1967Proxy} from "../../utils/Proxy.sol";
import {PluginRepo} from "../plugin/repo/PluginRepo.sol";
import {PluginSetupProcessor} from "../plugin/setup/PluginSetupProcessor.sol";
import {hashHelpers, PluginSetupRef} from "../plugin/setup/PluginSetupProcessorHelpers.sol";
import {IPluginSetup} from "../plugin/setup/IPluginSetup.sol";
import {DAORegistry} from "./DAORegistry.sol";
struct DAOSettings {
address trustedForwarder;
string daoURI;
string subdomain;
bytes metadata;
}
struct PluginSettings {
PluginSetupRef pluginSetupRef;
bytes data;
}
error NoPluginProvided();
constructor(DAORegistry _registry, PluginSetupProcessor _pluginSetupProcessor) {
daoRegistry = _registry;
pluginSetupProcessor = _pluginSetupProcessor;
daoBase = address(new DAO());
}
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
return
_interfaceId == type(IProtocolVersion).interfaceId ||
super.supportsInterface(_interfaceId);
}
function createDao(
DAOSettings calldata _daoSettings,
PluginSettings[] calldata _pluginSettings
) external returns (DAO createdDao) {
if (_pluginSettings.length == 0) {
revert NoPluginProvided();
}
bytes32 applyInstallationPermissionID = pluginSetupProcessor
.APPLY_INSTALLATION_PERMISSION_ID();
address(pluginSetupProcessor),
address(this),
applyInstallationPermissionID
);
for (uint256 i; i < _pluginSettings.length; ++i) {
(
address plugin,
IPluginSetup.PreparedSetupData memory preparedSetupData
) = pluginSetupProcessor.prepareInstallation(
address(createdDao),
PluginSetupProcessor.PrepareInstallationParams(
_pluginSettings[i].pluginSetupRef,
_pluginSettings[i].data
)
);
pluginSetupProcessor.applyInstallation(
address(createdDao),
PluginSetupProcessor.ApplyInstallationParams(
_pluginSettings[i].pluginSetupRef,
plugin,
preparedSetupData.permissions,
hashHelpers(preparedSetupData.helpers)
)
);
}
address(pluginSetupProcessor),
address(this),
applyInstallationPermissionID
);
}
function createDao(
DAOSettings calldata _daoSettings,
PluginSettings[] calldata _pluginSettings
) external returns (DAO createdDao) {
if (_pluginSettings.length == 0) {
revert NoPluginProvided();
}
bytes32 applyInstallationPermissionID = pluginSetupProcessor
.APPLY_INSTALLATION_PERMISSION_ID();
address(pluginSetupProcessor),
address(this),
applyInstallationPermissionID
);
for (uint256 i; i < _pluginSettings.length; ++i) {
(
address plugin,
IPluginSetup.PreparedSetupData memory preparedSetupData
) = pluginSetupProcessor.prepareInstallation(
address(createdDao),
PluginSetupProcessor.PrepareInstallationParams(
_pluginSettings[i].pluginSetupRef,
_pluginSettings[i].data
)
);
pluginSetupProcessor.applyInstallation(
address(createdDao),
PluginSetupProcessor.ApplyInstallationParams(
_pluginSettings[i].pluginSetupRef,
plugin,
preparedSetupData.permissions,
hashHelpers(preparedSetupData.helpers)
)
);
}
address(pluginSetupProcessor),
address(this),
applyInstallationPermissionID
);
}
createdDao = _createDAO(_daoSettings);
daoRegistry.register(createdDao, msg.sender, _daoSettings.subdomain);
bytes32 rootPermissionID = createdDao.ROOT_PERMISSION_ID();
createdDao.grant(address(createdDao), address(pluginSetupProcessor), rootPermissionID);
createdDao.grant(
function createDao(
DAOSettings calldata _daoSettings,
PluginSettings[] calldata _pluginSettings
) external returns (DAO createdDao) {
if (_pluginSettings.length == 0) {
revert NoPluginProvided();
}
bytes32 applyInstallationPermissionID = pluginSetupProcessor
.APPLY_INSTALLATION_PERMISSION_ID();
address(pluginSetupProcessor),
address(this),
applyInstallationPermissionID
);
for (uint256 i; i < _pluginSettings.length; ++i) {
(
address plugin,
IPluginSetup.PreparedSetupData memory preparedSetupData
) = pluginSetupProcessor.prepareInstallation(
address(createdDao),
PluginSetupProcessor.PrepareInstallationParams(
_pluginSettings[i].pluginSetupRef,
_pluginSettings[i].data
)
);
pluginSetupProcessor.applyInstallation(
address(createdDao),
PluginSetupProcessor.ApplyInstallationParams(
_pluginSettings[i].pluginSetupRef,
plugin,
preparedSetupData.permissions,
hashHelpers(preparedSetupData.helpers)
)
);
}
address(pluginSetupProcessor),
address(this),
applyInstallationPermissionID
);
}
_setDAOPermissions(createdDao);
createdDao.revoke(address(createdDao), address(pluginSetupProcessor), rootPermissionID);
createdDao.revoke(
createdDao.revoke(address(createdDao), address(this), rootPermissionID);
function _createDAO(DAOSettings calldata _daoSettings) internal returns (DAO dao) {
dao = DAO(payable(createERC1967Proxy(daoBase, bytes(""))));
dao.initialize(
_daoSettings.metadata,
address(this),
_daoSettings.trustedForwarder,
_daoSettings.daoURI
);
}
function _setDAOPermissions(DAO _dao) internal {
PermissionLib.SingleTargetPermission[]
memory items = new PermissionLib.SingleTargetPermission[](6);
items[0] = PermissionLib.SingleTargetPermission(
PermissionLib.Operation.Grant,
address(_dao),
_dao.ROOT_PERMISSION_ID()
);
items[1] = PermissionLib.SingleTargetPermission(
PermissionLib.Operation.Grant,
address(_dao),
_dao.UPGRADE_DAO_PERMISSION_ID()
);
items[2] = PermissionLib.SingleTargetPermission(
PermissionLib.Operation.Grant,
address(_dao),
_dao.SET_SIGNATURE_VALIDATOR_PERMISSION_ID()
);
items[3] = PermissionLib.SingleTargetPermission(
PermissionLib.Operation.Grant,
address(_dao),
_dao.SET_TRUSTED_FORWARDER_PERMISSION_ID()
);
items[4] = PermissionLib.SingleTargetPermission(
PermissionLib.Operation.Grant,
address(_dao),
_dao.SET_METADATA_PERMISSION_ID()
);
items[5] = PermissionLib.SingleTargetPermission(
PermissionLib.Operation.Grant,
address(_dao),
_dao.REGISTER_STANDARD_CALLBACK_PERMISSION_ID()
);
_dao.applySingleTargetPermissions(address(_dao), items);
}
}
| 5,569,320 | [
1,
18485,
1733,
225,
1201,
346,
265,
18400,
300,
26599,
22,
17,
18212,
23,
225,
1220,
6835,
353,
1399,
358,
752,
279,
463,
20463,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
463,
20463,
1733,
353,
4232,
39,
28275,
16,
4547,
1444,
288,
203,
565,
1758,
1071,
11732,
15229,
2171,
31,
203,
203,
565,
463,
20463,
4243,
1071,
11732,
15229,
4243,
31,
203,
203,
565,
6258,
7365,
5164,
1071,
11732,
1909,
7365,
5164,
31,
203,
203,
203,
5666,
288,
654,
39,
28275,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
474,
26362,
19,
654,
39,
28275,
18,
18281,
14432,
203,
5666,
288,
45,
28252,
97,
628,
315,
16644,
5471,
19,
8373,
19,
45,
28252,
18,
18281,
14432,
203,
5666,
288,
28252,
97,
628,
315,
16644,
5471,
19,
8373,
19,
28252,
18,
18281,
14432,
203,
5666,
288,
18485,
97,
628,
315,
16644,
3644,
19,
2414,
83,
19,
18485,
18,
18281,
14432,
203,
5666,
288,
5041,
5664,
97,
628,
315,
16644,
3644,
19,
9827,
19,
5041,
5664,
18,
18281,
14432,
203,
5666,
288,
2640,
654,
39,
3657,
9599,
3886,
97,
628,
315,
16644,
5471,
19,
3886,
18,
18281,
14432,
203,
5666,
288,
3773,
8791,
97,
628,
315,
6216,
4094,
19,
7422,
19,
3773,
8791,
18,
18281,
14432,
203,
5666,
288,
3773,
7365,
5164,
97,
628,
315,
6216,
4094,
19,
8401,
19,
3773,
7365,
5164,
18,
18281,
14432,
203,
5666,
288,
2816,
13375,
16,
6258,
7365,
1957,
97,
628,
315,
6216,
4094,
19,
8401,
19,
3773,
7365,
5164,
13375,
18,
18281,
14432,
203,
5666,
288,
45,
3773,
7365,
97,
628,
315,
6216,
4094,
19,
8401,
19,
45,
3773,
7365,
18,
18281,
14432,
203,
5666,
288,
18485,
4243,
97,
628,
25165,
18485,
2
] |
pragma ton-solidity >=0.44.0;
pragma AbiHeader time;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
//================================================================================
//
/// @title DexDebot
/// @author Augual.Team
/// @notice Debot for Augual.DEX (LiquiSOR) service
//================================================================================
//
import "../interfaces/IDexFactory.sol";
import "../interfaces/ISymbolPair.sol";
import "../interfaces/ILiquidFTRoot.sol";
import "../interfaces/ILiquidFTWallet.sol";
import "../interfaces/IDebot.sol";
import "../interfaces/IUpgradable.sol";
import "../interfaces/debot/address.sol";
import "../interfaces/debot/amount.sol";
import "../interfaces/debot/menu.sol";
import "../interfaces/debot/number.sol";
import "../interfaces/debot/sdk.sol";
import "../interfaces/debot/terminal.sol";
//================================================================================
//
interface IMsig
{
/// @dev Allows custodian if she is the only owner of multisig to transfer funds with minimal fees.
/// @param dest Transfer target address.
/// @param value Amount of funds to transfer.
/// @param bounce Bounce flag. Set true if need to transfer funds to existing account;
/// set false to create new account.
/// @param flags `sendmsg` flags.
/// @param payload Tree of cells used as body of outbound internal message.
function sendTransaction(
address dest,
uint128 value,
bool bounce,
uint8 flags,
TvmCell payload) external view;
}
//================================================================================
//
contract DexDebot is Debot, Upgradable
{
//TvmCell _domainCode;
//TvmCell _deployerCode;
address _factoryAddress;
address _symbolPairAddress;
int8 _symbolPairAccState;
address _msigAddress;
Symbol[] _symbolsList;
Symbol _selectedSymbol1;
Symbol _selectedSymbol2;
address _lpWalletAddress;
uint128 _depositAmount1;
uint128 _depositAmount2;
uint16 _depositSlippage;
// Provide liquidity
Symbol _provideLiquiditySymbol;
address _provideLiquidityWalletAddress;
// Trade
Symbol _tradeSellSymbol;
Symbol _tradeBuySymbol;
address _tradeSellWalletAddress;
address _tradeBuyWalletAddress;
uint128 _sellAmount;
uint128 _buyAmount;
/*string ctx_name;
address ctx_domain;
DnsWhois ctx_whois;
int8 ctx_accState;
uint8 ctx_segments;
address ctx_parent;*/
optional(uint256) _emptyPk;
uint128 constant ATTACH_VALUE = 0.5 ton;
//========================================
//
constructor(address ownerAddress) public
{
_ownerAddress = ownerAddress;
tvm.accept();
}
//========================================
//
function setFactoryAddress(address factoryAddress) public {
require(msg.pubkey() == tvm.pubkey() || senderIsOwner(), 100);
tvm.accept();
_factoryAddress = factoryAddress;
}
//========================================
//
function getRequiredInterfaces() public pure returns (uint256[] interfaces)
{
return [Terminal.ID, AddressInput.ID, NumberInput.ID, AmountInput.ID, Menu.ID];
}
//========================================
//
function getDebotInfo() public functionID(0xDEB) view returns(string name, string version, string publisher, string key, string author,
address support, string hello, string language, string dabi, bytes icon)
{
name = "LiquiSOR DEX DeBot (Augual.TEAM)";
version = "0.2.0";
publisher = "Augual.TEAM";
key = "LiquiSOR DEX from Augual.TEAM";
author = "Augual.TEAM";
support = addressZero;
hello = "Welcome to LiquiSOR DEX DeBot!";
language = "en";
dabi = m_debotAbi.hasValue() ? m_debotAbi.get() : "";
icon = m_icon.hasValue() ? m_icon.get() : "";
}
//========================================
/// @notice Define DeBot version and title here.
function getVersion() public override returns (string name, uint24 semver)
{
(name, semver) = ("DexDebot", _version(0, 2, 0));
}
function _version(uint24 major, uint24 minor, uint24 fix) private pure inline returns (uint24)
{
return (major << 16) | (minor << 8) | (fix);
}
//========================================
// Implementation of Upgradable
function onCodeUpgrade() internal override
{
tvm.resetStorage();
}
//========================================
//
function onError(uint32 sdkError, uint32 exitCode) public
{
// if (exitCode == ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER) { Terminal.print(0, "Failed! You're not the owner of this domain."); }
//else if (exitCode == ERROR_REQUIRE_INTERNAL_MESSAGE_WITH_VALUE) { Terminal.print(0, "Failed! No value attached."); }
//else if (exitCode == ERROR_DOMAIN_IS_EXPIRED) { Terminal.print(0, "Failed! Domain is expired."); }
//else if (exitCode == ERROR_DOMAIN_IS_NOT_EXPIRED) { Terminal.print(0, "Failed! Domain is not expired."); }
//else if (exitCode == ERROR_CAN_NOT_PROLONGATE_YET) { Terminal.print(0, "Failed! Can't prolong yet."); }
//else if (exitCode == ERROR_NOT_ENOUGH_MONEY) { Terminal.print(0, "Failed! Not enough value attached to cover domain price."); }
//else
{
Terminal.print(0, format("Failed! SDK Error: {}. Exit Code: {}", sdkError, exitCode));
}
mainMenu(0);
}
//========================================
// Inline functions
function _sortSymbols(Symbol sym1, Symbol sym2) internal inline pure returns (Symbol, Symbol)
{
return (sym1.addressRTW < sym2.addressRTW ? (sym1, sym2) : (sym2, sym1));
}
//========================================
/// @notice Entry point function for DeBot.
function start() public override
{
mainMenu(0);
}
//========================================
//
function _eraseCtx() internal
{
_msigAddress = addressZero;
delete _symbolsList;
/*ctx_domain = addressZero;
ctx_name = "";
ctx_accState = 0;
ctx_segments = 0;
ctx_parent = addressZero;
delete ctx_whois; // reset custom struct without specifying all the members*/
}
//========================================
//
function getSymbolRepresentation(Symbol symbol) public pure returns (string)
{
string text;
text.append("(");
text.append(symbol.symbol);
text.append(") ");
text.append(symbol.name);
return text;
}
//========================================
//
function mainMenu(uint32 index) public
{
_eraseCtx();
index = 0; // shut a warning
if(_factoryAddress == addressZero)
{
//Terminal.print(0, "DeBot is being upgraded.\nPlease come back in a minute.\nSorry for inconvenience.");
return;
}
AddressInput.get(tvm.functionId(onMsigEnter), "Let's start with entering your Multisig Wallet address: ");
}
//========================================
//
function onMsigEnter(address value) public
{
_msigAddress = value;
_refreshSymbols_1(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _refreshSymbols_1(uint32 index) public view
{
index = 0; // shut a warning
IDexFactory(_factoryAddress).getSymbolsList{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_refreshSymbols_2),
onErrorId: tvm.functionId(onError)
}();
}
function _refreshSymbols_2(Symbol[] symbols) public
{
_symbolsList = symbols;
_mainLoop(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _mainLoop(uint32 index) public
{
index = 0; // shut a warning
MenuItem[] mi;
mi.push(MenuItem("List Symbols", "", tvm.functionId(_listSymbols_1) ));
mi.push(MenuItem("Refresh Symbols", "", tvm.functionId(_refreshSymbols_1) ));
mi.push(MenuItem("Add Symbol", "", tvm.functionId(_addSymbol_1) ));
mi.push(MenuItem("Get Symbol Pair", "", tvm.functionId(_getSymbolPair_1) ));
mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", mi);
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _listSymbols_1(uint32 index) public
{
index = 0; // shut a warning
string text;
for(Symbol symbol : _symbolsList)
{
if(text.byteLength() > 0){ text.append("\n"); }
text.append(getSymbolRepresentation(symbol));
}
Terminal.print(0, text);
_mainLoop(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _addSymbol_1(uint32 index) public
{
index = 0; // shut a warning
AddressInput.get(tvm.functionId(_addSymbol_2), "Please enter TRC-6 RTW address: ");
}
function _addSymbol_2(address value) public
{
TvmCell body = tvm.encodeBody(IDexFactory.addSymbol, value);
_sendTransact(_msigAddress, _factoryAddress, body, ATTACH_VALUE);
_addSymbol_3(0);
}
function _addSymbol_3(uint32 index) public
{
index = 0; // shut a warning
Terminal.print(0, "Adding symbol, please wait for ~10 seconds and refresh Symbols list");
_mainLoop(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _getSymbolPair_1(uint32 index) public
{
index = 0; // shut a warning
delete _selectedSymbol1;
delete _selectedSymbol2;
Terminal.print(0, "Please choose the first Symbol:");
MenuItem[] mi;
for(Symbol symbol : _symbolsList)
{
mi.push(MenuItem(getSymbolRepresentation(symbol), "", tvm.functionId(_getSymbolPair_2)));
}
Menu.select("Enter your choice: ", "", mi);
}
function _getSymbolPair_2(uint32 index) public
{
_selectedSymbol1 = _symbolsList[index];
Terminal.print(0, "Please choose the second Symbol:");
MenuItem[] mi;
for(Symbol symbol : _symbolsList)
{
//if(symbol.addressRTW == _selectedSymbol1.addressRTW) { continue; }
mi.push(MenuItem(getSymbolRepresentation(symbol), "", tvm.functionId(_getSymbolPair_3)));
}
Menu.select("Enter your choice: ", "", mi);
}
function _getSymbolPair_3(uint32 index) public
{
_selectedSymbol2 = _symbolsList[index];
if(_selectedSymbol2.addressRTW == _selectedSymbol1.addressRTW)
{
Terminal.print(0, "You can't choose same Symbol twice!");
_getSymbolPair_1(0);
return;
}
//(_selectedSymbol1, _selectedSymbol2) = _sortSymbols(_selectedSymbol1, _selectedSymbol2);
IDexFactory(_factoryAddress).getPairAddress{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_getSymbolPair_4),
onErrorId: tvm.functionId(onError)
}(_selectedSymbol1.addressRTW, _selectedSymbol2.addressRTW);
}
function _getSymbolPair_4(address value) public
{
_symbolPairAddress = value;
Sdk.getAccountType(tvm.functionId(_getSymbolPair_5), _symbolPairAddress);
}
function _getSymbolPair_5(int8 acc_type) public
{
_symbolPairAccState = acc_type;
_getSymbolPair_6(0);
}
function _getSymbolPair_6(uint32 index) public
{
index = 0; // shut a warning
if (_symbolPairAccState == -1 || _symbolPairAccState == 0)
{
Terminal.print(0, format("Symbol Pair does not exist!"));
MenuItem[] mi;
mi.push(MenuItem("Deploy Pair", "", tvm.functionId(_symbolPairDeploy_1)));
mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) ));
mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", mi);
}
else if (_symbolPairAccState == 1)
{
_symbolPairMenu_1(0);
}
else if (_symbolPairAccState == 2)
{
Terminal.print(0, format("Symbol Pair is FROZEN."));
_mainLoop(0);
}
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _symbolPairDeploy_1(uint32 index) public
{
index = 0; // shut a warning
TvmCell body = tvm.encodeBody(IDexFactory.addPair, _selectedSymbol1.addressRTW, _selectedSymbol2.addressRTW);
_sendTransact(_msigAddress, _factoryAddress, body, ATTACH_VALUE * 2);
_symbolPairDeploy_2(1);
}
function _symbolPairDeploy_2(uint32 index) public
{
index = 0; // shut a warning
Sdk.getAccountType(tvm.functionId(_symbolPairDeploy_3), _symbolPairAddress);
}
function _symbolPairDeploy_3(int8 acc_type) public
{
// Loop like crazy until we get the Pair
if(acc_type == 1) { _symbolPairMenu_1(0); }
else { _symbolPairDeploy_2(0); }
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _symbolPairMenu_1(uint32 index) public view
{
index = 0; // shut a warning
ISymbolPair(_symbolPairAddress).getPairLiquidity{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairMenu_2),
onErrorId: tvm.functionId(onError)
}();
}
function _symbolPairMenu_2(Symbol symbol1, Symbol symbol2, uint256 liquidity, uint8 decimals) public
{
_selectedSymbol1 = symbol1;
_selectedSymbol2 = symbol2;
// TODO: show Pair info;
string text1 = format("SYMBOL 1\nName: {}\nSymbol: {}\nDecimals: {}\nIn Pool: {}", symbol1.name, symbol1.symbol, symbol1.decimals, symbol1.balance);
string text2 = format("SYMBOL 2\nName: {}\nSymbol: {}\nDecimals: {}\nIn Pool: {}", symbol2.name, symbol2.symbol, symbol2.decimals, symbol2.balance);
string text3 = format("Liquidity: {}\nLiquidity decimals: {}", liquidity, decimals);
Terminal.print(0, text1);
Terminal.print(0, text2);
Terminal.print(0, text3);
MenuItem[] mi;
mi.push(MenuItem("Trade", "", tvm.functionId(_symbolPairTrade_1) ));
mi.push(MenuItem("Provide liquidity", "", tvm.functionId(_symbolPairProvideLiquidity_1) ));
mi.push(MenuItem("Get liquidity limbo", "", tvm.functionId(_symbolPairGetLiquidityLimbo_1) ));
mi.push(MenuItem("Deposit liquidity", "", tvm.functionId(_symbolPairDepositLiquidity_1) ));
mi.push(MenuItem("Withdraw liquidity", "", tvm.functionId(_symbolPairWithdrawLiquidity_1) ));
mi.push(MenuItem("Withdraw leftovers", "", tvm.functionId(_symbolPairWithdrawLiquidityLeftovers_1)));
mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) ));
mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", mi);
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _symbolPairGetLiquidityLimbo_1(uint32 index) public view
{
index = 0; // shut a warning
ISymbolPair(_symbolPairAddress).getUserLimbo{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairGetLiquidityLimbo_2),
onErrorId: tvm.functionId(onError)
}(_msigAddress);
}
function _symbolPairGetLiquidityLimbo_2(uint128 amount1, uint128 amount2) public
{
Terminal.print(0, format("Symbol1: {}\nSymbol2: {}", amount1, amount2));
_symbolPairMenu_1(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
// TODO: including wallet deployment
function _symbolPairTrade_1(uint32 index) public
{
index = 0; // shut a warning
delete _tradeSellSymbol;
delete _tradeBuySymbol;
Terminal.print(0, format("Select a symbol to sell:"));
MenuItem[] mi;
mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol1), "", tvm.functionId(_symbolPairTrade_2) ));
mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol2), "", tvm.functionId(_symbolPairTrade_2) ));
mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) ));
mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", mi);
}
function _symbolPairTrade_2(uint32 index) public
{
_tradeSellSymbol = (index == 0 ? _selectedSymbol1 : _selectedSymbol2);
_tradeBuySymbol = (index == 0 ? _selectedSymbol2 : _selectedSymbol1);
ILiquidFTRoot(_tradeSellSymbol.addressRTW).getWalletAddress{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairTrade_3),
onErrorId: tvm.functionId(onError)
}(_msigAddress);
}
function _symbolPairTrade_3(address value) public
{
_tradeSellWalletAddress = value;
Sdk.getAccountType(tvm.functionId(_symbolPairTrade_4), _tradeSellWalletAddress);
}
function _symbolPairTrade_4(int8 acc_type) public
{
if (acc_type == -1 || acc_type == 0)
{
Terminal.print(0, format("You don't have a Token wallet, you can't trade!"));
_symbolPairMenu_1(0);
}
else if (acc_type == 1)
{
_symbolPairTrade_5(0);
}
else if (acc_type == 2)
{
Terminal.print(0, format("Your Token wallet Wallet is FROZEN."));
_mainLoop(0);
}
}
function _symbolPairTrade_5(uint32 index) public view
{
index = 0; // shut a warning
ILiquidFTRoot(_tradeBuySymbol.addressRTW).getWalletAddress{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairTrade_6),
onErrorId: tvm.functionId(onError)
}(_msigAddress);
}
function _symbolPairTrade_6(address value) public
{
_tradeBuyWalletAddress = value;
Sdk.getAccountType(tvm.functionId(_symbolPairTrade_7), _tradeBuyWalletAddress);
}
function _symbolPairTrade_7(int8 acc_type) public
{
if (acc_type == -1 || acc_type == 0)
{
Terminal.print(0, format("Deploy receiver TTW first!"));
TvmCell body = tvm.encodeBody(ILiquidFTRoot.createWallet, _msigAddress, addressZero, 0);
_sendTransact(_msigAddress, _tradeBuySymbol.addressRTW, body, ATTACH_VALUE);
_symbolPairTrade_8(0);
}
else if (acc_type == 1)
{
_symbolPairTrade_8(0);
}
else if (acc_type == 2)
{
Terminal.print(0, format("Your Token wallet Wallet is FROZEN."));
_mainLoop(0);
}
}
function _symbolPairTrade_8(uint32 index) public
{
index = 0; // shut a warning
AmountInput.get(tvm.functionId(_symbolPairTrade_9), format("Enter amount of {} to sell: ", _tradeSellSymbol.symbol), _tradeSellSymbol.decimals, 0, 999999999999999999999999999999);
}
function _symbolPairTrade_9(uint256 value) public
{
_sellAmount = uint128(value);
ISymbolPair(_symbolPairAddress).getPrice{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairTrade_10),
onErrorId: tvm.functionId(onError)
}(_tradeSellSymbol.addressRTW, _sellAmount);
}
function _symbolPairTrade_10(uint128 amount, uint8 decimals) public
{
_buyAmount = amount;
decimals = 0; // shut a warning
Terminal.print(0, format("You are selling {} amount of {} and will get {} amount of {} in return. OK?", _sellAmount, _tradeSellSymbol.symbol, _buyAmount, _tradeBuySymbol.symbol));
MenuItem[] mi;
mi.push(MenuItem("YES", "", tvm.functionId(_symbolPairTrade_11) ));
mi.push(MenuItem("Nah, get me out", "", tvm.functionId(_symbolPairMenu_1) ));
Menu.select("Enter your choice: ", "", mi);
}
function _symbolPairTrade_11(uint32 index) public view
{
index = 0; // shut a warning
TvmBuilder builder;
builder.store(uint8(0), _buyAmount, uint16(500)); // TODO: slippage is forced to 5%, ash user to enter number instead
TvmCell body = tvm.encodeBody(ILiquidFTWallet.transfer, uint128(_sellAmount), _symbolPairAddress, _msigAddress, addressZero, builder.toCell());
_sendTransact(_msigAddress, _tradeSellWalletAddress, body, ATTACH_VALUE);
_symbolPairMenu_1(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _symbolPairProvideLiquidity_1(uint32 index) public
{
index = 0; // shut a warning
delete _provideLiquiditySymbol;
MenuItem[] mi;
mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol1), "", tvm.functionId(_symbolPairProvideLiquidity_2) ));
mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol2), "", tvm.functionId(_symbolPairProvideLiquidity_2) ));
mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) ));
mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", mi);
}
function _symbolPairProvideLiquidity_2(uint32 index) public
{
_provideLiquiditySymbol = (index == 0 ? _selectedSymbol1 : _selectedSymbol2);
ILiquidFTRoot(_provideLiquiditySymbol.addressRTW).getWalletAddress{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairProvideLiquidity_3),
onErrorId: tvm.functionId(onError)
}(_msigAddress);
}
function _symbolPairProvideLiquidity_3(address value) public
{
_provideLiquidityWalletAddress = value;
Sdk.getAccountType(tvm.functionId(_symbolPairProvideLiquidity_4), _provideLiquidityWalletAddress);
}
function _symbolPairProvideLiquidity_4(int8 acc_type) public
{
if (acc_type == -1 || acc_type == 0)
{
Terminal.print(0, format("You don't have a Token wallet!"));
_symbolPairMenu_1(0);
}
else if (acc_type == 1)
{
_symbolPairProvideLiquidity_5(0);
}
else if (acc_type == 2)
{
Terminal.print(0, format("Your Token wallet Wallet is FROZEN."));
_mainLoop(0);
}
}
function _symbolPairProvideLiquidity_5(uint32 index) public
{
index = 0; // shut a warning
AmountInput.get(tvm.functionId(_symbolPairProvideLiquidity_6), format("Enter amount of {} to deposit: ", _provideLiquiditySymbol.symbol), _provideLiquiditySymbol.decimals, 0, 999999999999999999999999999999);
}
function _symbolPairProvideLiquidity_6(uint256 value) public view
{
TvmBuilder builder;
builder.store(uint8(1), uint128(0), uint16(0));
TvmCell body = tvm.encodeBody(ILiquidFTWallet.transfer, uint128(value), _symbolPairAddress, _msigAddress, addressZero, builder.toCell());
_sendTransact(_msigAddress, _provideLiquidityWalletAddress, body, ATTACH_VALUE);
_symbolPairMenu_1(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
// TODO: including LP wallet deployment
function _symbolPairDepositLiquidity_1(uint32 index) public view
{
index = 0; // shut a warning
ILiquidFTRoot(_symbolPairAddress).getWalletAddress{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairDepositLiquidity_2),
onErrorId: tvm.functionId(onError)
}(_msigAddress);
}
function _symbolPairDepositLiquidity_2(address value) public
{
_lpWalletAddress = value;
Sdk.getAccountType(tvm.functionId(_symbolPairDepositLiquidity_3), _lpWalletAddress);
}
function _symbolPairDepositLiquidity_3(int8 acc_type) public
{
if (acc_type == -1 || acc_type == 0)
{
// TODO: notify that we are deploying LP wallet; +
// also, check that wallet was created;
Terminal.print(0, "You don't have LP wallet, deploy?");
TvmCell body = tvm.encodeBody(ILiquidFTRoot.createWallet, _msigAddress, addressZero, 0);
_sendTransact(_msigAddress, _symbolPairAddress, body, ATTACH_VALUE);
_symbolPairDepositLiquidity_4(0);
}
else if (acc_type == 1)
{
_symbolPairDepositLiquidity_4(0);
}
else if (acc_type == 2)
{
Terminal.print(0, format("Your LP Wallet is FROZEN."));
_mainLoop(0);
}
}
function _symbolPairDepositLiquidity_4(uint32 index) public
{
index = 0; // shut a warning
AmountInput.get(tvm.functionId(_symbolPairDepositLiquidity_5), format("Enter amount of {} to deposit: ", _selectedSymbol1.symbol), _selectedSymbol1.decimals, 0, 999999999999999999999999999999);
}
function _symbolPairDepositLiquidity_5(uint256 value) public
{
_depositAmount1 = uint128(value);
AmountInput.get(tvm.functionId(_symbolPairDepositLiquidity_6), format("Enter amount of {} to deposit: ", _selectedSymbol2.symbol), _selectedSymbol2.decimals, 0, 999999999999999999999999999999);
}
function _symbolPairDepositLiquidity_6(uint256 value) public
{
_depositAmount2 = uint128(value);
AmountInput.get(tvm.functionId(_symbolPairDepositLiquidity_7), "Enter Slippage in %: ", 2, 0, 10000);
}
function _symbolPairDepositLiquidity_7(uint256 value) public
{
_depositSlippage = uint16(value);
// TODO: text?
TvmCell body = tvm.encodeBody(ISymbolPair.depositLiquidity, _depositAmount1, _depositAmount2, uint16(_depositSlippage));
_sendTransact(_msigAddress, _symbolPairAddress, body, ATTACH_VALUE);
_symbolPairMenu_1(0);
}
//========================================
//========================================
//========================================
//========================================
//========================================
// TODO: we catually can be missing TTWs if we just bought liquidity tokens
function _symbolPairWithdrawLiquidity_1(uint32 index) public view
{
index = 0; // shut a warning
ILiquidFTRoot(_symbolPairAddress).getWalletAddress{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairWithdrawLiquidity_2),
onErrorId: tvm.functionId(onError)
}(_msigAddress);
}
function _symbolPairWithdrawLiquidity_2(address value) public
{
_lpWalletAddress = value;
Sdk.getAccountType(tvm.functionId(_symbolPairWithdrawLiquidity_3), _lpWalletAddress);
}
function _symbolPairWithdrawLiquidity_3(int8 acc_type) public
{
if (acc_type == -1 || acc_type == 0)
{
// TODO: notify that we are deploying LP wallet; +
// also, check that wallet was created;
Terminal.print(0, "Oops, looks like you don't have LP wallet, that means you don't have liquidity to withdraw (sorry bout that).");
_symbolPairMenu_1(0);
}
else if (acc_type == 1)
{
_symbolPairWithdrawLiquidity_4(0);
}
else if (acc_type == 2)
{
Terminal.print(0, format("Your LP Wallet is FROZEN (oopsie)."));
_symbolPairMenu_1(0);
}
}
function _symbolPairWithdrawLiquidity_4(uint32 index) public view
{
index = 0; // shut a warning
ILiquidFTWallet(_lpWalletAddress).getBalance{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: _emptyPk,
callbackId: tvm.functionId(_symbolPairWithdrawLiquidity_5),
onErrorId: tvm.functionId(onError)
}();
}
function _symbolPairWithdrawLiquidity_5(uint128 balance) public
{
Terminal.print(0, format("You currently have {} Liquidity tokens.", balance));
AmountInput.get(tvm.functionId(_symbolPairWithdrawLiquidity_6), "Enter amount to withdraw: ", 18, 0, 999999999999999999999999999999);
}
function _symbolPairWithdrawLiquidity_6(int256 value) public view
{
TvmCell body = tvm.encodeBody(ILiquidFTWallet.burn, uint128(value));
_sendTransact(_msigAddress, _lpWalletAddress, body, ATTACH_VALUE);
_symbolPairMenu_1(0); // TODO: other menu? maybe some message?
}
//========================================
//========================================
//========================================
//========================================
//========================================
//
function _symbolPairWithdrawLiquidityLeftovers_1(uint32 index) public view
{
index = 0; // shut a warning
TvmCell body = tvm.encodeBody(ISymbolPair.collectLiquidityLeftovers);
_sendTransact(_msigAddress, _symbolPairAddress, body, ATTACH_VALUE);
_symbolPairMenu_1(0); // TODO: other menu? maybe some message?
}
//========================================
//
// 1. main menu: add symbol, get symbol pair to trade
// 2.1. if adding symbol, enter rtw address;
// 2.2. after entering send transaction and go to main menu
// 3.1. if getting symbol, show list of symbols to choose 1st
// 3.2. show list of symbols to choose 2nd
// 3.3. check if pair exists, if it doesn't ask to deploy it
// 3.4. if pair exists get pair information and show current info.
// 4. get three wallets silently (we need to know if user has wallet A, wallet B and liquidity wallet)
// 4. you need to choose, buy, sell, deposit, finalize or withdraw leftovers;
// 4.1. if depositing, if walletA or walletB doesn't exist, say you can't deposit without wallets and go to menu 4;
// 4.3. ask to send amount of symbol A
// 4.4. ask to send amount of symbol B
// 4.5. if finalizing, ask to create LP wallet if it doesn't exist;
// 4.6. if finalizing, show current leftovers and pair ratio ask the amount symbol A to deposit;
// 4.7. calculate symbol B based on amount, ask what slippage is good;
// 4.8. send finalize;
// 5. if buying, ask to create wallets that you don't have before that;
// 5.1. after that ask for the amount to buy;
// 5.2. ask for the slippage to buy;
// 5.3. send transaction;
// 6. if withdraw leftovers, we know that both wallets exist, just do that;
//========================================
//
function _sendTransact(address msigAddr, address dest, TvmCell payload, uint128 grams) internal pure
{
IMsig(msigAddr).sendTransaction{
abiVer: 2,
extMsg: true,
sign: true,
callbackId: 0,
onErrorId: tvm.functionId(onError),
time: uint32(now),
expire: 0,
pubkey: 0x00
}(dest,
grams,
false,
1,
payload);
}
}
//================================================================================
// | ======================================================================================================================================================================================================== | function _addSymbol_1(uint32 index) public
{
AddressInput.get(tvm.functionId(_addSymbol_2), "Please enter TRC-6 RTW address: ");
}
| 6,478,828 | [
1,
9917,
9917,
22121,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1289,
5335,
67,
21,
12,
11890,
1578,
770,
13,
1071,
203,
565,
288,
203,
3639,
5267,
1210,
18,
588,
12,
88,
3489,
18,
915,
548,
24899,
1289,
5335,
67,
22,
3631,
315,
8496,
6103,
4235,
39,
17,
26,
13060,
59,
1758,
30,
315,
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
] |
// @Author: Yuexin Xiang
// @Email: [email protected]
//Remix Compiler 0.4.24+conmmit.e67f0147
pragma solidity >=0.4.22 <0.7.0;
contract Scheme {
/************************DEFINE************************/
uint256 Value_Amount;//The amount of the transaction
uint256 Value_Deposit;//The deposi of the transaction
uint256 Time_First;//Record the time Bob finished the first step(Bob pays)
uint256 Time_Second;//Record the time Alice finished the second step(Alice sends encrypted key)
uint256 Time_Third;//Record the time Bob finished the third step(Bob reports)
uint256 Time_Rep = 300 seconds;//The time Bob can send report after transaction is finished
uint256 Time_Trans = 300 seconds;//The time limit of each step
string PubKey_Buyer;//Bob's public key
string EncryptedKey_Seller;//Alice's key encrypted(EK) by Bob's PK
string EvidenceKey;//Bob sends the key he recieved as evidence to the smart contract
string ReasonType;//Bob chooses the reason for reporting Alice
string Hash_Data;//Alice's selling data(verify by web)
string Hash_Key;//Alice's key's hash value(verify by web)
address public AddressPay;//Alice can recieve the money by the address
address public AddressBuyer;//The address of Bob
address public AddressVerify;//The address of the person who helps veriifying
string public DataAddress = "www.cugdatatrade.com";//The adress of the big data
string public CalHash = "https://emn178.github.io/online-tools/sha256_checksum.html";//The web for calculating sha256
bool Goal_Amount = false;//Judge if Alice sets the amount
bool Goal_HashData = false;//Judge if Alice uploads Hash value of the data
bool Goal_HashKey = false;//Judge if Alice uploads Hash value of the key
bool Goal_Deposit = false;//Judge if Alice sends the deposit
bool Goal_Money = false;//Judge if Bob sends the money
bool Goal_PubKeyB = false;//Judge if Bob sends his public key
bool Goal_EnK = false;//Judge if Alice sends the encrypted key
bool Goal_GotRep = false;//Jugde if Bob sends the report
bool Goal_Verify = false;//Judge if the report sent by Bob is true
bool Goal_Success = false;//Judge if the transaction is successful
bool Goal_First = false;//Judge if the time of first step is run out
bool Goal_Second = false;//Judge if the time of second step is run out
bool Goal_Third = false;//Judge if the time of third step is run out
event SetAmountAndDeposit(uint);
event UploadHashData(string);
event UploadHashKey(string);
event GotMoney(uint,address);
event GotDeposit(uint,address);
event UploadPubKeyB(string);
event UploadEncrypedKey(string);
event GotReport(string,string);
event VerifyResult(bool);
event TransResult(bool);
/************************INIT************************/
//The constructor of the smart contract
constructor () public payable {
AddressPay = msg.sender;
}
//Show the time now
function CurrTimeInSeconds() public view returns (uint256) {
return now;
}
/************************VIEW************************/
//View the amount of the transaction
function get_amount () public view returns (uint256) {
return Value_Amount;
}
//View the deposit of the transaction
function get_deposit () public view returns (uint256) {
return Value_Deposit;
}
//View the Bob's public key of the transaction
function get_pubkeyB() view public returns(string) {
return PubKey_Buyer;
}
//View the encrypted key of Alice
function get_enkey () view public returns(string) {
return EncryptedKey_Seller;
}
//View the hash value of the key of Alice
function get_hash_key () view public returns(string) {
return Hash_Key;
}
//View the hash value of the encrypted data
function get_hash_data () view public returns(string) {
return Hash_Data;
}
/*
//View the status of goal of amount
function goal_amount () view public returns(bool) {
return Goal_Amount;
}
//View the status of goal of deposit
function goal_deposit () view public returns(bool) {
return Goal_Deposit;
}
//View the status of goal of hash
function goal_hash () view public returns(bool) {
return Goal_Hash;
}
//View the status of goal of money
function goal_money () view public returns(bool) {
return Goal_Money;
}
//View the status of goal of public key of Bob
function goal_pubkeyB () view public returns(bool) {
return Goal_PubKeyB;
}
//View the status of goal of encrypted key
function goal_enkey () view public returns(bool) {
return Goal_EnK;
}
//View the status of goal of transaction
function goal_success () view public returns(bool) {
return Goal_Success;
}
//View the status of goal of verfication
function goal_verify () view public returns(bool) {
return Goal_Verify;
}
//View the status of first step
function goal_first () view public returns(bool) {
return Goal_First;
}
//View the status of second step
function goal_second () view public returns(bool) {
return Goal_Second;
}
//View the status of third step
function goal_third () view public returns(bool) {
return Goal_Third;
}
*/
//View the time Bob finished the first step
function view_first () public view returns (uint256){
return Time_First;
}
//View the time Alice finished the second step
function view_second () public view returns (uint256){
return Time_Second;
}
//View the time Alice finished the third step
function view_third () public view returns (uint256){
return Time_Third;
}
//View the evidence and reason
function show_evidence_reason () view public returns(string, string) {
return (EvidenceKey, ReasonType);
}
//Show the type of the reason
function show_reason () pure public returns(string) {
return "Type-1: Wrong key || Type-2: Messy watermark || Type-3: Two or more watermarks";
}
//Inquire the amount of a specific account
function get_balance (address AccountOrContract) constant public returns(uint) {
return AccountOrContract.balance;
}
/************************PROCESS************************/
//Alice sets the amount and deposit of the trasnsaction
function set_amount (uint256 Amount) public {
if (msg.sender == AddressPay) {
Value_Amount = Amount;
Value_Deposit = 2 * Value_Amount;
Goal_Amount = true;
emit SetAmountAndDeposit(Value_Amount);
}
else {
Goal_Amount = false;
revert("Wrong input.");
}
}
//Alice uploads the hash value of the data
function upload_hash_data (string HashData) public {
if (Goal_Amount == true) {
if (msg.sender == AddressPay) {
Hash_Data = HashData;
Goal_HashData = true;
emit UploadHashData(Hash_Data);
}
else {
Goal_HashData = false;
revert("Only the seller can upload hash value of the data.");
}
}
else {
Goal_HashData = false;
revert("Please set the amount first.");
}
}
//Alice uploads the hash value of the key
function upload_hash_key (string HashKey) public {
if (Goal_HashData == true) {
if (msg.sender == AddressPay) {
Hash_Key = HashKey;
Goal_HashKey = true;
emit UploadHashKey(Hash_Key);
}
else {
Goal_HashKey = false;
revert("Only the seller can upload hash value of the key.");
}
}
else {
Goal_HashKey = false;
revert("Please upload hash value of the data first.");
}
}
//Alice sends the deposit to the smart contract
function send_deposit () public payable returns(bool) {
if (Goal_HashKey == true) {
if (msg.sender == AddressPay) {
if (msg.value == Value_Deposit) {
Goal_Deposit = true;
Time_First = now;
emit GotDeposit(Value_Deposit, this);
return address(this).send(msg.value);
}
else {
Goal_Deposit = false;
revert("The value of the desposit is wrong.");
}
}
else {
Goal_Deposit = false;
revert("Only the seller can send the desposit.");
}
}
else {
Goal_Deposit = false;
revert("Please upload the hash value of the key first.");
}
}
//Bob sends the money to the smart contract
function send_money () public payable returns(bool) {
AddressBuyer = msg.sender;
if (Goal_Deposit == true) {
if (AddressBuyer != AddressPay) {
if (now <= Time_First + Time_Trans) {
Goal_Money = true;
Goal_First = true;
emit GotMoney(Value_Amount, this);
return address(this).send(msg.value);
}
else {
Goal_First = false;
revert("Time is run out (first step).");
}
}
else {
Goal_Money = false;
revert("Seller can not send the money.");
}
}
else {
Goal_Money = false;
revert("Seller should send deposit first.");
}
}
//Bob Uploads the public key
function upload_pubkey_buyer (string PubKey) public {
if (Goal_Money == true) {
if (AddressBuyer != AddressPay) {
PubKey_Buyer = PubKey;
Goal_PubKeyB = true;
Time_Second = now;
emit UploadPubKeyB(PubKey_Buyer);
}
else {
Goal_PubKeyB = false;
revert("Seller can not send the money.");
}
}
else {
Goal_PubKeyB = false;
revert("Buyer should send money first.");
}
}
//Alice uploads the encrypted key
function upload_encryptedkey (string EnKey) public {
if (Goal_Money == true) {
if (Goal_PubKeyB == true) {
if (msg.sender == AddressPay) {
if (now <= Time_Second + Time_Trans) {
EncryptedKey_Seller = EnKey;
Goal_EnK = true;
Goal_Second = true;
Time_Third = now;
emit UploadEncrypedKey(EncryptedKey_Seller);
}
else {
Goal_Second = false;
revert("Time is run out (second step).");
}
}
else {
Goal_EnK = false;
revert("Only seller can send encrypted key.");
}
}
else {
Goal_EnK = false;
revert("Please ask buyer to send public key first.");
}
}
else {
Goal_EnK = false;
revert("Please ask buyer to send money first.");
}
}
//Bob sends the report to the smart contract and the key is evidence
function report_send (string Evidence, string Reason) public {
if (Goal_EnK == true) {
if (msg.sender == AddressBuyer) {
if (now <= Time_Third + Time_Rep) {
EvidenceKey = Evidence;
ReasonType = Reason;
Goal_GotRep = true;
Goal_Third = true;
emit GotReport(EvidenceKey, ReasonType);
}
else {
Goal_Third = false;
revert("Time is run out (third step).");
}
}
else {
Goal_GotRep = false;
revert("Only the buyer can send the report.");
}
}
else {
Goal_GotRep = false;
revert("Plaese ask seller to send encrypted key first.");
}
}
//Others vertify the report sent by Bob
function report_verify (bool Verify) public {
if (Goal_GotRep == true) {
if (msg.sender != AddressPay && msg.sender != AddressBuyer) {
AddressVerify = msg.sender;
Goal_Verify = Verify;
emit VerifyResult(Goal_Verify);
}
else {
Goal_Verify = false;
revert("Only the third part can vertify the report.");
}
}
else {
Goal_Verify = false;
revert("Smart contract did not get the report.");
}
}
/************************RESULT************************/
//Different results of the transaction
function end_transaction () public {
//The transaction is successful
if (msg.sender == AddressBuyer &&
Goal_Amount == true &&
Goal_HashData == true &&
Goal_HashKey == true &&
Goal_Money == true &&
Goal_PubKeyB == true &&
Goal_EnK == true &&
Goal_Verify == false) {
Goal_Success = true;
emit TransResult(Goal_Success);
AddressPay.transfer(Value_Amount);
AddressPay.transfer(Value_Deposit);
}
//Only the seller pays but the time is run out
else if (msg.sender == AddressPay &&
Goal_Deposit == true &&
Goal_First == false) {
Goal_Success = false;
emit TransResult(Goal_Success);
AddressPay.transfer(Value_Deposit);
}
//Both pay but time is run out
else if (Goal_Money = true &&
Goal_Second == false) {
Goal_Success = false;
emit TransResult(Goal_Success);
AddressPay.transfer(Value_Deposit);
AddressBuyer.transfer(Value_Amount);
}
//If Bob does not send report and report time is run out Alice can end
else if (Goal_EnK == true &&
Goal_GotRep == false &&
(now > Time_Third + Time_Rep)) {
Goal_Success = true;
emit TransResult(Goal_Success);
AddressPay.transfer(Value_Amount);
AddressPay.transfer(Value_Deposit);
}
//Bob's report is right
else if (msg.sender == AddressVerify &&
Goal_GotRep == true &&
Goal_Verify == true) {
Goal_Success = false;
emit TransResult(Goal_Success);
AddressBuyer.transfer(Value_Deposit);
AddressBuyer.transfer(Value_Amount);
}
//Bob's report is wrong
else if (msg.sender == AddressVerify &&
Goal_GotRep == true &&
Goal_Verify == false) {
Goal_Success = false;
emit TransResult(Goal_Success);
AddressPay.transfer(Value_Deposit);
AddressPay.transfer(Value_Amount);
}
else
revert("Wait...");
}
}
| Judge if Alice sends the deposit
| bool Goal_Deposit = false; | 12,768,990 | [
1,
46,
27110,
309,
432,
2008,
9573,
326,
443,
1724,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
6430,
4220,
287,
67,
758,
1724,
273,
629,
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,
-100,
-100
] |
./full_match/8453/0xf9cFB8a62f50e10AdDE5Aa888B44cF01C5957055/sources/contracts/libraries/helpers/Errors.sol | 'There is not enough liquidity available to borrow'
| string internal constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = "80"; | 11,549,341 | [
1,
11,
9828,
353,
486,
7304,
4501,
372,
24237,
2319,
358,
29759,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
533,
2713,
5381,
511,
52,
67,
4400,
67,
1157,
26556,
16715,
67,
2053,
53,
3060,
4107,
67,
4296,
67,
38,
916,
11226,
273,
315,
3672,
14432,
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
] |
./partial_match/137/0xC71a0306a0A628C616DAC42097bDc21EcDBc5d9d/sources/contracts/ERC721Raffle.sol | solhint-disable-line
| constructor(address _renderer, address _usdcToken, address _link, address _vrfV2Wrapper, string memory _name, string memory _ticker) ERC721A(_name, _ticker) VRFV2WrapperConsumerBase(_link, _vrfV2Wrapper) { | 3,517,000 | [
1,
18281,
11317,
17,
8394,
17,
1369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
389,
14374,
16,
1758,
389,
407,
7201,
1345,
16,
1758,
389,
1232,
16,
1758,
389,
16825,
58,
22,
3611,
16,
533,
3778,
389,
529,
16,
533,
3778,
389,
88,
5448,
13,
4232,
39,
27,
5340,
37,
24899,
529,
16,
389,
88,
5448,
13,
776,
12918,
58,
22,
3611,
5869,
2171,
24899,
1232,
16,
389,
16825,
58,
22,
3611,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x26788a8f60E079356b05e13bfBA2a16AbE03AA05/sources/src/token/ERC1155/extensions/mintable/ERC1155Mintable.sol | * @title Extension of {ERC1155} that allows other facets of the diamond to mint based on arbitrary logic./ | abstract contract ERC1155Mintable is IERC1155Mintable, ERC1155BaseInternal {
function mintByFacet(
address to,
uint256 id,
uint256 amount,
bytes calldata data
) public virtual {
if (address(this) != msg.sender) {
revert ErrSenderIsNotSelf();
}
_mint(to, id, amount, data);
}
) public virtual {
if (address(this) != msg.sender) {
revert ErrSenderIsNotSelf();
}
_mint(to, id, amount, data);
}
function mintByFacet(
address[] calldata tos,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes[] calldata datas
) public virtual {
if (address(this) != msg.sender) {
revert ErrSenderIsNotSelf();
}
_mintBatch(tos, ids, amounts, datas);
}
function mintByFacet(
address[] calldata tos,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes[] calldata datas
) public virtual {
if (address(this) != msg.sender) {
revert ErrSenderIsNotSelf();
}
_mintBatch(tos, ids, amounts, datas);
}
}
| 7,046,001 | [
1,
3625,
434,
288,
654,
39,
2499,
2539,
97,
716,
5360,
1308,
21681,
434,
326,
4314,
301,
1434,
358,
312,
474,
2511,
603,
11078,
4058,
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
] | [
1,
1,
1,
1,
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,
17801,
6835,
4232,
39,
2499,
2539,
49,
474,
429,
353,
467,
654,
39,
2499,
2539,
49,
474,
429,
16,
4232,
39,
2499,
2539,
2171,
3061,
288,
203,
565,
445,
312,
474,
858,
11137,
12,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
612,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
501,
203,
203,
565,
262,
1071,
5024,
288,
203,
3639,
309,
261,
2867,
12,
2211,
13,
480,
1234,
18,
15330,
13,
288,
203,
5411,
15226,
1926,
12021,
28041,
10084,
5621,
203,
3639,
289,
203,
203,
3639,
389,
81,
474,
12,
869,
16,
612,
16,
3844,
16,
501,
1769,
203,
565,
289,
203,
203,
565,
262,
1071,
5024,
288,
203,
3639,
309,
261,
2867,
12,
2211,
13,
480,
1234,
18,
15330,
13,
288,
203,
5411,
15226,
1926,
12021,
28041,
10084,
5621,
203,
3639,
289,
203,
203,
3639,
389,
81,
474,
12,
869,
16,
612,
16,
3844,
16,
501,
1769,
203,
565,
289,
203,
203,
565,
445,
312,
474,
858,
11137,
12,
203,
3639,
1758,
8526,
745,
892,
358,
87,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
3258,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
30980,
16,
203,
3639,
1731,
8526,
745,
892,
5386,
203,
565,
262,
1071,
5024,
288,
203,
3639,
309,
261,
2867,
12,
2211,
13,
480,
1234,
18,
15330,
13,
288,
203,
5411,
15226,
1926,
12021,
28041,
10084,
5621,
203,
3639,
289,
203,
203,
3639,
389,
81,
474,
4497,
12,
14627,
16,
3258,
16,
30980,
16,
5386,
1769,
203,
565,
289,
203,
565,
445,
312,
2
] |
pragma solidity ^0.4.2;
/*
* 以太坊上的去中心化竞猜合约
* @Author Leo Ning <[email protected]>
* @Data 2018-07-06
*/
contract TrustBet {
address public owner;//合约所有者
bool public stop = false;//是否停止竞猜
uint8 public winTeam = 3;//比赛结果:3未开奖;0:1队胜;1:2队胜;2:2队平
uint256 public stopWithdrawBlock = 0;//停止提现区块
mapping(uint8 => mapping(address=>uint256)) public stakes;//竞猜金额
uint256[3] public teamStakes;//每队竞猜金额
//只能合约所有者执行的方法
modifier owned {
require(owner == msg.sender);
_;
}
//创建可信任竞猜合约
constructor () public {
owner = msg.sender;
}
//停止竞猜(发起人调用)
function stopBet() public owned {
stop = true;
}
// 开奖(发起人调用),team=0时1队赢,team=1时2队赢,team=2时2队打平
function lottery(uint8 team) public owned {
//已经停止竞猜且team正确才能开奖
require(stop && team < 3);
//赢的队伍
winTeam = team;
//130000个区块之后停止提现(大概开奖后15天内)
stopWithdrawBlock = block.number + 130000;
}
//竞猜,team=0时1队赢,team=1时2队赢,team=2时打平
function bet(uint8 team) public payable {
//未停止竞猜且team正确
require(!stop && team < 3 && msg.value >= 0.01 ether);
//用户竞猜总额
stakes[team][msg.sender] += msg.value;
//队伍竞猜总额
teamStakes[team] += msg.value;
}
//提取奖金
function withdraw() public returns (uint256) {
//开奖26000个区块内一定要提现且要猜中
require(stopWithdrawBlock>=block.number && stakes[winTeam][msg.sender]>0);
//竞猜金额
uint256 myStake = stakes[winTeam][msg.sender];
//钱分完了,不能再分喽,如果你有GAS,你可以无限次调用此方法
stakes[winTeam][msg.sender] = 0;
//计算奖金
uint256 win = myStake * (teamStakes[0] + teamStakes[1] + teamStakes[2]) / teamStakes[winTeam];
//扣除百分之一的手续费后的金额
uint256 amount = win - win * 1 / 100;
//奖金要大小0(^_^)
assert(amount > 0);
//有余额才能分
if(address(this).balance > amount){
msg.sender.transfer(amount);
return amount;
}
return 0;
}
//提取佣金
function commission() public {
//开奖26000个区块之后,竞猜发起人可以提取佣金
require(winTeam < 3 && stopWithdrawBlock<block.number && address(this).balance>0);
owner.transfer(address(this).balance);
}
} | 开奖(发起人调用),team=0时1队赢,team=1时2队赢,team=2时2队打平已经停止竞猜且team正确才能开奖赢的队伍130000个区块之后停止提现(大概开奖后15天内) | function lottery(uint8 team) public owned {
require(stop && team < 3);
winTeam = team;
stopWithdrawBlock = block.number + 130000;
}
| 5,493,003 | [
1,
166,
125,
227,
166,
103,
249,
176,
125,
235,
166,
242,
244,
169,
118,
120,
165,
123,
123,
169,
113,
230,
168,
247,
106,
176,
125,
236,
176,
125,
239,
10035,
33,
20,
167,
250,
119,
21,
170,
251,
258,
169,
118,
100,
176,
125,
239,
10035,
33,
21,
167,
250,
119,
22,
170,
251,
258,
169,
118,
100,
16,
10035,
33,
22,
167,
250,
119,
22,
170,
251,
258,
167,
236,
246,
166,
122,
116,
166,
120,
115,
168,
124,
242,
166,
228,
255,
167,
260,
100,
168,
109,
257,
168,
239,
255,
165,
121,
247,
10035,
167,
260,
101,
168,
99,
111,
167,
236,
240,
169,
230,
126,
166,
125,
227,
166,
103,
249,
169,
118,
100,
168,
253,
231,
170,
251,
258,
165,
125,
240,
3437,
2787,
165,
121,
108,
166,
239,
123,
166,
256,
250,
165,
122,
238,
166,
243,
241,
166,
228,
255,
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,
17417,
387,
93,
12,
11890,
28,
5927,
13,
1071,
16199,
288,
203,
3639,
2583,
12,
5681,
597,
5927,
411,
890,
1769,
203,
3639,
5657,
8689,
273,
5927,
31,
203,
3639,
2132,
1190,
9446,
1768,
273,
1203,
18,
2696,
397,
5958,
2787,
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
] |
./full_match/43113/0xFbA8b6d31ba648CC34247DD3D4282c457293E78C/sources/contracts/WOOFI.sol | [0] = owner, [1] = rewardToken, [2] = marketing wallet, [3] = router | contract WOOFI is ERC20Upgradeable, OwnableUpgradeable, IWOOFIToken {
using SafeMath for uint256;
uint256 private constant MAX = ~uint256(0);
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => bool) private _isExcluded;
bool private _swapping;
uint8 private _decimals;
uint256 private _tTotal;
uint256 private _rTotal;
uint256 private _tFeeTotal;
address[] private _excluded;
address private _marketingWalletAddress;
address public rewardToken;
uint256 public swapTokensAtAmount;
IRouter public router;
function initialize (
address[4] memory addrs,
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 totalSupply_
) external override initializer {
require(addrs[0] != addrs[2], "WOOFI: Owner and marketing wallet cannot be the same");
__ERC20_init(name_, symbol_);
__Ownable_init();
_decimals = decimals_;
_tTotal = totalSupply_;
_rTotal = (MAX - (MAX % _tTotal));
_marketingWalletAddress = addrs[2];
rewardToken = addrs[1];
router = IRouter(addrs[3]);
excludeAccount(addrs[0]);
excludeAccount(_marketingWalletAddress);
excludeAccount(address(this));
_tOwned[addrs[0]] = _tTotal;
_rOwned[addrs[0]] = _rTotal;
emit Transfer(address(0), addrs[0], _tTotal);
super.transferOwnership(addrs[0]);
}
receive() external payable {}
function transferOwnership(address newOwner) public override onlyOwner {
address owner = owner();
uint256 balance = balanceOf(owner);
require(newOwner != address(0), "WOOFI: New owner cannot be the zero address");
if(!isExcluded(newOwner)) excludeAccount(newOwner);
_transferBothExcluded(owner, newOwner, balance, balance);
super.transferOwnership(newOwner);
}
function updateRouter(address newAddress) public onlyOwner {
require(newAddress != address(router), "WOOFI: The router already has that address");
require(newAddress != address(0), "WOOFI: New router cannot be the zero address");
router = IRouter(newAddress);
}
function setMarketingWallet(address payable wallet) external onlyOwner {
_marketingWalletAddress = wallet;
}
function swapTokensForGB(uint256 tokenAmount) public {
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = router.WAVAX();
path[2] = rewardToken;
uint[] memory amountOutMins = router.getAmountsOut(tokenAmount, path);
uint amountOutMin = amountOutMins[path.length - 1];
router.swapExactTokensForTokens(tokenAmount, amountOutMin, path, address(this), block.timestamp);
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function excludeAccount(address account) public onlyOwner() {
require(!_isExcluded[account], "WOOFI: Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeAccount(address account) public onlyOwner() {
require(!_isExcluded[account], "WOOFI: 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], "WOOFI: 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], "WOOFI: 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], "WOOFI: 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 _splitBalance(uint256 amount) internal pure returns (uint256, uint256) {
uint256 amountToGB = amount.mul(4).div(100);
uint256 subAmount = amount.sub(amountToGB);
return (amountToGB, subAmount);
}
function _transfer(address sender, address recipient, uint256 amount) internal override {
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");
(uint256 amountToGB, uint256 subAmount) = _splitBalance(amount);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount, amount);
_transferToExcluded(sender, recipient, amount, amount);
_transferBothExcluded(sender, recipient, amount, amount);
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
_swapping = true;
uint256 initialBalance = IERC20(rewardToken).balanceOf(address(this));
swapTokensForGB(amountToGB);
uint256 newBalance = (IERC20(rewardToken).balanceOf(address(this)))
.sub(initialBalance);
uint256 toH = newBalance.div(4);
uint256 toD = newBalance.sub(toH);
bool success = IERC20(rewardToken).transfer(_marketingWalletAddress, toD);
_transferStandard(sender, recipient, subAmount, amount);
uint256 transferAmount = amount.sub(amountToGB);
_transferToExcluded(sender, address(this), transferAmount, transferAmount);
_transferStandard(sender, recipient, transferAmount, amount);
}
}
function _transfer(address sender, address recipient, uint256 amount) internal override {
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");
(uint256 amountToGB, uint256 subAmount) = _splitBalance(amount);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount, amount);
_transferToExcluded(sender, recipient, amount, amount);
_transferBothExcluded(sender, recipient, amount, amount);
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
_swapping = true;
uint256 initialBalance = IERC20(rewardToken).balanceOf(address(this));
swapTokensForGB(amountToGB);
uint256 newBalance = (IERC20(rewardToken).balanceOf(address(this)))
.sub(initialBalance);
uint256 toH = newBalance.div(4);
uint256 toD = newBalance.sub(toH);
bool success = IERC20(rewardToken).transfer(_marketingWalletAddress, toD);
_transferStandard(sender, recipient, subAmount, amount);
uint256 transferAmount = amount.sub(amountToGB);
_transferToExcluded(sender, address(this), transferAmount, transferAmount);
_transferStandard(sender, recipient, transferAmount, amount);
}
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
} else {
}
| 13,167,097 | [
1,
63,
20,
65,
273,
3410,
16,
306,
21,
65,
273,
19890,
1345,
16,
306,
22,
65,
273,
13667,
310,
9230,
16,
306,
23,
65,
273,
4633,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
678,
25148,
1653,
353,
4232,
39,
3462,
10784,
429,
16,
14223,
6914,
10784,
429,
16,
467,
59,
51,
3932,
1285,
969,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
203,
565,
1426,
3238,
389,
22270,
1382,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
88,
5269,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
31,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
377,
203,
565,
1758,
8526,
3238,
389,
24602,
31,
203,
565,
1758,
3238,
389,
3355,
21747,
16936,
1887,
31,
203,
377,
203,
565,
1758,
1071,
19890,
1345,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
377,
203,
565,
467,
8259,
1071,
4633,
31,
203,
203,
565,
445,
4046,
261,
203,
3639,
1758,
63,
24,
65,
3778,
11755,
16,
203,
3639,
533,
3778,
508,
67,
16,
203,
3639,
533,
3778,
3273,
67,
16,
203,
3639,
2254,
28,
15105,
67,
16,
203,
3639,
2254,
5034,
2078,
3088,
1283,
67,
203,
565,
262,
225,
3903,
3849,
12562,
288,
203,
3639,
2583,
12,
23305,
63,
20,
65,
480,
11755,
63,
22,
6487,
2
] |
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// LC->07.08.2018
facts гл_предл language=Russian
{
arity=3
//violation_score=-5
generic
return=boolean
}
#define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{}
#region Предлог_В
// ------------------- С ПРЕДЛОГОМ 'В' ---------------------------
#region Предложный
// Глаголы и отглагольные части речи, присоединяющие
// предложное дополнение с предлогом В и сущ. в предложном падеже.
wordentry_set Гл_В_Предл =
{
rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль
// вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб
rus_verbs:воевать{}, // Воевал во Франции.
rus_verbs:устать{}, // Устали в дороге?
rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения.
rus_verbs:решить{}, // Что решат в правительстве?
rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает.
rus_verbs:обстоять{}, // В действительности же дело обстояло не так.
rus_verbs:подыматься{},
rus_verbs:поехать{}, // поедем в такси!
rus_verbs:уехать{}, // он уехал в такси
rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей
rus_verbs:ОБЛАЧИТЬ{},
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло.
rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ)
rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ)
rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ)
rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ)
rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ)
rus_verbs:ЗАМАЯЧИТЬ{},
rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ)
rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ)
rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ)
rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ)
rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ)
rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ)
rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ)
rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ)
rus_verbs:ПоТЕРЯТЬ{},
rus_verbs:УТЕРЯТЬ{},
rus_verbs:РАСТЕРЯТЬ{},
rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.)
rus_verbs:СОМКНУТЬСЯ{},
rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ)
rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ)
rus_verbs:ВЫСТОЯТЬ{},
rus_verbs:ПОСТОЯТЬ{},
rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ)
rus_verbs:ВЗВЕШИВАТЬ{},
rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ)
прилагательное:быстрый{}, // Кисель быстр в приготовлении
rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень
rus_verbs:призывать{},
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ)
rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ)
rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ)
rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ)
rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ)
rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ)
rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ)
rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ)
rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ)
rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ)
rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ)
rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения
rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ)
rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ)
rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ)
rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ)
rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ)
rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ)
rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ)
rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ)
rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ)
rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ)
rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ)
rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА
rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ)
rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ)
rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ)
rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ)
rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ)
rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль
rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение
rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ)
инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан
глагол:проводить{ вид:несоверш },
деепричастие:проводя{},
rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала
rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл)
rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл)
rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл)
rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл)
rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл)
rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл)
rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл)
rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл)
rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл)
rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл)
rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл)
rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл)
rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл)
rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл)
прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В)
rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл)
rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл)
rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл)
rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл)
rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл)
rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл)
rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл)
rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл)
rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В)
rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В)
rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл)
rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В)
rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл)
rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл)
rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В)
rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл)
rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл)
rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В)
rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл)
rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В)
rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В)
rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В)
rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В)
rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл)
rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В)
частица:нет{}, // В этом нет сомнения.
частица:нету{}, // В этом нету сомнения.
rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем
rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов.
прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В)
rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В)
rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В)
rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В)
rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл)
rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В)
rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в)
rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В)
rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В)
rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В)
rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В)
rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В)
rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В)
rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В)
rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В)
rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В)
rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В)
rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В)
rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В)
rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В)
rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:РАСКЛАДЫВАТЬСЯ{},
rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В)
rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В)
rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В)
rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В)
rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл)
rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В)
rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В)
инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В)
глагол:НАПИСАТЬ{ aux stress="напис^ать" },
прилагательное:НАПИСАННЫЙ{},
rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В)
rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В)
rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В)
rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В)
rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В)
rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В)
rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл)
rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл)
rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В)
безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в)
rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В)
rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В)
rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В)
rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В)
rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В)
rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В)
rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В)
rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В)
rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В)
rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В)
rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В)
rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В)
rus_verbs:объявить{}, // В газете объявили о конкурсе.
rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В)
rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В)
rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в)
rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в)
rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в)
rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в)
инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В)
глагол:ПАРИТЬ{ aux stress="пар^ить"},
деепричастие:паря{ aux stress="пар^я" },
прилагательное:ПАРЯЩИЙ{},
прилагательное:ПАРИВШИЙ{},
rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В)
rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В)
rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в)
rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В)
rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В)
rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В)
rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В)
rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В)
rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В)
rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в)
rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в)
rus_verbs:принять{}, // Документ принят в следующей редакции (принять в)
rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в)
rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В)
rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в)
rus_verbs:звучать{}, // в доме звучала музыка (звучать в)
rus_verbs:колебаться{}, // колеблется в выборе (колебаться в)
rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в)
rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в)
rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в)
rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в)
rus_verbs:вычитывать{}, // вычитывать в книге
rus_verbs:гудеть{}, // У него в ушах гудит.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки.
rus_verbs:разойтись{}, // Они разошлись в темноте.
rus_verbs:прибежать{}, // Мальчик прибежал в слезах.
rus_verbs:биться{}, // Она билась в истерике.
rus_verbs:регистрироваться{}, // регистрироваться в системе
rus_verbs:считать{}, // я буду считать в уме
rus_verbs:трахаться{}, // трахаться в гамаке
rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке
rus_verbs:разрушать{}, // разрушать в дробилке
rus_verbs:засидеться{}, // засидеться в гостях
rus_verbs:засиживаться{}, // засиживаться в гостях
rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке)
rus_verbs:навестить{}, // навестить в доме престарелых
rus_verbs:запомнить{}, // запомнить в кэше
rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.)
rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка)
rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику.
rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.)
rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу
rus_verbs:оглядываться{}, // оглядываться в зеркале
rus_verbs:нарисовать{}, // нарисовать в тетрадке
rus_verbs:пробить{}, // пробить отверствие в стене
rus_verbs:повертеть{}, // повертеть в руке
rus_verbs:вертеть{}, // Я вертел в руках
rus_verbs:рваться{}, // Веревка рвется в месте надреза
rus_verbs:распространяться{}, // распространяться в среде наркоманов
rus_verbs:попрощаться{}, // попрощаться в здании морга
rus_verbs:соображать{}, // соображать в уме
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати
rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот)
rus_verbs:разобрать{}, // разобрать в гараже
rus_verbs:помереть{}, // помереть в пути
rus_verbs:различить{}, // различить в темноте
rus_verbs:рисовать{}, // рисовать в графическом редакторе
rus_verbs:проследить{}, // проследить в записях камер слежения
rus_verbs:совершаться{}, // Правосудие совершается в суде
rus_verbs:задремать{}, // задремать в кровати
rus_verbs:ругаться{}, // ругаться в комнате
rus_verbs:зазвучать{}, // зазвучать в радиоприемниках
rus_verbs:задохнуться{}, // задохнуться в воде
rus_verbs:порождать{}, // порождать в неокрепших умах
rus_verbs:отдыхать{}, // отдыхать в санатории
rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении
rus_verbs:образовать{}, // образовать в пробирке темную взвесь
rus_verbs:отмечать{}, // отмечать в списке
rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте
rus_verbs:плясать{}, // плясать в откружении незнакомых людей
rus_verbs:повысить{}, // повысить в звании
rus_verbs:поджидать{}, // поджидать в подъезде
rus_verbs:отказать{}, // отказать в пересмотре дела
rus_verbs:раствориться{}, // раствориться в бензине
rus_verbs:отражать{}, // отражать в стихах
rus_verbs:дремать{}, // дремать в гамаке
rus_verbs:применяться{}, // применяться в домашних условиях
rus_verbs:присниться{}, // присниться во сне
rus_verbs:трястись{}, // трястись в драндулете
rus_verbs:сохранять{}, // сохранять в неприкосновенности
rus_verbs:расстрелять{}, // расстрелять в ложбине
rus_verbs:рассчитать{}, // рассчитать в программе
rus_verbs:перебирать{}, // перебирать в руке
rus_verbs:разбиться{}, // разбиться в аварии
rus_verbs:поискать{}, // поискать в углу
rus_verbs:мучиться{}, // мучиться в тесной клетке
rus_verbs:замелькать{}, // замелькать в телевизоре
rus_verbs:грустить{}, // грустить в одиночестве
rus_verbs:крутить{}, // крутить в банке
rus_verbs:объявиться{}, // объявиться в городе
rus_verbs:подготовить{}, // подготовить в тайне
rus_verbs:различать{}, // различать в смеси
rus_verbs:обнаруживать{}, // обнаруживать в крови
rus_verbs:киснуть{}, // киснуть в захолустье
rus_verbs:оборваться{}, // оборваться в начале фразы
rus_verbs:запутаться{}, // запутаться в веревках
rus_verbs:общаться{}, // общаться в интимной обстановке
rus_verbs:сочинить{}, // сочинить в ресторане
rus_verbs:изобрести{}, // изобрести в домашней лаборатории
rus_verbs:прокомментировать{}, // прокомментировать в своем блоге
rus_verbs:давить{}, // давить в зародыше
rus_verbs:повториться{}, // повториться в новом обличье
rus_verbs:отставать{}, // отставать в общем зачете
rus_verbs:разработать{}, // разработать в лаборатории
rus_verbs:качать{}, // качать в кроватке
rus_verbs:заменить{}, // заменить в двигателе
rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере
rus_verbs:забегать{}, // забегать в спешке
rus_verbs:наделать{}, // наделать в решении ошибок
rus_verbs:исказиться{}, // исказиться в кривом зеркале
rus_verbs:тушить{}, // тушить в помещении пожар
rus_verbs:охранять{}, // охранять в здании входы
rus_verbs:приметить{}, // приметить в кустах
rus_verbs:скрыть{}, // скрыть в складках одежды
rus_verbs:удерживать{}, // удерживать в заложниках
rus_verbs:увеличиваться{}, // увеличиваться в размере
rus_verbs:красоваться{}, // красоваться в новом платье
rus_verbs:сохраниться{}, // сохраниться в тепле
rus_verbs:лечить{}, // лечить в стационаре
rus_verbs:смешаться{}, // смешаться в баке
rus_verbs:прокатиться{}, // прокатиться в троллейбусе
rus_verbs:договариваться{}, // договариваться в закрытом кабинете
rus_verbs:опубликовать{}, // опубликовать в официальном блоге
rus_verbs:охотиться{}, // охотиться в прериях
rus_verbs:отражаться{}, // отражаться в окне
rus_verbs:понизить{}, // понизить в должности
rus_verbs:обедать{}, // обедать в ресторане
rus_verbs:посидеть{}, // посидеть в тени
rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете
rus_verbs:свершиться{}, // свершиться в суде
rus_verbs:ночевать{}, // ночевать в гостинице
rus_verbs:темнеть{}, // темнеть в воде
rus_verbs:гибнуть{}, // гибнуть в застенках
rus_verbs:усиливаться{}, // усиливаться в направлении главного удара
rus_verbs:расплыться{}, // расплыться в улыбке
rus_verbs:превышать{}, // превышать в несколько раз
rus_verbs:проживать{}, // проживать в отдельной коморке
rus_verbs:голубеть{}, // голубеть в тепле
rus_verbs:исследовать{}, // исследовать в естественных условиях
rus_verbs:обитать{}, // обитать в лесу
rus_verbs:скучать{}, // скучать в одиночестве
rus_verbs:сталкиваться{}, // сталкиваться в воздухе
rus_verbs:таиться{}, // таиться в глубине
rus_verbs:спасать{}, // спасать в море
rus_verbs:заблудиться{}, // заблудиться в лесу
rus_verbs:создаться{}, // создаться в новом виде
rus_verbs:пошарить{}, // пошарить в кармане
rus_verbs:планировать{}, // планировать в программе
rus_verbs:отбить{}, // отбить в нижней части
rus_verbs:отрицать{}, // отрицать в суде свою вину
rus_verbs:основать{}, // основать в пустыне новый город
rus_verbs:двоить{}, // двоить в глазах
rus_verbs:устоять{}, // устоять в лодке
rus_verbs:унять{}, // унять в ногах дрожь
rus_verbs:отзываться{}, // отзываться в обзоре
rus_verbs:притормозить{}, // притормозить в траве
rus_verbs:читаться{}, // читаться в глазах
rus_verbs:житься{}, // житься в деревне
rus_verbs:заиграть{}, // заиграть в жилах
rus_verbs:шевелить{}, // шевелить в воде
rus_verbs:зазвенеть{}, // зазвенеть в ушах
rus_verbs:зависнуть{}, // зависнуть в библиотеке
rus_verbs:затаить{}, // затаить в душе обиду
rus_verbs:сознаться{}, // сознаться в совершении
rus_verbs:протекать{}, // протекать в легкой форме
rus_verbs:выясняться{}, // выясняться в ходе эксперимента
rus_verbs:скрестить{}, // скрестить в неволе
rus_verbs:наводить{}, // наводить в комнате порядок
rus_verbs:значиться{}, // значиться в документах
rus_verbs:заинтересовать{}, // заинтересовать в получении результатов
rus_verbs:познакомить{}, // познакомить в непринужденной обстановке
rus_verbs:рассеяться{}, // рассеяться в воздухе
rus_verbs:грохнуть{}, // грохнуть в подвале
rus_verbs:обвинять{}, // обвинять в вымогательстве
rus_verbs:столпиться{}, // столпиться в фойе
rus_verbs:порыться{}, // порыться в сумке
rus_verbs:ослабить{}, // ослабить в верхней части
rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки
rus_verbs:спастись{}, // спастись в хижине
rus_verbs:прерваться{}, // прерваться в середине фразы
rus_verbs:применять{}, // применять в повседневной работе
rus_verbs:строиться{}, // строиться в зоне отчуждения
rus_verbs:путешествовать{}, // путешествовать в самолете
rus_verbs:побеждать{}, // побеждать в честной битве
rus_verbs:погубить{}, // погубить в себе артиста
rus_verbs:рассматриваться{}, // рассматриваться в следующей главе
rus_verbs:продаваться{}, // продаваться в специализированном магазине
rus_verbs:разместиться{}, // разместиться в аудитории
rus_verbs:повидать{}, // повидать в жизни
rus_verbs:настигнуть{}, // настигнуть в пригородах
rus_verbs:сгрудиться{}, // сгрудиться в центре загона
rus_verbs:укрыться{}, // укрыться в доме
rus_verbs:расплакаться{}, // расплакаться в суде
rus_verbs:пролежать{}, // пролежать в канаве
rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде
rus_verbs:поскользнуться{}, // поскользнуться в коридоре
rus_verbs:таскать{}, // таскать в руках
rus_verbs:нападать{}, // нападать в вольере
rus_verbs:просматривать{}, // просматривать в браузере
rus_verbs:обдумать{}, // обдумать в дороге
rus_verbs:обвинить{}, // обвинить в измене
rus_verbs:останавливать{}, // останавливать в дверях
rus_verbs:теряться{}, // теряться в догадках
rus_verbs:погибать{}, // погибать в бою
rus_verbs:обозначать{}, // обозначать в списке
rus_verbs:запрещать{}, // запрещать в парке
rus_verbs:долететь{}, // долететь в вертолёте
rus_verbs:тесниться{}, // тесниться в каморке
rus_verbs:уменьшаться{}, // уменьшаться в размере
rus_verbs:издавать{}, // издавать в небольшом издательстве
rus_verbs:хоронить{}, // хоронить в море
rus_verbs:перемениться{}, // перемениться в лице
rus_verbs:установиться{}, // установиться в северных областях
rus_verbs:прикидывать{}, // прикидывать в уме
rus_verbs:затаиться{}, // затаиться в траве
rus_verbs:раздобыть{}, // раздобыть в аптеке
rus_verbs:перебросить{}, // перебросить в товарном составе
rus_verbs:погружаться{}, // погружаться в батискафе
rus_verbs:поживать{}, // поживать в одиночестве
rus_verbs:признаваться{}, // признаваться в любви
rus_verbs:захватывать{}, // захватывать в здании
rus_verbs:покачиваться{}, // покачиваться в лодке
rus_verbs:крутиться{}, // крутиться в колесе
rus_verbs:помещаться{}, // помещаться в ящике
rus_verbs:питаться{}, // питаться в столовой
rus_verbs:отдохнуть{}, // отдохнуть в пансионате
rus_verbs:кататься{}, // кататься в коляске
rus_verbs:поработать{}, // поработать в цеху
rus_verbs:подразумевать{}, // подразумевать в задании
rus_verbs:ограбить{}, // ограбить в подворотне
rus_verbs:преуспеть{}, // преуспеть в бизнесе
rus_verbs:заерзать{}, // заерзать в кресле
rus_verbs:разъяснить{}, // разъяснить в другой статье
rus_verbs:продвинуться{}, // продвинуться в изучении
rus_verbs:поколебаться{}, // поколебаться в начале
rus_verbs:засомневаться{}, // засомневаться в честности
rus_verbs:приникнуть{}, // приникнуть в уме
rus_verbs:скривить{}, // скривить в усмешке
rus_verbs:рассечь{}, // рассечь в центре опухоли
rus_verbs:перепутать{}, // перепутать в роддоме
rus_verbs:посмеяться{}, // посмеяться в перерыве
rus_verbs:отмечаться{}, // отмечаться в полицейском участке
rus_verbs:накопиться{}, // накопиться в отстойнике
rus_verbs:уносить{}, // уносить в руках
rus_verbs:навещать{}, // навещать в больнице
rus_verbs:остыть{}, // остыть в проточной воде
rus_verbs:запереться{}, // запереться в комнате
rus_verbs:обогнать{}, // обогнать в первом круге
rus_verbs:убеждаться{}, // убеждаться в неизбежности
rus_verbs:подбирать{}, // подбирать в магазине
rus_verbs:уничтожать{}, // уничтожать в полете
rus_verbs:путаться{}, // путаться в показаниях
rus_verbs:притаиться{}, // притаиться в темноте
rus_verbs:проплывать{}, // проплывать в лодке
rus_verbs:засесть{}, // засесть в окопе
rus_verbs:подцепить{}, // подцепить в баре
rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок
rus_verbs:оправдаться{}, // оправдаться в суде
rus_verbs:созреть{}, // созреть в естественных условиях
rus_verbs:раскрываться{}, // раскрываться в подходящих условиях
rus_verbs:ожидаться{}, // ожидаться в верхней части
rus_verbs:одеваться{}, // одеваться в дорогих бутиках
rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта
rus_verbs:грабить{}, // грабить в подворотне
rus_verbs:ужинать{}, // ужинать в ресторане
rus_verbs:гонять{}, // гонять в жилах
rus_verbs:уверить{}, // уверить в безопасности
rus_verbs:потеряться{}, // потеряться в лесу
rus_verbs:устанавливаться{}, // устанавливаться в комнате
rus_verbs:предоставлять{}, // предоставлять в суде
rus_verbs:протянуться{}, // протянуться в стене
rus_verbs:допрашивать{}, // допрашивать в бункере
rus_verbs:проработать{}, // проработать в кабинете
rus_verbs:сосредоточить{}, // сосредоточить в своих руках
rus_verbs:утвердить{}, // утвердить в должности
rus_verbs:сочинять{}, // сочинять в дороге
rus_verbs:померкнуть{}, // померкнуть в глазах
rus_verbs:показываться{}, // показываться в окошке
rus_verbs:похудеть{}, // похудеть в талии
rus_verbs:проделывать{}, // проделывать в стене
rus_verbs:прославиться{}, // прославиться в интернете
rus_verbs:сдохнуть{}, // сдохнуть в нищете
rus_verbs:раскинуться{}, // раскинуться в степи
rus_verbs:развить{}, // развить в себе способности
rus_verbs:уставать{}, // уставать в цеху
rus_verbs:укрепить{}, // укрепить в земле
rus_verbs:числиться{}, // числиться в списке
rus_verbs:образовывать{}, // образовывать в смеси
rus_verbs:екнуть{}, // екнуть в груди
rus_verbs:одобрять{}, // одобрять в своей речи
rus_verbs:запить{}, // запить в одиночестве
rus_verbs:забыться{}, // забыться в тяжелом сне
rus_verbs:чернеть{}, // чернеть в кислой среде
rus_verbs:размещаться{}, // размещаться в гараже
rus_verbs:соорудить{}, // соорудить в гараже
rus_verbs:развивать{}, // развивать в себе
rus_verbs:пастись{}, // пастись в пойме
rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы
rus_verbs:ослабнуть{}, // ослабнуть в сочленении
rus_verbs:таить{}, // таить в себе
инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке
rus_verbs:приостановиться{}, // приостановиться в конце
rus_verbs:топтаться{}, // топтаться в грязи
rus_verbs:громить{}, // громить в финале
rus_verbs:заменять{}, // заменять в основном составе
rus_verbs:подъезжать{}, // подъезжать в колясках
rus_verbs:вычислить{}, // вычислить в уме
rus_verbs:заказывать{}, // заказывать в магазине
rus_verbs:осуществить{}, // осуществить в реальных условиях
rus_verbs:обосноваться{}, // обосноваться в дупле
rus_verbs:пытать{}, // пытать в камере
rus_verbs:поменять{}, // поменять в магазине
rus_verbs:совершиться{}, // совершиться в суде
rus_verbs:пролетать{}, // пролетать в вертолете
rus_verbs:сбыться{}, // сбыться во сне
rus_verbs:разговориться{}, // разговориться в отделении
rus_verbs:преподнести{}, // преподнести в красивой упаковке
rus_verbs:напечатать{}, // напечатать в типографии
rus_verbs:прорвать{}, // прорвать в центре
rus_verbs:раскачиваться{}, // раскачиваться в кресле
rus_verbs:задерживаться{}, // задерживаться в дверях
rus_verbs:угощать{}, // угощать в кафе
rus_verbs:проступать{}, // проступать в глубине
rus_verbs:шарить{}, // шарить в математике
rus_verbs:увеличивать{}, // увеличивать в конце
rus_verbs:расцвести{}, // расцвести в оранжерее
rus_verbs:закипеть{}, // закипеть в баке
rus_verbs:подлететь{}, // подлететь в вертолете
rus_verbs:рыться{}, // рыться в куче
rus_verbs:пожить{}, // пожить в гостинице
rus_verbs:добираться{}, // добираться в попутном транспорте
rus_verbs:перекрыть{}, // перекрыть в коридоре
rus_verbs:продержаться{}, // продержаться в барокамере
rus_verbs:разыскивать{}, // разыскивать в толпе
rus_verbs:освобождать{}, // освобождать в зале суда
rus_verbs:подметить{}, // подметить в человеке
rus_verbs:передвигаться{}, // передвигаться в узкой юбке
rus_verbs:продумать{}, // продумать в уме
rus_verbs:извиваться{}, // извиваться в траве
rus_verbs:процитировать{}, // процитировать в статье
rus_verbs:прогуливаться{}, // прогуливаться в парке
rus_verbs:защемить{}, // защемить в двери
rus_verbs:увеличиться{}, // увеличиться в объеме
rus_verbs:проявиться{}, // проявиться в результатах
rus_verbs:заскользить{}, // заскользить в ботинках
rus_verbs:пересказать{}, // пересказать в своем выступлении
rus_verbs:протестовать{}, // протестовать в здании парламента
rus_verbs:указываться{}, // указываться в путеводителе
rus_verbs:копошиться{}, // копошиться в песке
rus_verbs:проигнорировать{}, // проигнорировать в своей работе
rus_verbs:купаться{}, // купаться в речке
rus_verbs:подсчитать{}, // подсчитать в уме
rus_verbs:разволноваться{}, // разволноваться в классе
rus_verbs:придумывать{}, // придумывать в своем воображении
rus_verbs:предусмотреть{}, // предусмотреть в программе
rus_verbs:завертеться{}, // завертеться в колесе
rus_verbs:зачерпнуть{}, // зачерпнуть в ручье
rus_verbs:очистить{}, // очистить в химической лаборатории
rus_verbs:прозвенеть{}, // прозвенеть в коридорах
rus_verbs:уменьшиться{}, // уменьшиться в размере
rus_verbs:колыхаться{}, // колыхаться в проточной воде
rus_verbs:ознакомиться{}, // ознакомиться в автобусе
rus_verbs:ржать{}, // ржать в аудитории
rus_verbs:раскинуть{}, // раскинуть в микрорайоне
rus_verbs:разлиться{}, // разлиться в воде
rus_verbs:сквозить{}, // сквозить в словах
rus_verbs:задушить{}, // задушить в объятиях
rus_verbs:осудить{}, // осудить в особом порядке
rus_verbs:разгромить{}, // разгромить в честном поединке
rus_verbs:подслушать{}, // подслушать в кулуарах
rus_verbs:проповедовать{}, // проповедовать в сельских районах
rus_verbs:озарить{}, // озарить во сне
rus_verbs:потирать{}, // потирать в предвкушении
rus_verbs:описываться{}, // описываться в статье
rus_verbs:качаться{}, // качаться в кроватке
rus_verbs:усилить{}, // усилить в центре
rus_verbs:прохаживаться{}, // прохаживаться в новом костюме
rus_verbs:полечить{}, // полечить в больничке
rus_verbs:сниматься{}, // сниматься в римейке
rus_verbs:сыскать{}, // сыскать в наших краях
rus_verbs:поприветствовать{}, // поприветствовать в коридоре
rus_verbs:подтвердиться{}, // подтвердиться в эксперименте
rus_verbs:плескаться{}, // плескаться в теплой водичке
rus_verbs:расширяться{}, // расширяться в первом сегменте
rus_verbs:мерещиться{}, // мерещиться в тумане
rus_verbs:сгущаться{}, // сгущаться в воздухе
rus_verbs:храпеть{}, // храпеть во сне
rus_verbs:подержать{}, // подержать в руках
rus_verbs:накинуться{}, // накинуться в подворотне
rus_verbs:планироваться{}, // планироваться в закрытом режиме
rus_verbs:пробудить{}, // пробудить в себе
rus_verbs:побриться{}, // побриться в ванной
rus_verbs:сгинуть{}, // сгинуть в пучине
rus_verbs:окрестить{}, // окрестить в церкви
инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления
rus_verbs:замкнуться{}, // замкнуться в себе
rus_verbs:прибавлять{}, // прибавлять в весе
rus_verbs:проплыть{}, // проплыть в лодке
rus_verbs:растворяться{}, // растворяться в тумане
rus_verbs:упрекать{}, // упрекать в небрежности
rus_verbs:затеряться{}, // затеряться в лабиринте
rus_verbs:перечитывать{}, // перечитывать в поезде
rus_verbs:перелететь{}, // перелететь в вертолете
rus_verbs:оживать{}, // оживать в теплой воде
rus_verbs:заглохнуть{}, // заглохнуть в полете
rus_verbs:кольнуть{}, // кольнуть в боку
rus_verbs:копаться{}, // копаться в куче
rus_verbs:развлекаться{}, // развлекаться в клубе
rus_verbs:отливать{}, // отливать в кустах
rus_verbs:зажить{}, // зажить в деревне
rus_verbs:одолжить{}, // одолжить в соседнем кабинете
rus_verbs:заклинать{}, // заклинать в своей речи
rus_verbs:различаться{}, // различаться в мелочах
rus_verbs:печататься{}, // печататься в типографии
rus_verbs:угадываться{}, // угадываться в контурах
rus_verbs:обрывать{}, // обрывать в начале
rus_verbs:поглаживать{}, // поглаживать в кармане
rus_verbs:подписывать{}, // подписывать в присутствии понятых
rus_verbs:добывать{}, // добывать в разломе
rus_verbs:скопиться{}, // скопиться в воротах
rus_verbs:повстречать{}, // повстречать в бане
rus_verbs:совпасть{}, // совпасть в упрощенном виде
rus_verbs:разрываться{}, // разрываться в точке спайки
rus_verbs:улавливать{}, // улавливать в датчике
rus_verbs:повстречаться{}, // повстречаться в лифте
rus_verbs:отразить{}, // отразить в отчете
rus_verbs:пояснять{}, // пояснять в примечаниях
rus_verbs:накормить{}, // накормить в столовке
rus_verbs:поужинать{}, // поужинать в ресторане
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить в молоке
rus_verbs:освоить{}, // освоить в работе
rus_verbs:зародиться{}, // зародиться в голове
rus_verbs:отплыть{}, // отплыть в старой лодке
rus_verbs:отстаивать{}, // отстаивать в суде
rus_verbs:осуждать{}, // осуждать в своем выступлении
rus_verbs:переговорить{}, // переговорить в перерыве
rus_verbs:разгораться{}, // разгораться в сердце
rus_verbs:укрыть{}, // укрыть в шалаше
rus_verbs:томиться{}, // томиться в застенках
rus_verbs:клубиться{}, // клубиться в воздухе
rus_verbs:сжигать{}, // сжигать в топке
rus_verbs:позавтракать{}, // позавтракать в кафешке
rus_verbs:функционировать{}, // функционировать в лабораторных условиях
rus_verbs:смять{}, // смять в руке
rus_verbs:разместить{}, // разместить в интернете
rus_verbs:пронести{}, // пронести в потайном кармане
rus_verbs:руководствоваться{}, // руководствоваться в работе
rus_verbs:нашарить{}, // нашарить в потемках
rus_verbs:закрутить{}, // закрутить в вихре
rus_verbs:просматриваться{}, // просматриваться в дальней перспективе
rus_verbs:распознать{}, // распознать в незнакомце
rus_verbs:повеситься{}, // повеситься в камере
rus_verbs:обшарить{}, // обшарить в поисках наркотиков
rus_verbs:наполняться{}, // наполняется в карьере
rus_verbs:засвистеть{}, // засвистеть в воздухе
rus_verbs:процветать{}, // процветать в мягком климате
rus_verbs:шуршать{}, // шуршать в простенке
rus_verbs:подхватывать{}, // подхватывать в полете
инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе
прилагательное:роившийся{}, прилагательное:роящийся{},
// деепричастие:роясь{ aux stress="ро^ясь" },
rus_verbs:преобладать{}, // преобладать в тексте
rus_verbs:посветлеть{}, // посветлеть в лице
rus_verbs:игнорировать{}, // игнорировать в рекомендациях
rus_verbs:обсуждаться{}, // обсуждаться в кулуарах
rus_verbs:отказывать{}, // отказывать в визе
rus_verbs:ощупывать{}, // ощупывать в кармане
rus_verbs:разливаться{}, // разливаться в цеху
rus_verbs:расписаться{}, // расписаться в получении
rus_verbs:учинить{}, // учинить в казарме
rus_verbs:плестись{}, // плестись в хвосте
rus_verbs:объявляться{}, // объявляться в группе
rus_verbs:повышаться{}, // повышаться в первой части
rus_verbs:напрягать{}, // напрягать в паху
rus_verbs:разрабатывать{}, // разрабатывать в студии
rus_verbs:хлопотать{}, // хлопотать в мэрии
rus_verbs:прерывать{}, // прерывать в самом начале
rus_verbs:каяться{}, // каяться в грехах
rus_verbs:освоиться{}, // освоиться в кабине
rus_verbs:подплыть{}, // подплыть в лодке
rus_verbs:замигать{}, // замигать в темноте
rus_verbs:оскорблять{}, // оскорблять в выступлении
rus_verbs:торжествовать{}, // торжествовать в душе
rus_verbs:поправлять{}, // поправлять в прологе
rus_verbs:угадывать{}, // угадывать в размытом изображении
rus_verbs:потоптаться{}, // потоптаться в прихожей
rus_verbs:переправиться{}, // переправиться в лодочке
rus_verbs:увериться{}, // увериться в невиновности
rus_verbs:забрезжить{}, // забрезжить в конце тоннеля
rus_verbs:утвердиться{}, // утвердиться во мнении
rus_verbs:завывать{}, // завывать в трубе
rus_verbs:заварить{}, // заварить в заварнике
rus_verbs:скомкать{}, // скомкать в руке
rus_verbs:перемещаться{}, // перемещаться в капсуле
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле
rus_verbs:праздновать{}, // праздновать в баре
rus_verbs:мигать{}, // мигать в темноте
rus_verbs:обучить{}, // обучить в мастерской
rus_verbs:орудовать{}, // орудовать в кладовке
rus_verbs:упорствовать{}, // упорствовать в заблуждении
rus_verbs:переминаться{}, // переминаться в прихожей
rus_verbs:подрасти{}, // подрасти в теплице
rus_verbs:предписываться{}, // предписываться в законе
rus_verbs:приписать{}, // приписать в конце
rus_verbs:задаваться{}, // задаваться в своей статье
rus_verbs:чинить{}, // чинить в домашних условиях
rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке
rus_verbs:пообедать{}, // пообедать в ресторанчике
rus_verbs:жрать{}, // жрать в чуланчике
rus_verbs:исполняться{}, // исполняться в антракте
rus_verbs:гнить{}, // гнить в тюрьме
rus_verbs:глодать{}, // глодать в конуре
rus_verbs:прослушать{}, // прослушать в дороге
rus_verbs:истратить{}, // истратить в кабаке
rus_verbs:стареть{}, // стареть в одиночестве
rus_verbs:разжечь{}, // разжечь в сердце
rus_verbs:совещаться{}, // совещаться в кабинете
rus_verbs:покачивать{}, // покачивать в кроватке
rus_verbs:отсидеть{}, // отсидеть в одиночке
rus_verbs:формировать{}, // формировать в умах
rus_verbs:захрапеть{}, // захрапеть во сне
rus_verbs:петься{}, // петься в хоре
rus_verbs:объехать{}, // объехать в автобусе
rus_verbs:поселить{}, // поселить в гостинице
rus_verbs:предаться{}, // предаться в книге
rus_verbs:заворочаться{}, // заворочаться во сне
rus_verbs:напрятать{}, // напрятать в карманах
rus_verbs:очухаться{}, // очухаться в незнакомом месте
rus_verbs:ограничивать{}, // ограничивать в движениях
rus_verbs:завертеть{}, // завертеть в руках
rus_verbs:печатать{}, // печатать в редакторе
rus_verbs:теплиться{}, // теплиться в сердце
rus_verbs:увязнуть{}, // увязнуть в зыбучем песке
rus_verbs:усмотреть{}, // усмотреть в обращении
rus_verbs:отыскаться{}, // отыскаться в запасах
rus_verbs:потушить{}, // потушить в горле огонь
rus_verbs:поубавиться{}, // поубавиться в размере
rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти
rus_verbs:смыть{}, // смыть в ванной
rus_verbs:заместить{}, // заместить в кресле
rus_verbs:угасать{}, // угасать в одиночестве
rus_verbs:сразить{}, // сразить в споре
rus_verbs:фигурировать{}, // фигурировать в бюллетене
rus_verbs:расплываться{}, // расплываться в глазах
rus_verbs:сосчитать{}, // сосчитать в уме
rus_verbs:сгуститься{}, // сгуститься в воздухе
rus_verbs:цитировать{}, // цитировать в своей статье
rus_verbs:помяться{}, // помяться в давке
rus_verbs:затрагивать{}, // затрагивать в процессе выполнения
rus_verbs:обтереть{}, // обтереть в гараже
rus_verbs:подстрелить{}, // подстрелить в пойме реки
rus_verbs:растереть{}, // растереть в руке
rus_verbs:подавлять{}, // подавлять в зародыше
rus_verbs:смешиваться{}, // смешиваться в чане
инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке
rus_verbs:сократиться{}, // сократиться в обхвате
rus_verbs:занервничать{}, // занервничать в кабинете
rus_verbs:соприкоснуться{}, // соприкоснуться в полете
rus_verbs:обозначить{}, // обозначить в объявлении
rus_verbs:обучаться{}, // обучаться в училище
rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы
rus_verbs:лелеять{}, // лелеять в сердце
rus_verbs:поддерживаться{}, // поддерживаться в суде
rus_verbs:уплыть{}, // уплыть в лодочке
rus_verbs:резвиться{}, // резвиться в саду
rus_verbs:поерзать{}, // поерзать в гамаке
rus_verbs:оплатить{}, // оплатить в ресторане
rus_verbs:похвастаться{}, // похвастаться в компании
rus_verbs:знакомиться{}, // знакомиться в классе
rus_verbs:приплыть{}, // приплыть в подводной лодке
rus_verbs:зажигать{}, // зажигать в классе
rus_verbs:смыслить{}, // смыслить в математике
rus_verbs:закопать{}, // закопать в огороде
rus_verbs:порхать{}, // порхать в зарослях
rus_verbs:потонуть{}, // потонуть в бумажках
rus_verbs:стирать{}, // стирать в холодной воде
rus_verbs:подстерегать{}, // подстерегать в придорожных кустах
rus_verbs:погулять{}, // погулять в парке
rus_verbs:предвкушать{}, // предвкушать в воображении
rus_verbs:ошеломить{}, // ошеломить в бою
rus_verbs:удостовериться{}, // удостовериться в безопасности
rus_verbs:огласить{}, // огласить в заключительной части
rus_verbs:разбогатеть{}, // разбогатеть в деревне
rus_verbs:грохотать{}, // грохотать в мастерской
rus_verbs:реализоваться{}, // реализоваться в должности
rus_verbs:красть{}, // красть в магазине
rus_verbs:нарваться{}, // нарваться в коридоре
rus_verbs:застывать{}, // застывать в неудобной позе
rus_verbs:толкаться{}, // толкаться в тесной комнате
rus_verbs:извлекать{}, // извлекать в аппарате
rus_verbs:обжигать{}, // обжигать в печи
rus_verbs:запечатлеть{}, // запечатлеть в кинохронике
rus_verbs:тренироваться{}, // тренироваться в зале
rus_verbs:поспорить{}, // поспорить в кабинете
rus_verbs:рыскать{}, // рыскать в лесу
rus_verbs:надрываться{}, // надрываться в шахте
rus_verbs:сняться{}, // сняться в фильме
rus_verbs:закружить{}, // закружить в танце
rus_verbs:затонуть{}, // затонуть в порту
rus_verbs:побыть{}, // побыть в гостях
rus_verbs:почистить{}, // почистить в носу
rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре
rus_verbs:подслушивать{}, // подслушивать в классе
rus_verbs:сгорать{}, // сгорать в танке
rus_verbs:разочароваться{}, // разочароваться в артисте
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках
rus_verbs:мять{}, // мять в руках
rus_verbs:подраться{}, // подраться в классе
rus_verbs:замести{}, // замести в прихожей
rus_verbs:откладываться{}, // откладываться в печени
rus_verbs:обозначаться{}, // обозначаться в перечне
rus_verbs:просиживать{}, // просиживать в интернете
rus_verbs:соприкасаться{}, // соприкасаться в точке
rus_verbs:начертить{}, // начертить в тетрадке
rus_verbs:уменьшать{}, // уменьшать в поперечнике
rus_verbs:тормозить{}, // тормозить в облаке
rus_verbs:затевать{}, // затевать в лаборатории
rus_verbs:затопить{}, // затопить в бухте
rus_verbs:задерживать{}, // задерживать в лифте
rus_verbs:прогуляться{}, // прогуляться в лесу
rus_verbs:прорубить{}, // прорубить во льду
rus_verbs:очищать{}, // очищать в кислоте
rus_verbs:полулежать{}, // полулежать в гамаке
rus_verbs:исправить{}, // исправить в задании
rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи
rus_verbs:замучить{}, // замучить в плену
rus_verbs:разрушаться{}, // разрушаться в верхней части
rus_verbs:ерзать{}, // ерзать в кресле
rus_verbs:покопаться{}, // покопаться в залежах
rus_verbs:раскаяться{}, // раскаяться в содеянном
rus_verbs:пробежаться{}, // пробежаться в парке
rus_verbs:полежать{}, // полежать в гамаке
rus_verbs:позаимствовать{}, // позаимствовать в книге
rus_verbs:снижать{}, // снижать в несколько раз
rus_verbs:черпать{}, // черпать в поэзии
rus_verbs:заверять{}, // заверять в своей искренности
rus_verbs:проглядеть{}, // проглядеть в сумерках
rus_verbs:припарковать{}, // припарковать во дворе
rus_verbs:сверлить{}, // сверлить в стене
rus_verbs:здороваться{}, // здороваться в аудитории
rus_verbs:рожать{}, // рожать в воде
rus_verbs:нацарапать{}, // нацарапать в тетрадке
rus_verbs:затопать{}, // затопать в коридоре
rus_verbs:прописать{}, // прописать в правилах
rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах
rus_verbs:снизить{}, // снизить в несколько раз
rus_verbs:заблуждаться{}, // заблуждаться в своей теории
rus_verbs:откопать{}, // откопать в отвалах
rus_verbs:смастерить{}, // смастерить в лаборатории
rus_verbs:замедлиться{}, // замедлиться в парафине
rus_verbs:избивать{}, // избивать в участке
rus_verbs:мыться{}, // мыться в бане
rus_verbs:сварить{}, // сварить в кастрюльке
rus_verbs:раскопать{}, // раскопать в снегу
rus_verbs:крепиться{}, // крепиться в держателе
rus_verbs:дробить{}, // дробить в мельнице
rus_verbs:попить{}, // попить в ресторанчике
rus_verbs:затронуть{}, // затронуть в душе
rus_verbs:лязгнуть{}, // лязгнуть в тишине
rus_verbs:заправлять{}, // заправлять в полете
rus_verbs:размножаться{}, // размножаться в неволе
rus_verbs:потопить{}, // потопить в Тихом Океане
rus_verbs:кушать{}, // кушать в столовой
rus_verbs:замолкать{}, // замолкать в замешательстве
rus_verbs:измеряться{}, // измеряться в дюймах
rus_verbs:сбываться{}, // сбываться в мечтах
rus_verbs:задернуть{}, // задернуть в комнате
rus_verbs:затихать{}, // затихать в темноте
rus_verbs:прослеживаться{}, // прослеживается в журнале
rus_verbs:прерываться{}, // прерывается в начале
rus_verbs:изображаться{}, // изображается в любых фильмах
rus_verbs:фиксировать{}, // фиксировать в данной точке
rus_verbs:ослаблять{}, // ослаблять в поясе
rus_verbs:зреть{}, // зреть в теплице
rus_verbs:зеленеть{}, // зеленеть в огороде
rus_verbs:критиковать{}, // критиковать в статье
rus_verbs:облететь{}, // облететь в частном вертолете
rus_verbs:разбросать{}, // разбросать в комнате
rus_verbs:заразиться{}, // заразиться в людном месте
rus_verbs:рассеять{}, // рассеять в бою
rus_verbs:печься{}, // печься в духовке
rus_verbs:поспать{}, // поспать в палатке
rus_verbs:заступиться{}, // заступиться в драке
rus_verbs:сплетаться{}, // сплетаться в середине
rus_verbs:поместиться{}, // поместиться в мешке
rus_verbs:спереть{}, // спереть в лавке
// инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде
// инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш },
rus_verbs:проваляться{}, // проваляться в постели
rus_verbs:лечиться{}, // лечиться в стационаре
rus_verbs:определиться{}, // определиться в честном бою
rus_verbs:обработать{}, // обработать в растворе
rus_verbs:пробивать{}, // пробивать в стене
rus_verbs:перемешаться{}, // перемешаться в чане
rus_verbs:чесать{}, // чесать в паху
rus_verbs:пролечь{}, // пролечь в пустынной местности
rus_verbs:скитаться{}, // скитаться в дальних странах
rus_verbs:затрудняться{}, // затрудняться в выборе
rus_verbs:отряхнуться{}, // отряхнуться в коридоре
rus_verbs:разыгрываться{}, // разыгрываться в лотерее
rus_verbs:помолиться{}, // помолиться в церкви
rus_verbs:предписывать{}, // предписывать в рецепте
rus_verbs:порваться{}, // порваться в слабом месте
rus_verbs:греться{}, // греться в здании
rus_verbs:опровергать{}, // опровергать в своем выступлении
rus_verbs:помянуть{}, // помянуть в своем выступлении
rus_verbs:допросить{}, // допросить в прокуратуре
rus_verbs:материализоваться{}, // материализоваться в соседнем здании
rus_verbs:рассеиваться{}, // рассеиваться в воздухе
rus_verbs:перевозить{}, // перевозить в вагоне
rus_verbs:отбывать{}, // отбывать в тюрьме
rus_verbs:попахивать{}, // попахивать в отхожем месте
rus_verbs:перечислять{}, // перечислять в заключении
rus_verbs:зарождаться{}, // зарождаться в дебрях
rus_verbs:предъявлять{}, // предъявлять в своем письме
rus_verbs:распространять{}, // распространять в сети
rus_verbs:пировать{}, // пировать в соседнем селе
rus_verbs:начертать{}, // начертать в летописи
rus_verbs:расцветать{}, // расцветать в подходящих условиях
rus_verbs:царствовать{}, // царствовать в южной части материка
rus_verbs:накопить{}, // накопить в буфере
rus_verbs:закрутиться{}, // закрутиться в рутине
rus_verbs:отработать{}, // отработать в забое
rus_verbs:обокрасть{}, // обокрасть в автобусе
rus_verbs:прокладывать{}, // прокладывать в снегу
rus_verbs:ковырять{}, // ковырять в носу
rus_verbs:копить{}, // копить в очереди
rus_verbs:полечь{}, // полечь в степях
rus_verbs:щебетать{}, // щебетать в кустиках
rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении
rus_verbs:посеять{}, // посеять в огороде
rus_verbs:разъезжать{}, // разъезжать в кабриолете
rus_verbs:замечаться{}, // замечаться в лесу
rus_verbs:просчитать{}, // просчитать в уме
rus_verbs:маяться{}, // маяться в командировке
rus_verbs:выхватывать{}, // выхватывать в тексте
rus_verbs:креститься{}, // креститься в деревенской часовне
rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты
rus_verbs:настигать{}, // настигать в огороде
rus_verbs:разгуливать{}, // разгуливать в роще
rus_verbs:насиловать{}, // насиловать в квартире
rus_verbs:побороть{}, // побороть в себе
rus_verbs:учитывать{}, // учитывать в расчетах
rus_verbs:искажать{}, // искажать в заметке
rus_verbs:пропить{}, // пропить в кабаке
rus_verbs:катать{}, // катать в лодочке
rus_verbs:припрятать{}, // припрятать в кармашке
rus_verbs:запаниковать{}, // запаниковать в бою
rus_verbs:рассыпать{}, // рассыпать в траве
rus_verbs:застревать{}, // застревать в ограде
rus_verbs:зажигаться{}, // зажигаться в сумерках
rus_verbs:жарить{}, // жарить в масле
rus_verbs:накапливаться{}, // накапливаться в костях
rus_verbs:распуститься{}, // распуститься в горшке
rus_verbs:проголосовать{}, // проголосовать в передвижном пункте
rus_verbs:странствовать{}, // странствовать в автомобиле
rus_verbs:осматриваться{}, // осматриваться в хоромах
rus_verbs:разворачивать{}, // разворачивать в спортзале
rus_verbs:заскучать{}, // заскучать в самолете
rus_verbs:напутать{}, // напутать в расчете
rus_verbs:перекусить{}, // перекусить в столовой
rus_verbs:спасаться{}, // спасаться в автономной капсуле
rus_verbs:посовещаться{}, // посовещаться в комнате
rus_verbs:доказываться{}, // доказываться в статье
rus_verbs:познаваться{}, // познаваться в беде
rus_verbs:загрустить{}, // загрустить в одиночестве
rus_verbs:оживить{}, // оживить в памяти
rus_verbs:переворачиваться{}, // переворачиваться в гробу
rus_verbs:заприметить{}, // заприметить в лесу
rus_verbs:отравиться{}, // отравиться в забегаловке
rus_verbs:продержать{}, // продержать в клетке
rus_verbs:выявить{}, // выявить в костях
rus_verbs:заседать{}, // заседать в совете
rus_verbs:расплачиваться{}, // расплачиваться в первой кассе
rus_verbs:проломить{}, // проломить в двери
rus_verbs:подражать{}, // подражать в мелочах
rus_verbs:подсчитывать{}, // подсчитывать в уме
rus_verbs:опережать{}, // опережать во всем
rus_verbs:сформироваться{}, // сформироваться в облаке
rus_verbs:укрепиться{}, // укрепиться в мнении
rus_verbs:отстоять{}, // отстоять в очереди
rus_verbs:развертываться{}, // развертываться в месте испытания
rus_verbs:замерзать{}, // замерзать во льду
rus_verbs:утопать{}, // утопать в снегу
rus_verbs:раскаиваться{}, // раскаиваться в содеянном
rus_verbs:организовывать{}, // организовывать в пионерлагере
rus_verbs:перевестись{}, // перевестись в наших краях
rus_verbs:смешивать{}, // смешивать в блендере
rus_verbs:ютиться{}, // ютиться в тесной каморке
rus_verbs:прождать{}, // прождать в аудитории
rus_verbs:подыскивать{}, // подыскивать в женском общежитии
rus_verbs:замочить{}, // замочить в сортире
rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке
rus_verbs:растирать{}, // растирать в ступке
rus_verbs:замедлять{}, // замедлять в парафине
rus_verbs:переспать{}, // переспать в палатке
rus_verbs:рассекать{}, // рассекать в кабриолете
rus_verbs:отыскивать{}, // отыскивать в залежах
rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении
rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке
rus_verbs:укрываться{}, // укрываться в землянке
rus_verbs:запечься{}, // запечься в золе
rus_verbs:догорать{}, // догорать в темноте
rus_verbs:застилать{}, // застилать в коридоре
rus_verbs:сыскаться{}, // сыскаться в деревне
rus_verbs:переделать{}, // переделать в мастерской
rus_verbs:разъяснять{}, // разъяснять в своей лекции
rus_verbs:селиться{}, // селиться в центре
rus_verbs:оплачивать{}, // оплачивать в магазине
rus_verbs:переворачивать{}, // переворачивать в закрытой банке
rus_verbs:упражняться{}, // упражняться в остроумии
rus_verbs:пометить{}, // пометить в списке
rus_verbs:припомниться{}, // припомниться в завещании
rus_verbs:приютить{}, // приютить в амбаре
rus_verbs:натерпеться{}, // натерпеться в темнице
rus_verbs:затеваться{}, // затеваться в клубе
rus_verbs:уплывать{}, // уплывать в лодке
rus_verbs:скиснуть{}, // скиснуть в бидоне
rus_verbs:заколоть{}, // заколоть в боку
rus_verbs:замерцать{}, // замерцать в темноте
rus_verbs:фиксироваться{}, // фиксироваться в протоколе
rus_verbs:запираться{}, // запираться в комнате
rus_verbs:съезжаться{}, // съезжаться в каретах
rus_verbs:толочься{}, // толочься в ступе
rus_verbs:потанцевать{}, // потанцевать в клубе
rus_verbs:побродить{}, // побродить в парке
rus_verbs:назревать{}, // назревать в коллективе
rus_verbs:дохнуть{}, // дохнуть в питомнике
rus_verbs:крестить{}, // крестить в деревенской церквушке
rus_verbs:рассчитаться{}, // рассчитаться в банке
rus_verbs:припарковаться{}, // припарковаться во дворе
rus_verbs:отхватить{}, // отхватить в магазинчике
rus_verbs:остывать{}, // остывать в холодильнике
rus_verbs:составляться{}, // составляться в атмосфере тайны
rus_verbs:переваривать{}, // переваривать в тишине
rus_verbs:хвастать{}, // хвастать в казино
rus_verbs:отрабатывать{}, // отрабатывать в теплице
rus_verbs:разлечься{}, // разлечься в кровати
rus_verbs:прокручивать{}, // прокручивать в голове
rus_verbs:очертить{}, // очертить в воздухе
rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей
rus_verbs:выявлять{}, // выявлять в боевых условиях
rus_verbs:караулить{}, // караулить в лифте
rus_verbs:расставлять{}, // расставлять в бойницах
rus_verbs:прокрутить{}, // прокрутить в голове
rus_verbs:пересказывать{}, // пересказывать в первой главе
rus_verbs:задавить{}, // задавить в зародыше
rus_verbs:хозяйничать{}, // хозяйничать в холодильнике
rus_verbs:хвалиться{}, // хвалиться в детском садике
rus_verbs:оперировать{}, // оперировать в полевом госпитале
rus_verbs:формулировать{}, // формулировать в следующей главе
rus_verbs:застигнуть{}, // застигнуть в неприглядном виде
rus_verbs:замурлыкать{}, // замурлыкать в тепле
rus_verbs:поддакивать{}, // поддакивать в споре
rus_verbs:прочертить{}, // прочертить в воздухе
rus_verbs:отменять{}, // отменять в городе коменданский час
rus_verbs:колдовать{}, // колдовать в лаборатории
rus_verbs:отвозить{}, // отвозить в машине
rus_verbs:трахать{}, // трахать в гамаке
rus_verbs:повозиться{}, // повозиться в мешке
rus_verbs:ремонтировать{}, // ремонтировать в центре
rus_verbs:робеть{}, // робеть в гостях
rus_verbs:перепробовать{}, // перепробовать в деле
инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии
глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш },
rus_verbs:покаяться{}, // покаяться в церкви
rus_verbs:попрыгать{}, // попрыгать в бассейне
rus_verbs:умалчивать{}, // умалчивать в своем докладе
rus_verbs:ковыряться{}, // ковыряться в старой технике
rus_verbs:расписывать{}, // расписывать в деталях
rus_verbs:вязнуть{}, // вязнуть в песке
rus_verbs:погрязнуть{}, // погрязнуть в скандалах
rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу
rus_verbs:зажимать{}, // зажимать в углу
rus_verbs:стискивать{}, // стискивать в ладонях
rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса
rus_verbs:израсходовать{}, // израсходовать в полете
rus_verbs:клокотать{}, // клокотать в жерле
rus_verbs:обвиняться{}, // обвиняться в растрате
rus_verbs:уединиться{}, // уединиться в кладовке
rus_verbs:подохнуть{}, // подохнуть в болоте
rus_verbs:кипятиться{}, // кипятиться в чайнике
rus_verbs:уродиться{}, // уродиться в лесу
rus_verbs:продолжиться{}, // продолжиться в баре
rus_verbs:расшифровать{}, // расшифровать в специальном устройстве
rus_verbs:посапывать{}, // посапывать в кровати
rus_verbs:скрючиться{}, // скрючиться в мешке
rus_verbs:лютовать{}, // лютовать в отдаленных селах
rus_verbs:расписать{}, // расписать в статье
rus_verbs:публиковаться{}, // публиковаться в научном журнале
rus_verbs:зарегистрировать{}, // зарегистрировать в комитете
rus_verbs:прожечь{}, // прожечь в листе
rus_verbs:переждать{}, // переждать в окопе
rus_verbs:публиковать{}, // публиковать в журнале
rus_verbs:морщить{}, // морщить в уголках глаз
rus_verbs:спиться{}, // спиться в одиночестве
rus_verbs:изведать{}, // изведать в гареме
rus_verbs:обмануться{}, // обмануться в ожиданиях
rus_verbs:сочетать{}, // сочетать в себе
rus_verbs:подрабатывать{}, // подрабатывать в магазине
rus_verbs:репетировать{}, // репетировать в студии
rus_verbs:рябить{}, // рябить в глазах
rus_verbs:намочить{}, // намочить в луже
rus_verbs:скатать{}, // скатать в руке
rus_verbs:одевать{}, // одевать в магазине
rus_verbs:испечь{}, // испечь в духовке
rus_verbs:сбрить{}, // сбрить в подмышках
rus_verbs:зажужжать{}, // зажужжать в ухе
rus_verbs:сберечь{}, // сберечь в тайном месте
rus_verbs:согреться{}, // согреться в хижине
инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле
глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш },
rus_verbs:переплыть{}, // переплыть в лодочке
rus_verbs:передохнуть{}, // передохнуть в тени
rus_verbs:отсвечивать{}, // отсвечивать в зеркалах
rus_verbs:переправляться{}, // переправляться в лодках
rus_verbs:накупить{}, // накупить в магазине
rus_verbs:проторчать{}, // проторчать в очереди
rus_verbs:проскальзывать{}, // проскальзывать в сообщениях
rus_verbs:застукать{}, // застукать в солярии
rus_verbs:наесть{}, // наесть в отпуске
rus_verbs:подвизаться{}, // подвизаться в новом деле
rus_verbs:вычистить{}, // вычистить в саду
rus_verbs:кормиться{}, // кормиться в лесу
rus_verbs:покурить{}, // покурить в саду
rus_verbs:понизиться{}, // понизиться в ранге
rus_verbs:зимовать{}, // зимовать в избушке
rus_verbs:проверяться{}, // проверяться в службе безопасности
rus_verbs:подпирать{}, // подпирать в первом забое
rus_verbs:кувыркаться{}, // кувыркаться в постели
rus_verbs:похрапывать{}, // похрапывать в постели
rus_verbs:завязнуть{}, // завязнуть в песке
rus_verbs:трактовать{}, // трактовать в исследовательской статье
rus_verbs:замедляться{}, // замедляться в тяжелой воде
rus_verbs:шастать{}, // шастать в здании
rus_verbs:заночевать{}, // заночевать в пути
rus_verbs:наметиться{}, // наметиться в исследованиях рака
rus_verbs:освежить{}, // освежить в памяти
rus_verbs:оспаривать{}, // оспаривать в суде
rus_verbs:умещаться{}, // умещаться в ячейке
rus_verbs:искупить{}, // искупить в бою
rus_verbs:отсиживаться{}, // отсиживаться в тылу
rus_verbs:мчать{}, // мчать в кабриолете
rus_verbs:обличать{}, // обличать в своем выступлении
rus_verbs:сгнить{}, // сгнить в тюряге
rus_verbs:опробовать{}, // опробовать в деле
rus_verbs:тренировать{}, // тренировать в зале
rus_verbs:прославить{}, // прославить в академии
rus_verbs:учитываться{}, // учитываться в дипломной работе
rus_verbs:повеселиться{}, // повеселиться в лагере
rus_verbs:поумнеть{}, // поумнеть в карцере
rus_verbs:перестрелять{}, // перестрелять в воздухе
rus_verbs:проведать{}, // проведать в больнице
rus_verbs:измучиться{}, // измучиться в деревне
rus_verbs:прощупать{}, // прощупать в глубине
rus_verbs:изготовлять{}, // изготовлять в сарае
rus_verbs:свирепствовать{}, // свирепствовать в популяции
rus_verbs:иссякать{}, // иссякать в источнике
rus_verbs:гнездиться{}, // гнездиться в дупле
rus_verbs:разогнаться{}, // разогнаться в спортивной машине
rus_verbs:опознавать{}, // опознавать в неизвестном
rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде
rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках
rus_verbs:редактировать{}, // редактировать в редакторе
rus_verbs:покупаться{}, // покупаться в магазине
rus_verbs:промышлять{}, // промышлять в роще
rus_verbs:растягиваться{}, // растягиваться в коридоре
rus_verbs:приобретаться{}, // приобретаться в антикварных лавках
инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде
глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш },
rus_verbs:запечатлеться{}, // запечатлеться в мозгу
rus_verbs:укрывать{}, // укрывать в подвале
rus_verbs:закрепиться{}, // закрепиться в первой башне
rus_verbs:освежать{}, // освежать в памяти
rus_verbs:громыхать{}, // громыхать в ванной
инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати
глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш },
rus_verbs:добываться{}, // добываться в шахтах
rus_verbs:растворить{}, // растворить в кислоте
rus_verbs:приплясывать{}, // приплясывать в гримерке
rus_verbs:доживать{}, // доживать в доме престарелых
rus_verbs:отпраздновать{}, // отпраздновать в ресторане
rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях
rus_verbs:помыть{}, // помыть в проточной воде
инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке
глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш },
прилагательное:увязавший{ вид:несоверш },
rus_verbs:наличествовать{}, // наличествовать в запаснике
rus_verbs:нащупывать{}, // нащупывать в кармане
rus_verbs:повествоваться{}, // повествоваться в рассказе
rus_verbs:отремонтировать{}, // отремонтировать в техцентре
rus_verbs:покалывать{}, // покалывать в правом боку
rus_verbs:сиживать{}, // сиживать в саду
rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях
rus_verbs:укрепляться{}, // укрепляться в мнении
rus_verbs:разниться{}, // разниться во взглядах
rus_verbs:сполоснуть{}, // сполоснуть в водичке
rus_verbs:скупать{}, // скупать в магазине
rus_verbs:почесывать{}, // почесывать в паху
rus_verbs:оформлять{}, // оформлять в конторе
rus_verbs:распускаться{}, // распускаться в садах
rus_verbs:зарябить{}, // зарябить в глазах
rus_verbs:загореть{}, // загореть в Испании
rus_verbs:очищаться{}, // очищаться в баке
rus_verbs:остудить{}, // остудить в холодной воде
rus_verbs:разбомбить{}, // разбомбить в горах
rus_verbs:издохнуть{}, // издохнуть в бедности
rus_verbs:проехаться{}, // проехаться в новой машине
rus_verbs:задействовать{}, // задействовать в анализе
rus_verbs:произрастать{}, // произрастать в степи
rus_verbs:разуться{}, // разуться в прихожей
rus_verbs:сооружать{}, // сооружать в огороде
rus_verbs:зачитывать{}, // зачитывать в суде
rus_verbs:состязаться{}, // состязаться в остроумии
rus_verbs:ополоснуть{}, // ополоснуть в молоке
rus_verbs:уместиться{}, // уместиться в кармане
rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом
rus_verbs:стираться{}, // стираться в стиральной машине
rus_verbs:искупаться{}, // искупаться в прохладной реке
rus_verbs:курировать{}, // курировать в правительстве
rus_verbs:закупить{}, // закупить в магазине
rus_verbs:плодиться{}, // плодиться в подходящих условиях
rus_verbs:горланить{}, // горланить в парке
rus_verbs:першить{}, // першить в горле
rus_verbs:пригрезиться{}, // пригрезиться во сне
rus_verbs:исправлять{}, // исправлять в тетрадке
rus_verbs:расслабляться{}, // расслабляться в гамаке
rus_verbs:скапливаться{}, // скапливаться в нижней части
rus_verbs:сплетничать{}, // сплетничают в комнате
rus_verbs:раздевать{}, // раздевать в кабинке
rus_verbs:окопаться{}, // окопаться в лесу
rus_verbs:загорать{}, // загорать в Испании
rus_verbs:подпевать{}, // подпевать в церковном хоре
rus_verbs:прожужжать{}, // прожужжать в динамике
rus_verbs:изучаться{}, // изучаться в дикой природе
rus_verbs:заклубиться{}, // заклубиться в воздухе
rus_verbs:подметать{}, // подметать в зале
rus_verbs:подозреваться{}, // подозреваться в совершении кражи
rus_verbs:обогащать{}, // обогащать в специальном аппарате
rus_verbs:издаться{}, // издаться в другом издательстве
rus_verbs:справить{}, // справить в кустах нужду
rus_verbs:помыться{}, // помыться в бане
rus_verbs:проскакивать{}, // проскакивать в словах
rus_verbs:попивать{}, // попивать в кафе чай
rus_verbs:оформляться{}, // оформляться в регистратуре
rus_verbs:чирикать{}, // чирикать в кустах
rus_verbs:скупить{}, // скупить в магазинах
rus_verbs:переночевать{}, // переночевать в гостинице
rus_verbs:концентрироваться{}, // концентрироваться в пробирке
rus_verbs:одичать{}, // одичать в лесу
rus_verbs:ковырнуть{}, // ковырнуть в ухе
rus_verbs:затеплиться{}, // затеплиться в глубине души
rus_verbs:разгрести{}, // разгрести в задачах залежи
rus_verbs:застопориться{}, // застопориться в начале списка
rus_verbs:перечисляться{}, // перечисляться во введении
rus_verbs:покататься{}, // покататься в парке аттракционов
rus_verbs:изловить{}, // изловить в поле
rus_verbs:прославлять{}, // прославлять в стихах
rus_verbs:промочить{}, // промочить в луже
rus_verbs:поделывать{}, // поделывать в отпуске
rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии
rus_verbs:подстеречь{}, // подстеречь в подъезде
rus_verbs:прикупить{}, // прикупить в магазине
rus_verbs:перемешивать{}, // перемешивать в кастрюле
rus_verbs:тискать{}, // тискать в углу
rus_verbs:купать{}, // купать в теплой водичке
rus_verbs:завариться{}, // завариться в стакане
rus_verbs:притулиться{}, // притулиться в углу
rus_verbs:пострелять{}, // пострелять в тире
rus_verbs:навесить{}, // навесить в больнице
инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере
глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш },
rus_verbs:нежиться{}, // нежится в постельке
rus_verbs:притомиться{}, // притомиться в школе
rus_verbs:раздвоиться{}, // раздвоиться в глазах
rus_verbs:навалить{}, // навалить в углу
rus_verbs:замуровать{}, // замуровать в склепе
rus_verbs:поселяться{}, // поселяться в кроне дуба
rus_verbs:потягиваться{}, // потягиваться в кровати
rus_verbs:укачать{}, // укачать в поезде
rus_verbs:отлеживаться{}, // отлеживаться в гамаке
rus_verbs:разменять{}, // разменять в кассе
rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде
rus_verbs:ржаветь{}, // ржаветь в воде
rus_verbs:уличить{}, // уличить в плагиате
rus_verbs:мутиться{}, // мутиться в голове
rus_verbs:растворять{}, // растворять в бензоле
rus_verbs:двоиться{}, // двоиться в глазах
rus_verbs:оговорить{}, // оговорить в договоре
rus_verbs:подделать{}, // подделать в документе
rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети
rus_verbs:растолстеть{}, // растолстеть в талии
rus_verbs:повоевать{}, // повоевать в городских условиях
rus_verbs:прибраться{}, // гнушаться прибраться в хлеву
rus_verbs:поглощаться{}, // поглощаться в металлической фольге
rus_verbs:ухать{}, // ухать в лесу
rus_verbs:подписываться{}, // подписываться в петиции
rus_verbs:покатать{}, // покатать в машинке
rus_verbs:излечиться{}, // излечиться в клинике
rus_verbs:трепыхаться{}, // трепыхаться в мешке
rus_verbs:кипятить{}, // кипятить в кастрюле
rus_verbs:понастроить{}, // понастроить в прибрежной зоне
rus_verbs:перебывать{}, // перебывать во всех европейских столицах
rus_verbs:оглашать{}, // оглашать в итоговой части
rus_verbs:преуспевать{}, // преуспевать в новом бизнесе
rus_verbs:консультироваться{}, // консультироваться в техподдержке
rus_verbs:накапливать{}, // накапливать в печени
rus_verbs:перемешать{}, // перемешать в контейнере
rus_verbs:наследить{}, // наследить в коридоре
rus_verbs:выявиться{}, // выявиться в результе
rus_verbs:забулькать{}, // забулькать в болоте
rus_verbs:отваривать{}, // отваривать в молоке
rus_verbs:запутываться{}, // запутываться в веревках
rus_verbs:нагреться{}, // нагреться в микроволновой печке
rus_verbs:рыбачить{}, // рыбачить в открытом море
rus_verbs:укорениться{}, // укорениться в сознании широких народных масс
rus_verbs:умывать{}, // умывать в тазике
rus_verbs:защекотать{}, // защекотать в носу
rus_verbs:заходиться{}, // заходиться в плаче
инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке
глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш },
деепричастие:искупав{}, деепричастие:искупая{},
rus_verbs:заморозить{}, // заморозить в холодильнике
rus_verbs:закреплять{}, // закреплять в металлическом держателе
rus_verbs:расхватать{}, // расхватать в магазине
rus_verbs:истязать{}, // истязать в тюремном подвале
rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере
rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле
rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете
rus_verbs:подогреть{}, // подогрей в микроволновке
rus_verbs:подогревать{},
rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку
rus_verbs:проделать{}, // проделать в стене дыру
инфинитив:жениться{ вид:соверш }, // жениться в Техасе
инфинитив:жениться{ вид:несоверш },
глагол:жениться{ вид:соверш },
глагол:жениться{ вид:несоверш },
деепричастие:женившись{},
деепричастие:женясь{},
прилагательное:женатый{},
прилагательное:женившийся{вид:соверш},
прилагательное:женящийся{},
rus_verbs:всхрапнуть{}, // всхрапнуть во сне
rus_verbs:всхрапывать{}, // всхрапывать во сне
rus_verbs:ворочаться{}, // Собака ворочается во сне
rus_verbs:воссоздаваться{}, // воссоздаваться в памяти
rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах
инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу
инфинитив:атаковать{ вид:соверш },
глагол:атаковать{ вид:несоверш },
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{},
прилагательное:атаковавший{},
прилагательное:атакующий{},
инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени
инфинитив:аккумулировать{вид:соверш},
глагол:аккумулировать{вид:несоверш},
глагол:аккумулировать{вид:соверш},
прилагательное:аккумулированный{},
прилагательное:аккумулирующий{},
//прилагательное:аккумулировавший{ вид:несоверш },
прилагательное:аккумулировавший{ вид:соверш },
rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию
rus_verbs:вырасти{}, // Он вырос в глазах коллег.
rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо.
rus_verbs:убить{}, // убить в себе зверя
инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани
инфинитив:абсорбироваться{ вид:несоверш },
глагол:абсорбироваться{ вид:соверш },
глагол:абсорбироваться{ вид:несоверш },
rus_verbs:поставить{}, // поставить в углу
rus_verbs:сжимать{}, // сжимать в кулаке
rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах
rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях
инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы
инфинитив:активизироваться{ вид:соверш },
глагол:активизироваться{ вид:несоверш },
глагол:активизироваться{ вид:соверш },
rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера
rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе
rus_verbs:базировать{}, // установка будет базирована в лесу
rus_verbs:барахтаться{}, // дети барахтались в воде
rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка
rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне
rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе
rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины
rus_verbs:блуждать{}, // Туристы блуждали в лесу
rus_verbs:брать{}, // Жена берет деньги в тумбочке
rus_verbs:бродить{}, // парочки бродили в парке
rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге
rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США
rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде
rus_verbs:вариться{}, // Курица варится в кастрюле
rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году
rus_verbs:прокручиваться{}, // Ключ прокручивается в замке
rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке
rus_verbs:храниться{}, // Настройки хранятся в текстовом файле
rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле
rus_verbs:витать{}, // Мальчик витает в облаках
rus_verbs:владычествовать{}, // Король владычествует в стране
rus_verbs:властвовать{}, // Олигархи властвовали в стране
rus_verbs:возбудить{}, // возбудить в сердце тоску
rus_verbs:возбуждать{}, // возбуждать в сердце тоску
rus_verbs:возвыситься{}, // возвыситься в глазах современников
rus_verbs:возжечь{}, // возжечь в храме огонь
rus_verbs:возжечься{}, // Огонь возжёгся в храме
rus_verbs:возжигать{}, // возжигать в храме огонь
rus_verbs:возжигаться{}, // Огонь возжигается в храме
rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь
rus_verbs:вознамериться{}, // вознамериться уйти в монастырь
rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове
rus_verbs:возникнуть{}, // Новые идейки возникли в голове
rus_verbs:возродиться{}, // возродиться в новом качестве
rus_verbs:возрождать{}, // возрождать в новом качестве
rus_verbs:возрождаться{}, // возрождаться в новом амплуа
rus_verbs:ворошить{}, // ворошить в камине кочергой золу
rus_verbs:воспевать{}, // Поэты воспевают героев в одах
rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами
rus_verbs:воспеть{}, // Поэты воспели в этой оде героев
rus_verbs:воспретить{}, // воспретить в помещении азартные игры
rus_verbs:восславить{}, // Поэты восславили в одах
rus_verbs:восславлять{}, // Поэты восславляют в одах
rus_verbs:восславляться{}, // Героя восславляются в одах
rus_verbs:воссоздать{}, // воссоздает в памяти образ человека
rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека
rus_verbs:воссоздаться{}, // воссоздаться в памяти
rus_verbs:вскипятить{}, // вскипятить в чайнике воду
rus_verbs:вскипятиться{}, // вскипятиться в чайнике
rus_verbs:встретить{}, // встретить в классе старого приятеля
rus_verbs:встретиться{}, // встретиться в классе
rus_verbs:встречать{}, // встречать в лесу голодного медведя
rus_verbs:встречаться{}, // встречаться в кафе
rus_verbs:выбривать{}, // выбривать что-то в подмышках
rus_verbs:выбрить{}, // выбрить что-то в паху
rus_verbs:вывалять{}, // вывалять кого-то в грязи
rus_verbs:вываляться{}, // вываляться в грязи
rus_verbs:вываривать{}, // вываривать в молоке
rus_verbs:вывариваться{}, // вывариваться в молоке
rus_verbs:выварить{}, // выварить в молоке
rus_verbs:вывариться{}, // вывариться в молоке
rus_verbs:выгрызать{}, // выгрызать в сыре отверствие
rus_verbs:выгрызть{}, // выгрызть в сыре отверстие
rus_verbs:выгуливать{}, // выгуливать в парке собаку
rus_verbs:выгулять{}, // выгулять в парке собаку
rus_verbs:выдолбить{}, // выдолбить в стволе углубление
rus_verbs:выжить{}, // выжить в пустыне
rus_verbs:Выискать{}, // Выискать в программе ошибку
rus_verbs:выискаться{}, // Ошибка выискалась в программе
rus_verbs:выискивать{}, // выискивать в программе ошибку
rus_verbs:выискиваться{}, // выискиваться в программе
rus_verbs:выкраивать{}, // выкраивать в расписании время
rus_verbs:выкраиваться{}, // выкраиваться в расписании
инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере
глагол:выкупаться{вид:соверш},
rus_verbs:выловить{}, // выловить в пруду
rus_verbs:вымачивать{}, // вымачивать в молоке
rus_verbs:вымачиваться{}, // вымачиваться в молоке
rus_verbs:вынюхивать{}, // вынюхивать в траве следы
rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду
rus_verbs:выпачкаться{}, // выпачкаться в грязи
rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков
rus_verbs:выращивать{}, // выращивать в теплице помидоры
rus_verbs:выращиваться{}, // выращиваться в теплице
rus_verbs:вырыть{}, // вырыть в земле глубокую яму
rus_verbs:высадить{}, // высадить в пустынной местности
rus_verbs:высадиться{}, // высадиться в пустынной местности
rus_verbs:высаживать{}, // высаживать в пустыне
rus_verbs:высверливать{}, // высверливать в доске отверствие
rus_verbs:высверливаться{}, // высверливаться в стене
rus_verbs:высверлить{}, // высверлить в стене отверствие
rus_verbs:высверлиться{}, // высверлиться в стене
rus_verbs:выскоблить{}, // выскоблить в столешнице канавку
rus_verbs:высматривать{}, // высматривать в темноте
rus_verbs:заметить{}, // заметить в помещении
rus_verbs:оказаться{}, // оказаться в первых рядах
rus_verbs:душить{}, // душить в объятиях
rus_verbs:оставаться{}, // оставаться в классе
rus_verbs:появиться{}, // впервые появиться в фильме
rus_verbs:лежать{}, // лежать в футляре
rus_verbs:раздаться{}, // раздаться в плечах
rus_verbs:ждать{}, // ждать в здании вокзала
rus_verbs:жить{}, // жить в трущобах
rus_verbs:постелить{}, // постелить в прихожей
rus_verbs:оказываться{}, // оказываться в неприятной ситуации
rus_verbs:держать{}, // держать в голове
rus_verbs:обнаружить{}, // обнаружить в себе способность
rus_verbs:начинать{}, // начинать в лаборатории
rus_verbs:рассказывать{}, // рассказывать в лицах
rus_verbs:ожидать{}, // ожидать в помещении
rus_verbs:продолжить{}, // продолжить в помещении
rus_verbs:состоять{}, // состоять в группе
rus_verbs:родиться{}, // родиться в рубашке
rus_verbs:искать{}, // искать в кармане
rus_verbs:иметься{}, // иметься в наличии
rus_verbs:говориться{}, // говориться в среде панков
rus_verbs:клясться{}, // клясться в верности
rus_verbs:узнавать{}, // узнавать в нем своего сына
rus_verbs:признаться{}, // признаться в ошибке
rus_verbs:сомневаться{}, // сомневаться в искренности
rus_verbs:толочь{}, // толочь в ступе
rus_verbs:понадобиться{}, // понадобиться в суде
rus_verbs:служить{}, // служить в пехоте
rus_verbs:потолочь{}, // потолочь в ступе
rus_verbs:появляться{}, // появляться в театре
rus_verbs:сжать{}, // сжать в объятиях
rus_verbs:действовать{}, // действовать в постановке
rus_verbs:селить{}, // селить в гостинице
rus_verbs:поймать{}, // поймать в лесу
rus_verbs:увидать{}, // увидать в толпе
rus_verbs:подождать{}, // подождать в кабинете
rus_verbs:прочесть{}, // прочесть в глазах
rus_verbs:тонуть{}, // тонуть в реке
rus_verbs:ощущать{}, // ощущать в животе
rus_verbs:ошибиться{}, // ошибиться в расчетах
rus_verbs:отметить{}, // отметить в списке
rus_verbs:показывать{}, // показывать в динамике
rus_verbs:скрыться{}, // скрыться в траве
rus_verbs:убедиться{}, // убедиться в корректности
rus_verbs:прозвучать{}, // прозвучать в наушниках
rus_verbs:разговаривать{}, // разговаривать в фойе
rus_verbs:издать{}, // издать в России
rus_verbs:прочитать{}, // прочитать в газете
rus_verbs:попробовать{}, // попробовать в деле
rus_verbs:замечать{}, // замечать в программе ошибку
rus_verbs:нести{}, // нести в руках
rus_verbs:пропасть{}, // пропасть в плену
rus_verbs:носить{}, // носить в кармане
rus_verbs:гореть{}, // гореть в аду
rus_verbs:поправить{}, // поправить в программе
rus_verbs:застыть{}, // застыть в неудобной позе
rus_verbs:получать{}, // получать в кассе
rus_verbs:потребоваться{}, // потребоваться в работе
rus_verbs:спрятать{}, // спрятать в шкафу
rus_verbs:учиться{}, // учиться в институте
rus_verbs:развернуться{}, // развернуться в коридоре
rus_verbs:подозревать{}, // подозревать в мошенничестве
rus_verbs:играть{}, // играть в команде
rus_verbs:сыграть{}, // сыграть в команде
rus_verbs:строить{}, // строить в деревне
rus_verbs:устроить{}, // устроить в доме вечеринку
rus_verbs:находить{}, // находить в лесу
rus_verbs:нуждаться{}, // нуждаться в деньгах
rus_verbs:испытать{}, // испытать в рабочей обстановке
rus_verbs:мелькнуть{}, // мелькнуть в прицеле
rus_verbs:очутиться{}, // очутиться в закрытом помещении
инфинитив:использовать{вид:соверш}, // использовать в работе
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
глагол:использовать{вид:соверш},
rus_verbs:лететь{}, // лететь в самолете
rus_verbs:смеяться{}, // смеяться в цирке
rus_verbs:ездить{}, // ездить в лимузине
rus_verbs:заснуть{}, // заснуть в неудобной позе
rus_verbs:застать{}, // застать в неформальной обстановке
rus_verbs:очнуться{}, // очнуться в незнакомой обстановке
rus_verbs:твориться{}, // Что творится в закрытой зоне
rus_verbs:разглядеть{}, // разглядеть в темноте
rus_verbs:изучать{}, // изучать в естественных условиях
rus_verbs:удержаться{}, // удержаться в седле
rus_verbs:побывать{}, // побывать в зоопарке
rus_verbs:уловить{}, // уловить в словах нотку отчаяния
rus_verbs:приобрести{}, // приобрести в лавке
rus_verbs:исчезать{}, // исчезать в тумане
rus_verbs:уверять{}, // уверять в своей невиновности
rus_verbs:продолжаться{}, // продолжаться в воздухе
rus_verbs:открывать{}, // открывать в городе новый стадион
rus_verbs:поддержать{}, // поддержать в парке порядок
rus_verbs:солить{}, // солить в бочке
rus_verbs:прожить{}, // прожить в деревне
rus_verbs:создавать{}, // создавать в театре
rus_verbs:обсуждать{}, // обсуждать в коллективе
rus_verbs:заказать{}, // заказать в магазине
rus_verbs:отыскать{}, // отыскать в гараже
rus_verbs:уснуть{}, // уснуть в кресле
rus_verbs:задержаться{}, // задержаться в театре
rus_verbs:подобрать{}, // подобрать в коллекции
rus_verbs:пробовать{}, // пробовать в работе
rus_verbs:курить{}, // курить в закрытом помещении
rus_verbs:устраивать{}, // устраивать в лесу засаду
rus_verbs:установить{}, // установить в багажнике
rus_verbs:запереть{}, // запереть в сарае
rus_verbs:содержать{}, // содержать в достатке
rus_verbs:синеть{}, // синеть в кислородной атмосфере
rus_verbs:слышаться{}, // слышаться в голосе
rus_verbs:закрыться{}, // закрыться в здании
rus_verbs:скрываться{}, // скрываться в квартире
rus_verbs:родить{}, // родить в больнице
rus_verbs:описать{}, // описать в заметках
rus_verbs:перехватить{}, // перехватить в коридоре
rus_verbs:менять{}, // менять в магазине
rus_verbs:скрывать{}, // скрывать в чужой квартире
rus_verbs:стиснуть{}, // стиснуть в стальных объятиях
rus_verbs:останавливаться{}, // останавливаться в гостинице
rus_verbs:мелькать{}, // мелькать в телевизоре
rus_verbs:присутствовать{}, // присутствовать в аудитории
rus_verbs:украсть{}, // украсть в магазине
rus_verbs:победить{}, // победить в войне
rus_verbs:расположиться{}, // расположиться в гостинице
rus_verbs:упомянуть{}, // упомянуть в своей книге
rus_verbs:плыть{}, // плыть в старой бочке
rus_verbs:нащупать{}, // нащупать в глубине
rus_verbs:проявляться{}, // проявляться в работе
rus_verbs:затихнуть{}, // затихнуть в норе
rus_verbs:построить{}, // построить в гараже
rus_verbs:поддерживать{}, // поддерживать в исправном состоянии
rus_verbs:заработать{}, // заработать в стартапе
rus_verbs:сломать{}, // сломать в суставе
rus_verbs:снимать{}, // снимать в гардеробе
rus_verbs:сохранить{}, // сохранить в коллекции
rus_verbs:располагаться{}, // располагаться в отдельном кабинете
rus_verbs:сражаться{}, // сражаться в честном бою
rus_verbs:спускаться{}, // спускаться в батискафе
rus_verbs:уничтожить{}, // уничтожить в схроне
rus_verbs:изучить{}, // изучить в естественных условиях
rus_verbs:рождаться{}, // рождаться в муках
rus_verbs:пребывать{}, // пребывать в прострации
rus_verbs:прилететь{}, // прилететь в аэробусе
rus_verbs:догнать{}, // догнать в переулке
rus_verbs:изобразить{}, // изобразить в танце
rus_verbs:проехать{}, // проехать в легковушке
rus_verbs:убедить{}, // убедить в разумности
rus_verbs:приготовить{}, // приготовить в духовке
rus_verbs:собирать{}, // собирать в лесу
rus_verbs:поплыть{}, // поплыть в катере
rus_verbs:доверять{}, // доверять в управлении
rus_verbs:разобраться{}, // разобраться в законах
rus_verbs:ловить{}, // ловить в озере
rus_verbs:проесть{}, // проесть в куске металла отверстие
rus_verbs:спрятаться{}, // спрятаться в подвале
rus_verbs:провозгласить{}, // провозгласить в речи
rus_verbs:изложить{}, // изложить в своём выступлении
rus_verbs:замяться{}, // замяться в коридоре
rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях
rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна
rus_verbs:хранить{}, // хранить в шкатулке
rus_verbs:шутить{}, // шутить в классе
глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях
инфинитив:рассыпаться{ aux stress="рассып^аться" },
rus_verbs:чертить{}, // чертить в тетрадке
rus_verbs:отразиться{}, // отразиться в аттестате
rus_verbs:греть{}, // греть в микроволновке
rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса
rus_verbs:рассуждать{}, // Автор рассуждает в своей статье
rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда
rus_verbs:окружать{}, // окружать в лесу
rus_verbs:сопровождать{}, // сопровождать в операции
rus_verbs:заканчиваться{}, // заканчиваться в дороге
rus_verbs:поселиться{}, // поселиться в загородном доме
rus_verbs:охватывать{}, // охватывать в хронологии
rus_verbs:запеть{}, // запеть в кино
инфинитив:провозить{вид:несоверш}, // провозить в багаже
глагол:провозить{вид:несоверш},
rus_verbs:мочить{}, // мочить в сортире
rus_verbs:перевернуться{}, // перевернуться в полёте
rus_verbs:улететь{}, // улететь в теплые края
rus_verbs:сдержать{}, // сдержать в руках
rus_verbs:преследовать{}, // преследовать в любой другой стране
rus_verbs:драться{}, // драться в баре
rus_verbs:просидеть{}, // просидеть в классе
rus_verbs:убираться{}, // убираться в квартире
rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения
rus_verbs:пугать{}, // пугать в прессе
rus_verbs:отреагировать{}, // отреагировать в прессе
rus_verbs:проверять{}, // проверять в аппарате
rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив
rus_verbs:летать{}, // летать в комфортабельном частном самолёте
rus_verbs:толпиться{}, // толпиться в фойе
rus_verbs:плавать{}, // плавать в специальном костюме
rus_verbs:пробыть{}, // пробыть в воде слишком долго
rus_verbs:прикинуть{}, // прикинуть в уме
rus_verbs:застрять{}, // застрять в лифте
rus_verbs:метаться{}, // метаться в кровате
rus_verbs:сжечь{}, // сжечь в печке
rus_verbs:расслабиться{}, // расслабиться в ванной
rus_verbs:услыхать{}, // услыхать в автобусе
rus_verbs:удержать{}, // удержать в вертикальном положении
rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы
rus_verbs:рассмотреть{}, // рассмотреть в капле воды
rus_verbs:просмотреть{}, // просмотреть в браузере
rus_verbs:учесть{}, // учесть в планах
rus_verbs:уезжать{}, // уезжать в чьей-то машине
rus_verbs:похоронить{}, // похоронить в мерзлой земле
rus_verbs:растянуться{}, // растянуться в расслабленной позе
rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке
rus_verbs:гулять{}, // гулять в парке
rus_verbs:утонуть{}, // утонуть в реке
rus_verbs:зажать{}, // зажать в медвежьих объятиях
rus_verbs:усомниться{}, // усомниться в объективности
rus_verbs:танцевать{}, // танцевать в спортзале
rus_verbs:проноситься{}, // проноситься в голове
rus_verbs:трудиться{}, // трудиться в кооперативе
глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке
инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный },
rus_verbs:сушить{}, // сушить в сушильном шкафу
rus_verbs:зашевелиться{}, // зашевелиться в траве
rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке
rus_verbs:промелькнуть{}, // промелькнуть в окне
rus_verbs:поучаствовать{}, // поучаствовать в обсуждении
rus_verbs:закрыть{}, // закрыть в комнате
rus_verbs:запирать{}, // запирать в комнате
rus_verbs:закрывать{}, // закрывать в доме
rus_verbs:заблокировать{}, // заблокировать в доме
rus_verbs:зацвести{}, // В садах зацвела сирень
rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу.
rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе
rus_verbs:стоять{}, // войска, стоявшие в Риме
rus_verbs:закалить{}, // ветераны, закаленные в боях
rus_verbs:выступать{}, // пришлось выступать в тюрьме.
rus_verbs:выступить{}, // пришлось выступить в тюрьме.
rus_verbs:закопошиться{}, // Мыши закопошились в траве
rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре
rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре
rus_verbs:закрываться{}, // закрываться в комнате
rus_verbs:провалиться{}, // провалиться в прокате
деепричастие:авторизируясь{ вид:несоверш },
глагол:авторизироваться{ вид:несоверш },
инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе
rus_verbs:существовать{}, // существовать в вакууме
деепричастие:находясь{},
прилагательное:находившийся{},
прилагательное:находящийся{},
глагол:находиться{ вид:несоверш },
инфинитив:находиться{ вид:несоверш }, // находиться в вакууме
rus_verbs:регистрировать{}, // регистрировать в инспекции
глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш },
инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции
rus_verbs:поковыряться{}, // поковыряться в носу
rus_verbs:оттаять{}, // оттаять в кипятке
rus_verbs:распинаться{}, // распинаться в проклятиях
rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России
rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе
rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения.
прилагательное:несчастный{}, // Он очень несчастен в семейной жизни.
rus_verbs:объясниться{}, // Он объяснился в любви.
прилагательное:нетвердый{}, // Он нетвёрд в истории.
rus_verbs:заниматься{}, // Он занимается в читальном зале.
rus_verbs:вращаться{}, // Он вращается в учёных кругах.
прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне.
rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры.
rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения.
rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев.
rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия
rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях.
rus_verbs:продолжать{}, // Продолжайте в том же духе.
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:болтать{}, // Не болтай в присутствии начальника!
rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника!
rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей
rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию
rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине.
rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах
rus_verbs:сходиться{}, // Все дороги сходятся в Москве
rus_verbs:убирать{}, // убирать в комнате
rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста
rus_verbs:уединяться{}, // уединяться в пустыне
rus_verbs:уживаться{}, // уживаться в одном коллективе
rus_verbs:укорять{}, // укорять друга в забывчивости
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы
rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем
rus_verbs:работать{}, // Я работаю в театре.
rus_verbs:признать{}, // Я признал в нём старого друга.
rus_verbs:преподавать{}, // Я преподаю в университете.
rus_verbs:понимать{}, // Я плохо понимаю в живописи.
rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах
rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа
rus_verbs:замереть{}, // вся толпа замерла в восхищении
rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле.
rus_verbs:идти{}, // Я иду в неопределённом направлении.
rus_verbs:заболеть{}, // Я заболел в дороге.
rus_verbs:ехать{}, // Я еду в автобусе
rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю.
rus_verbs:провести{}, // Юные годы он провёл в Италии.
rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти.
rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении.
rus_verbs:произойти{}, // Это произошло в одном городе в Японии.
rus_verbs:привидеться{}, // Это мне привиделось во сне.
rus_verbs:держаться{}, // Это дело держится в большом секрете.
rus_verbs:привиться{}, // Это выражение не привилось в русском языке.
rus_verbs:восстановиться{}, // Эти писатели восстановились в правах.
rus_verbs:быть{}, // Эта книга есть в любом книжном магазине.
прилагательное:популярный{}, // Эта идея очень популярна в массах.
rus_verbs:шуметь{}, // Шумит в голове.
rus_verbs:остаться{}, // Шляпа осталась в поезде.
rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях.
rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе.
rus_verbs:пересохнуть{}, // У меня в горле пересохло.
rus_verbs:щекотать{}, // У меня в горле щекочет.
rus_verbs:колоть{}, // У меня в боку колет.
прилагательное:свежий{}, // Событие ещё свежо в памяти.
rus_verbs:собрать{}, // Соберите всех учеников во дворе.
rus_verbs:белеть{}, // Снег белеет в горах.
rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте?
rus_verbs:таять{}, // Сахар тает в кипятке.
rus_verbs:жать{}, // Сапог жмёт в подъёме.
rus_verbs:возиться{}, // Ребята возятся в углу.
rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме.
rus_verbs:кружиться{}, // Они кружились в вальсе.
rus_verbs:выставлять{}, // Они выставляют его в смешном виде.
rus_verbs:бывать{}, // Она часто бывает в обществе.
rus_verbs:петь{}, // Она поёт в опере.
rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях.
rus_verbs:валяться{}, // Вещи валялись в беспорядке.
rus_verbs:пройти{}, // Весь день прошёл в беготне.
rus_verbs:продавать{}, // В этом магазине продают обувь.
rus_verbs:заключаться{}, // В этом заключается вся сущность.
rus_verbs:звенеть{}, // В ушах звенит.
rus_verbs:проступить{}, // В тумане проступили очертания корабля.
rus_verbs:бить{}, // В саду бьёт фонтан.
rus_verbs:проскользнуть{}, // В речи проскользнул упрёк.
rus_verbs:оставить{}, // Не оставь товарища в опасности.
rus_verbs:прогулять{}, // Мы прогуляли час в парке.
rus_verbs:перебить{}, // Мы перебили врагов в бою.
rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице.
rus_verbs:видеть{}, // Он многое видел в жизни.
// глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере.
rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах.
rus_verbs:кинуть{}, // Он кинул меня в беде.
rus_verbs:приходить{}, // Приходи в сентябре
rus_verbs:воскрешать{}, // воскрешать в памяти
rus_verbs:соединять{}, // соединять в себе
rus_verbs:разбираться{}, // умение разбираться в вещах
rus_verbs:делать{}, // В её комнате делали обыск.
rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина.
rus_verbs:начаться{}, // В деревне начались полевые работы.
rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль.
rus_verbs:вертеться{}, // В голове вертится вчерашний разговор.
rus_verbs:веять{}, // В воздухе веет прохладой.
rus_verbs:висеть{}, // В воздухе висит зной.
rus_verbs:носиться{}, // В воздухе носятся комары.
rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее
rus_verbs:воскресить{}, // воскресить в памяти
rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне
rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина
прилагательное:уверенный{ причастие }, // Она уверена в своих силах.
прилагательное:постоянный{}, // Она постоянна во вкусах.
прилагательное:сильный{}, // Он не силён в математике.
прилагательное:повинный{}, // Он не повинен в этом.
прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары
rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории
прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве.
rus_verbs:сесть{}, // Она села в тени
rus_verbs:заливаться{}, // в нашем парке заливаются соловьи
rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло
rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени
// rus_verbs:расти{}, // дерево, растущее в лесу
rus_verbs:происходить{}, // что происходит в поликлиннике
rus_verbs:спать{}, // кто спит в моей кровати
rus_verbs:мыть{}, // мыть машину в саду
ГЛ_ИНФ(царить), // В воздухе царило безмолвие
ГЛ_ИНФ(мести), // мести в прихожей пол
ГЛ_ИНФ(прятать), // прятать в яме
ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне.
// ГЛ_ИНФ(собраться), // собраться в порту
ГЛ_ИНФ(случиться), // что-то случилось в больнице
ГЛ_ИНФ(зажечься), // в небе зажглись звёзды
ГЛ_ИНФ(купить), // купи молока в магазине
прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
}
// Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
// С локативом:
// собраться в порту
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } }
then return true
}
#endregion Предложный
#region Винительный
// Для глаголов движения с выраженным направлением действия может присоединяться
// предложный паттерн с винительным падежом.
wordentry_set Гл_В_Вин =
{
rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок.
глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе.
глагол:ввергать{},
инфинитив:ввергнуть{},
инфинитив:ввергать{},
rus_verbs:двинуться{}, // Двинулись в путь и мы.
rus_verbs:сплавать{}, // Сплавать в Россию!
rus_verbs:уложиться{}, // Уложиться в воскресенье.
rus_verbs:спешить{}, // Спешите в Лондон
rus_verbs:кинуть{}, // Киньте в море.
rus_verbs:проситься{}, // Просилась в Никарагуа.
rus_verbs:притопать{}, // Притопал в Будапешт.
rus_verbs:скататься{}, // Скатался в Красноярск.
rus_verbs:соскользнуть{}, // Соскользнул в пике.
rus_verbs:соскальзывать{},
rus_verbs:играть{}, // Играл в дутье.
глагол:айда{}, // Айда в каморы.
rus_verbs:отзывать{}, // Отзывали в Москву...
rus_verbs:сообщаться{}, // Сообщается в Лондон.
rus_verbs:вдуматься{}, // Вдумайтесь в них.
rus_verbs:проехать{}, // Проехать в Лунево...
rus_verbs:спрыгивать{}, // Спрыгиваем в него.
rus_verbs:верить{}, // Верю в вас!
rus_verbs:прибыть{}, // Прибыл в Подмосковье.
rus_verbs:переходить{}, // Переходите в школу.
rus_verbs:доложить{}, // Доложили в Москву.
rus_verbs:подаваться{}, // Подаваться в Россию?
rus_verbs:спрыгнуть{}, // Спрыгнул в него.
rus_verbs:вывезти{}, // Вывезли в Китай.
rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю.
rus_verbs:пропихнуть{},
rus_verbs:транспортироваться{},
rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения
rus_verbs:дуть{},
rus_verbs:БОГАТЕТЬ{}, //
rus_verbs:РАЗБОГАТЕТЬ{}, //
rus_verbs:ВОЗРАСТАТЬ{}, //
rus_verbs:ВОЗРАСТИ{}, //
rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ)
rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ)
rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ)
rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ)
rus_verbs:ЗАМАНИВАТЬ{},
rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ)
rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ)
rus_verbs:ВРУБАТЬСЯ{},
rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ)
rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ)
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ)
rus_verbs:ЗАХВАТЫВАТЬ{},
rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ)
rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ)
rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ)
rus_verbs:ПОСТРОИТЬСЯ{},
rus_verbs:ВЫСТРОИТЬСЯ{},
rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ)
rus_verbs:ВЫПУСКАТЬ{},
rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ)
rus_verbs:ВЦЕПИТЬСЯ{},
rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ)
rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ)
rus_verbs:ОТСТУПАТЬ{},
rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ)
rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ)
rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ)
rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ)
rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ)
rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин)
rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ)
rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ)
rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ)
rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ)
rus_verbs:СЖИМАТЬСЯ{},
rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение
rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ)
rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ)
rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ)
rus_verbs:ПОКРАСИТЬ{}, //
rus_verbs:ПЕРЕКРАСИТЬ{}, //
rus_verbs:ОКРАСИТЬ{}, //
rus_verbs:ЗАКРАСИТЬ{}, //
rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ)
rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ)
rus_verbs:СТЯНУТЬ{}, //
rus_verbs:ЗАТЯНУТЬ{}, //
rus_verbs:ВТЯНУТЬ{}, //
rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ)
деепричастие:придя{}, // Немного придя в себя
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ)
rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ)
rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ)
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ)
rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ)
rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку
rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин)
rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин)
rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин)
rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин)
rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин)
rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин)
rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин)
rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В)
rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В)
rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В)
rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В)
rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин)
rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В)
rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В)
rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин)
rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В)
rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В)
rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В)
rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В)
rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В)
rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В)
rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В)
rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В)
rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В)
rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны.
rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В)
rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям.
rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В)
rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в)
rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В)
rus_verbs:валить{}, // валить все в одну кучу (валить в)
rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в)
rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в)
rus_verbs:клониться{}, // он клонился в сторону (клониться в)
rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в)
rus_verbs:запасть{}, // Эти слова запали мне в душу.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:ездить{}, // Каждый день грузовик ездит в город.
rus_verbs:претвориться{}, // Замысел претворился в жизнь.
rus_verbs:разойтись{}, // Они разошлись в разные стороны.
rus_verbs:выйти{}, // Охотник вышел в поле с ружьём.
rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом.
rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны
rus_verbs:переодеваться{}, // переодеваться в женское платье
rus_verbs:перерастать{}, // перерастать в массовые беспорядки
rus_verbs:завязываться{}, // завязываться в узел
rus_verbs:похватать{}, // похватать в руки
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:помещать{}, // помещать в изолятор
rus_verbs:зыркнуть{}, // зыркнуть в окошко
rus_verbs:закатать{}, // закатать в асфальт
rus_verbs:усаживаться{}, // усаживаться в кресло
rus_verbs:загонять{}, // загонять в сарай
rus_verbs:подбрасывать{}, // подбрасывать в воздух
rus_verbs:телеграфировать{}, // телеграфировать в центр
rus_verbs:вязать{}, // вязать в стопы
rus_verbs:подлить{}, // подлить в огонь
rus_verbs:заполучить{}, // заполучить в распоряжение
rus_verbs:подогнать{}, // подогнать в док
rus_verbs:ломиться{}, // ломиться в открытую дверь
rus_verbs:переправить{}, // переправить в деревню
rus_verbs:затягиваться{}, // затягиваться в трубу
rus_verbs:разлетаться{}, // разлетаться в стороны
rus_verbs:кланяться{}, // кланяться в ножки
rus_verbs:устремляться{}, // устремляться в открытое море
rus_verbs:переместиться{}, // переместиться в другую аудиторию
rus_verbs:ложить{}, // ложить в ящик
rus_verbs:отвозить{}, // отвозить в аэропорт
rus_verbs:напрашиваться{}, // напрашиваться в гости
rus_verbs:напроситься{}, // напроситься в гости
rus_verbs:нагрянуть{}, // нагрянуть в гости
rus_verbs:заворачивать{}, // заворачивать в фольгу
rus_verbs:заковать{}, // заковать в кандалы
rus_verbs:свезти{}, // свезти в сарай
rus_verbs:притащиться{}, // притащиться в дом
rus_verbs:завербовать{}, // завербовать в разведку
rus_verbs:рубиться{}, // рубиться в компьютерные игры
rus_verbs:тыкаться{}, // тыкаться в материнскую грудь
инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер
глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш },
деепричастие:ссыпав{}, деепричастие:ссыпая{},
rus_verbs:засасывать{}, // засасывать в себя
rus_verbs:скакнуть{}, // скакнуть в будущее
rus_verbs:подвозить{}, // подвозить в театр
rus_verbs:переиграть{}, // переиграть в покер
rus_verbs:мобилизовать{}, // мобилизовать в действующую армию
rus_verbs:залетать{}, // залетать в закрытое воздушное пространство
rus_verbs:подышать{}, // подышать в трубочку
rus_verbs:смотаться{}, // смотаться в институт
rus_verbs:рассовать{}, // рассовать в кармашки
rus_verbs:захаживать{}, // захаживать в дом
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард
деепричастие:сгоняя{},
rus_verbs:посылаться{}, // посылаться в порт
rus_verbs:отлить{}, // отлить в кастрюлю
rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение
rus_verbs:поплакать{}, // поплакать в платочек
rus_verbs:обуться{}, // обуться в сапоги
rus_verbs:закапать{}, // закапать в глаза
инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации
глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш },
деепричастие:свозив{}, деепричастие:свозя{},
rus_verbs:преобразовать{}, // преобразовать в линейное уравнение
rus_verbs:кутаться{}, // кутаться в плед
rus_verbs:смещаться{}, // смещаться в сторону
rus_verbs:зазывать{}, // зазывать в свой магазин
инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон
глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш },
деепричастие:трансформируясь{}, деепричастие:трансформировавшись{},
rus_verbs:погружать{}, // погружать в кипящее масло
rus_verbs:обыграть{}, // обыграть в теннис
rus_verbs:закутать{}, // закутать в одеяло
rus_verbs:изливаться{}, // изливаться в воду
rus_verbs:закатывать{}, // закатывать в асфальт
rus_verbs:мотнуться{}, // мотнуться в банк
rus_verbs:избираться{}, // избираться в сенат
rus_verbs:наниматься{}, // наниматься в услужение
rus_verbs:настучать{}, // настучать в органы
rus_verbs:запихивать{}, // запихивать в печку
rus_verbs:закапывать{}, // закапывать в нос
rus_verbs:засобираться{}, // засобираться в поход
rus_verbs:копировать{}, // копировать в другую папку
rus_verbs:замуровать{}, // замуровать в стену
rus_verbs:упечь{}, // упечь в тюрьму
rus_verbs:зрить{}, // зрить в корень
rus_verbs:стягиваться{}, // стягиваться в одну точку
rus_verbs:усаживать{}, // усаживать в тренажер
rus_verbs:протолкнуть{}, // протолкнуть в отверстие
rus_verbs:расшибиться{}, // расшибиться в лепешку
rus_verbs:приглашаться{}, // приглашаться в кабинет
rus_verbs:садить{}, // садить в телегу
rus_verbs:уткнуть{}, // уткнуть в подушку
rus_verbs:протечь{}, // протечь в подвал
rus_verbs:перегнать{}, // перегнать в другую страну
rus_verbs:переползти{}, // переползти в тень
rus_verbs:зарываться{}, // зарываться в грунт
rus_verbs:переодеть{}, // переодеть в сухую одежду
rus_verbs:припуститься{}, // припуститься в пляс
rus_verbs:лопотать{}, // лопотать в микрофон
rus_verbs:прогнусавить{}, // прогнусавить в микрофон
rus_verbs:мочиться{}, // мочиться в штаны
rus_verbs:загружать{}, // загружать в патронник
rus_verbs:радировать{}, // радировать в центр
rus_verbs:промотать{}, // промотать в конец
rus_verbs:помчать{}, // помчать в школу
rus_verbs:съезжать{}, // съезжать в кювет
rus_verbs:завозить{}, // завозить в магазин
rus_verbs:заявляться{}, // заявляться в школу
rus_verbs:наглядеться{}, // наглядеться в зеркало
rus_verbs:сворачиваться{}, // сворачиваться в клубочек
rus_verbs:устремлять{}, // устремлять взор в будущее
rus_verbs:забредать{}, // забредать в глухие уголки
rus_verbs:перемотать{}, // перемотать в самое начало диалога
rus_verbs:сморкаться{}, // сморкаться в носовой платочек
rus_verbs:перетекать{}, // перетекать в другой сосуд
rus_verbs:закачать{}, // закачать в шарик
rus_verbs:запрятать{}, // запрятать в сейф
rus_verbs:пинать{}, // пинать в живот
rus_verbs:затрубить{}, // затрубить в горн
rus_verbs:подглядывать{}, // подглядывать в замочную скважину
инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье
глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш },
деепричастие:подсыпав{}, деепричастие:подсыпая{},
rus_verbs:засовывать{}, // засовывать в пенал
rus_verbs:отрядить{}, // отрядить в командировку
rus_verbs:справлять{}, // справлять в кусты
rus_verbs:поторапливаться{}, // поторапливаться в самолет
rus_verbs:скопировать{}, // скопировать в кэш
rus_verbs:подливать{}, // подливать в огонь
rus_verbs:запрячь{}, // запрячь в повозку
rus_verbs:окраситься{}, // окраситься в пурпур
rus_verbs:уколоть{}, // уколоть в шею
rus_verbs:слететься{}, // слететься в гнездо
rus_verbs:резаться{}, // резаться в карты
rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров
инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш)
деепричастие:задвигая{},
rus_verbs:доставляться{}, // доставляться в ресторан
rus_verbs:поплевать{}, // поплевать в чашку
rus_verbs:попереться{}, // попереться в магазин
rus_verbs:хаживать{}, // хаживать в церковь
rus_verbs:преображаться{}, // преображаться в королеву
rus_verbs:организоваться{}, // организоваться в группу
rus_verbs:ужалить{}, // ужалить в руку
rus_verbs:протискиваться{}, // протискиваться в аудиторию
rus_verbs:препроводить{}, // препроводить в закуток
rus_verbs:разъезжаться{}, // разъезжаться в разные стороны
rus_verbs:пропыхтеть{}, // пропыхтеть в трубку
rus_verbs:уволочь{}, // уволочь в нору
rus_verbs:отодвигаться{}, // отодвигаться в сторону
rus_verbs:разливать{}, // разливать в стаканы
rus_verbs:сбегаться{}, // сбегаться в актовый зал
rus_verbs:наведаться{}, // наведаться в кладовку
rus_verbs:перекочевать{}, // перекочевать в горы
rus_verbs:прощебетать{}, // прощебетать в трубку
rus_verbs:перекладывать{}, // перекладывать в другой карман
rus_verbs:углубляться{}, // углубляться в теорию
rus_verbs:переименовать{}, // переименовать в город
rus_verbs:переметнуться{}, // переметнуться в лагерь противника
rus_verbs:разносить{}, // разносить в щепки
rus_verbs:осыпаться{}, // осыпаться в холода
rus_verbs:попроситься{}, // попроситься в туалет
rus_verbs:уязвить{}, // уязвить в сердце
rus_verbs:перетащить{}, // перетащить в дом
rus_verbs:закутаться{}, // закутаться в плед
// rus_verbs:упаковать{}, // упаковать в бумагу
инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость
rus_verbs:хихикать{}, // хихикать в кулачок
rus_verbs:объединить{}, // объединить в сеть
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию
деепричастие:слетав{},
rus_verbs:заползти{}, // заползти в норку
rus_verbs:перерасти{}, // перерасти в крупную аферу
rus_verbs:списать{}, // списать в утиль
rus_verbs:просачиваться{}, // просачиваться в бункер
rus_verbs:пускаться{}, // пускаться в погоню
rus_verbs:согревать{}, // согревать в мороз
rus_verbs:наливаться{}, // наливаться в емкость
rus_verbs:унестись{}, // унестись в небо
rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф
rus_verbs:сигануть{}, // сигануть в воду
rus_verbs:окунуть{}, // окунуть в ледяную воду
rus_verbs:просочиться{}, // просочиться в сапог
rus_verbs:соваться{}, // соваться в толпу
rus_verbs:протолкаться{}, // протолкаться в гардероб
rus_verbs:заложить{}, // заложить в ломбард
rus_verbs:перекатить{}, // перекатить в сарай
rus_verbs:поставлять{}, // поставлять в Китай
rus_verbs:залезать{}, // залезать в долги
rus_verbs:отлучаться{}, // отлучаться в туалет
rus_verbs:сбиваться{}, // сбиваться в кучу
rus_verbs:зарыть{}, // зарыть в землю
rus_verbs:засадить{}, // засадить в тело
rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь
rus_verbs:переставить{}, // переставить в шкаф
rus_verbs:отчалить{}, // отчалить в плавание
rus_verbs:набираться{}, // набираться в команду
rus_verbs:лягнуть{}, // лягнуть в живот
rus_verbs:притворить{}, // притворить в жизнь
rus_verbs:проковылять{}, // проковылять в гардероб
rus_verbs:прикатить{}, // прикатить в гараж
rus_verbs:залететь{}, // залететь в окно
rus_verbs:переделать{}, // переделать в мопед
rus_verbs:протащить{}, // протащить в совет
rus_verbs:обмакнуть{}, // обмакнуть в воду
rus_verbs:отклоняться{}, // отклоняться в сторону
rus_verbs:запихать{}, // запихать в пакет
rus_verbs:избирать{}, // избирать в совет
rus_verbs:загрузить{}, // загрузить в буфер
rus_verbs:уплывать{}, // уплывать в Париж
rus_verbs:забивать{}, // забивать в мерзлоту
rus_verbs:потыкать{}, // потыкать в безжизненную тушу
rus_verbs:съезжаться{}, // съезжаться в санаторий
rus_verbs:залепить{}, // залепить в рыло
rus_verbs:набиться{}, // набиться в карманы
rus_verbs:уползти{}, // уползти в нору
rus_verbs:упрятать{}, // упрятать в камеру
rus_verbs:переместить{}, // переместить в камеру анабиоза
rus_verbs:закрасться{}, // закрасться в душу
rus_verbs:сместиться{}, // сместиться в инфракрасную область
rus_verbs:запускать{}, // запускать в серию
rus_verbs:потрусить{}, // потрусить в чащобу
rus_verbs:забрасывать{}, // забрасывать в чистую воду
rus_verbs:переселить{}, // переселить в отдаленную деревню
rus_verbs:переезжать{}, // переезжать в новую квартиру
rus_verbs:приподнимать{}, // приподнимать в воздух
rus_verbs:добавиться{}, // добавиться в конец очереди
rus_verbs:убыть{}, // убыть в часть
rus_verbs:передвигать{}, // передвигать в соседнюю клетку
rus_verbs:добавляться{}, // добавляться в очередь
rus_verbs:дописать{}, // дописать в перечень
rus_verbs:записываться{}, // записываться в кружок
rus_verbs:продаться{}, // продаться в кредитное рабство
rus_verbs:переписывать{}, // переписывать в тетрадку
rus_verbs:заплыть{}, // заплыть в территориальные воды
инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок
глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" },
rus_verbs:отбирать{}, // отбирать в гвардию
rus_verbs:нашептывать{}, // нашептывать в микрофон
rus_verbs:ковылять{}, // ковылять в стойло
rus_verbs:прилетать{}, // прилетать в Париж
rus_verbs:пролиться{}, // пролиться в канализацию
rus_verbs:запищать{}, // запищать в микрофон
rus_verbs:подвезти{}, // подвезти в больницу
rus_verbs:припереться{}, // припереться в театр
rus_verbs:утечь{}, // утечь в сеть
rus_verbs:прорываться{}, // прорываться в буфет
rus_verbs:увозить{}, // увозить в ремонт
rus_verbs:съедать{}, // съедать в обед
rus_verbs:просунуться{}, // просунуться в дверь
rus_verbs:перенестись{}, // перенестись в прошлое
rus_verbs:завезти{}, // завезти в магазин
rus_verbs:проложить{}, // проложить в деревню
rus_verbs:объединяться{}, // объединяться в профсоюз
rus_verbs:развиться{}, // развиться в бабочку
rus_verbs:засеменить{}, // засеменить в кабинку
rus_verbs:скатываться{}, // скатываться в яму
rus_verbs:завозиться{}, // завозиться в магазин
rus_verbs:нанимать{}, // нанимать в рейс
rus_verbs:поспеть{}, // поспеть в класс
rus_verbs:кидаться{}, // кинаться в крайности
rus_verbs:поспевать{}, // поспевать в оперу
rus_verbs:обернуть{}, // обернуть в фольгу
rus_verbs:обратиться{}, // обратиться в прокуратуру
rus_verbs:истолковать{}, // истолковать в свою пользу
rus_verbs:таращиться{}, // таращиться в дисплей
rus_verbs:прыснуть{}, // прыснуть в кулачок
rus_verbs:загнуть{}, // загнуть в другую сторону
rus_verbs:раздать{}, // раздать в разные руки
rus_verbs:назначить{}, // назначить в приемную комиссию
rus_verbs:кидать{}, // кидать в кусты
rus_verbs:увлекать{}, // увлекать в лес
rus_verbs:переселиться{}, // переселиться в чужое тело
rus_verbs:присылать{}, // присылать в город
rus_verbs:уплыть{}, // уплыть в Европу
rus_verbs:запричитать{}, // запричитать в полный голос
rus_verbs:утащить{}, // утащить в логово
rus_verbs:завернуться{}, // завернуться в плед
rus_verbs:заносить{}, // заносить в блокнот
rus_verbs:пятиться{}, // пятиться в дом
rus_verbs:наведываться{}, // наведываться в больницу
rus_verbs:нырять{}, // нырять в прорубь
rus_verbs:зачастить{}, // зачастить в бар
rus_verbs:назначаться{}, // назначается в комиссию
rus_verbs:мотаться{}, // мотаться в областной центр
rus_verbs:разыграть{}, // разыграть в карты
rus_verbs:пропищать{}, // пропищать в микрофон
rus_verbs:пихнуть{}, // пихнуть в бок
rus_verbs:эмигрировать{}, // эмигрировать в Канаду
rus_verbs:подключить{}, // подключить в сеть
rus_verbs:упереть{}, // упереть в фундамент
rus_verbs:уплатить{}, // уплатить в кассу
rus_verbs:потащиться{}, // потащиться в медпункт
rus_verbs:пригнать{}, // пригнать в стойло
rus_verbs:оттеснить{}, // оттеснить в фойе
rus_verbs:стучаться{}, // стучаться в ворота
rus_verbs:перечислить{}, // перечислить в фонд
rus_verbs:сомкнуть{}, // сомкнуть в круг
rus_verbs:закачаться{}, // закачаться в резервуар
rus_verbs:кольнуть{}, // кольнуть в бок
rus_verbs:накрениться{}, // накрениться в сторону берега
rus_verbs:подвинуться{}, // подвинуться в другую сторону
rus_verbs:разнести{}, // разнести в клочья
rus_verbs:отливать{}, // отливать в форму
rus_verbs:подкинуть{}, // подкинуть в карман
rus_verbs:уводить{}, // уводить в кабинет
rus_verbs:ускакать{}, // ускакать в школу
rus_verbs:ударять{}, // ударять в барабаны
rus_verbs:даться{}, // даться в руки
rus_verbs:поцеловаться{}, // поцеловаться в губы
rus_verbs:посветить{}, // посветить в подвал
rus_verbs:тыкать{}, // тыкать в арбуз
rus_verbs:соединяться{}, // соединяться в кольцо
rus_verbs:растянуть{}, // растянуть в тонкую ниточку
rus_verbs:побросать{}, // побросать в пыль
rus_verbs:стукнуться{}, // стукнуться в закрытую дверь
rus_verbs:проигрывать{}, // проигрывать в теннис
rus_verbs:дунуть{}, // дунуть в трубочку
rus_verbs:улетать{}, // улетать в Париж
rus_verbs:переводиться{}, // переводиться в филиал
rus_verbs:окунуться{}, // окунуться в водоворот событий
rus_verbs:попрятаться{}, // попрятаться в норы
rus_verbs:перевезти{}, // перевезти в соседнюю палату
rus_verbs:топать{}, // топать в школу
rus_verbs:относить{}, // относить в помещение
rus_verbs:укладывать{}, // укладывать в стопку
rus_verbs:укатить{}, // укатил в турне
rus_verbs:убирать{}, // убирать в сумку
rus_verbs:помалкивать{}, // помалкивать в тряпочку
rus_verbs:ронять{}, // ронять в грязь
rus_verbs:глазеть{}, // глазеть в бинокль
rus_verbs:преобразиться{}, // преобразиться в другого человека
rus_verbs:запрыгнуть{}, // запрыгнуть в поезд
rus_verbs:сгодиться{}, // сгодиться в суп
rus_verbs:проползти{}, // проползти в нору
rus_verbs:забираться{}, // забираться в коляску
rus_verbs:сбежаться{}, // сбежались в класс
rus_verbs:закатиться{}, // закатиться в угол
rus_verbs:плевать{}, // плевать в душу
rus_verbs:поиграть{}, // поиграть в демократию
rus_verbs:кануть{}, // кануть в небытие
rus_verbs:опаздывать{}, // опаздывать в школу
rus_verbs:отползти{}, // отползти в сторону
rus_verbs:стекаться{}, // стекаться в отстойник
rus_verbs:запихнуть{}, // запихнуть в пакет
rus_verbs:вышвырнуть{}, // вышвырнуть в коридор
rus_verbs:связываться{}, // связываться в плотный узел
rus_verbs:затолкать{}, // затолкать в ухо
rus_verbs:скрутить{}, // скрутить в трубочку
rus_verbs:сворачивать{}, // сворачивать в трубочку
rus_verbs:сплестись{}, // сплестись в узел
rus_verbs:заскочить{}, // заскочить в кабинет
rus_verbs:проваливаться{}, // проваливаться в сон
rus_verbs:уверовать{}, // уверовать в свою безнаказанность
rus_verbs:переписать{}, // переписать в тетрадку
rus_verbs:переноситься{}, // переноситься в мир фантазий
rus_verbs:заводить{}, // заводить в помещение
rus_verbs:сунуться{}, // сунуться в аудиторию
rus_verbs:устраиваться{}, // устраиваться в автомастерскую
rus_verbs:пропускать{}, // пропускать в зал
инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино
глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш },
деепричастие:сбегая{}, деепричастие:сбегав{},
rus_verbs:прибегать{}, // прибегать в школу
rus_verbs:съездить{}, // съездить в лес
rus_verbs:захлопать{}, // захлопать в ладошки
rus_verbs:опрокинуться{}, // опрокинуться в грязь
инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан
глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш },
деепричастие:насыпая{}, деепричастие:насыпав{},
rus_verbs:употреблять{}, // употреблять в пищу
rus_verbs:приводиться{}, // приводиться в действие
rus_verbs:пристроить{}, // пристроить в надежные руки
rus_verbs:юркнуть{}, // юркнуть в нору
rus_verbs:объединиться{}, // объединиться в банду
rus_verbs:сажать{}, // сажать в одиночку
rus_verbs:соединить{}, // соединить в кольцо
rus_verbs:забрести{}, // забрести в кафешку
rus_verbs:свернуться{}, // свернуться в клубочек
rus_verbs:пересесть{}, // пересесть в другой автобус
rus_verbs:постучаться{}, // постучаться в дверцу
rus_verbs:соединять{}, // соединять в кольцо
rus_verbs:приволочь{}, // приволочь в коморку
rus_verbs:смахивать{}, // смахивать в ящик стола
rus_verbs:забежать{}, // забежать в помещение
rus_verbs:целиться{}, // целиться в беглеца
rus_verbs:прокрасться{}, // прокрасться в хранилище
rus_verbs:заковылять{}, // заковылять в травтамологию
rus_verbs:прискакать{}, // прискакать в стойло
rus_verbs:колотить{}, // колотить в дверь
rus_verbs:смотреться{}, // смотреться в зеркало
rus_verbs:подложить{}, // подложить в салон
rus_verbs:пущать{}, // пущать в королевские покои
rus_verbs:согнуть{}, // согнуть в дугу
rus_verbs:забарабанить{}, // забарабанить в дверь
rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы
rus_verbs:убраться{}, // убраться в специальную нишу
rus_verbs:насмотреться{}, // насмотреться в зеркало
rus_verbs:чмокнуть{}, // чмокнуть в щечку
rus_verbs:усмехаться{}, // усмехаться в бороду
rus_verbs:передвинуть{}, // передвинуть в конец очереди
rus_verbs:допускаться{}, // допускаться в опочивальню
rus_verbs:задвинуть{}, // задвинуть в дальний угол
rus_verbs:отправлять{}, // отправлять в центр
rus_verbs:сбрасывать{}, // сбрасывать в жерло
rus_verbs:расстреливать{}, // расстреливать в момент обнаружения
rus_verbs:заволочь{}, // заволочь в закуток
rus_verbs:пролить{}, // пролить в воду
rus_verbs:зарыться{}, // зарыться в сено
rus_verbs:переливаться{}, // переливаться в емкость
rus_verbs:затащить{}, // затащить в клуб
rus_verbs:перебежать{}, // перебежать в лагерь врагов
rus_verbs:одеть{}, // одеть в новое платье
инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу
деепричастие:задвигаясь{},
rus_verbs:клюнуть{}, // клюнуть в темечко
rus_verbs:наливать{}, // наливать в кружку
rus_verbs:пролезть{}, // пролезть в ушко
rus_verbs:откладывать{}, // откладывать в ящик
rus_verbs:протянуться{}, // протянуться в соседний дом
rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь
rus_verbs:устанавливать{}, // устанавливать в машину
rus_verbs:употребляться{}, // употребляться в пищу
rus_verbs:переключиться{}, // переключиться в реверсный режим
rus_verbs:пискнуть{}, // пискнуть в микрофон
rus_verbs:заявиться{}, // заявиться в класс
rus_verbs:налиться{}, // налиться в стакан
rus_verbs:заливать{}, // заливать в бак
rus_verbs:ставиться{}, // ставиться в очередь
инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны
деепричастие:писаясь{},
rus_verbs:целоваться{}, // целоваться в губы
rus_verbs:наносить{}, // наносить в область сердца
rus_verbs:посмеяться{}, // посмеяться в кулачок
rus_verbs:употребить{}, // употребить в пищу
rus_verbs:прорваться{}, // прорваться в столовую
rus_verbs:укладываться{}, // укладываться в ровные стопки
rus_verbs:пробиться{}, // пробиться в финал
rus_verbs:забить{}, // забить в землю
rus_verbs:переложить{}, // переложить в другой карман
rus_verbs:опускать{}, // опускать в свежевырытую могилу
rus_verbs:поторопиться{}, // поторопиться в школу
rus_verbs:сдвинуться{}, // сдвинуться в сторону
rus_verbs:капать{}, // капать в смесь
rus_verbs:погружаться{}, // погружаться во тьму
rus_verbs:направлять{}, // направлять в кабинку
rus_verbs:погрузить{}, // погрузить во тьму
rus_verbs:примчаться{}, // примчаться в школу
rus_verbs:упираться{}, // упираться в дверь
rus_verbs:удаляться{}, // удаляться в комнату совещаний
rus_verbs:ткнуться{}, // ткнуться в окошко
rus_verbs:убегать{}, // убегать в чащу
rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру
rus_verbs:наговорить{}, // наговорить в микрофон
rus_verbs:переносить{}, // переносить в дом
rus_verbs:прилечь{}, // прилечь в кроватку
rus_verbs:поворачивать{}, // поворачивать в обратную сторону
rus_verbs:проскочить{}, // проскочить в щель
rus_verbs:совать{}, // совать в духовку
rus_verbs:переодеться{}, // переодеться в чистую одежду
rus_verbs:порвать{}, // порвать в лоскуты
rus_verbs:завязать{}, // завязать в бараний рог
rus_verbs:съехать{}, // съехать в кювет
rus_verbs:литься{}, // литься в канистру
rus_verbs:уклониться{}, // уклониться в левую сторону
rus_verbs:смахнуть{}, // смахнуть в мусорное ведро
rus_verbs:спускать{}, // спускать в шахту
rus_verbs:плеснуть{}, // плеснуть в воду
rus_verbs:подуть{}, // подуть в угольки
rus_verbs:набирать{}, // набирать в команду
rus_verbs:хлопать{}, // хлопать в ладошки
rus_verbs:ранить{}, // ранить в самое сердце
rus_verbs:посматривать{}, // посматривать в иллюминатор
rus_verbs:превращать{}, // превращать воду в вино
rus_verbs:толкать{}, // толкать в пучину
rus_verbs:отбыть{}, // отбыть в расположение части
rus_verbs:сгрести{}, // сгрести в карман
rus_verbs:удрать{}, // удрать в тайгу
rus_verbs:пристроиться{}, // пристроиться в хорошую фирму
rus_verbs:сбиться{}, // сбиться в плотную группу
rus_verbs:заключать{}, // заключать в объятия
rus_verbs:отпускать{}, // отпускать в поход
rus_verbs:устремить{}, // устремить взгляд в будущее
rus_verbs:обронить{}, // обронить в траву
rus_verbs:сливаться{}, // сливаться в речку
rus_verbs:стекать{}, // стекать в канаву
rus_verbs:свалить{}, // свалить в кучу
rus_verbs:подтянуть{}, // подтянуть в кабину
rus_verbs:скатиться{}, // скатиться в канаву
rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь
rus_verbs:заторопиться{}, // заторопиться в буфет
rus_verbs:протиснуться{}, // протиснуться в центр толпы
rus_verbs:прятать{}, // прятать в укромненькое местечко
rus_verbs:пропеть{}, // пропеть в микрофон
rus_verbs:углубиться{}, // углубиться в джунгли
rus_verbs:сползти{}, // сползти в яму
rus_verbs:записывать{}, // записывать в память
rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР)
rus_verbs:колотиться{}, // колотиться в дверь
rus_verbs:просунуть{}, // просунуть в отверстие
rus_verbs:провожать{}, // провожать в армию
rus_verbs:катить{}, // катить в гараж
rus_verbs:поражать{}, // поражать в самое сердце
rus_verbs:отлететь{}, // отлететь в дальний угол
rus_verbs:закинуть{}, // закинуть в речку
rus_verbs:катиться{}, // катиться в пропасть
rus_verbs:забросить{}, // забросить в дальний угол
rus_verbs:отвезти{}, // отвезти в лагерь
rus_verbs:втопить{}, // втопить педаль в пол
rus_verbs:втапливать{}, // втапливать педать в пол
rus_verbs:утопить{}, // утопить кнопку в панель
rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США
rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?)
rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег
rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег
rus_verbs:поскакать{}, // поскакать в атаку
rus_verbs:прицелиться{}, // прицелиться в бегущего зайца
rus_verbs:прыгать{}, // прыгать в кровать
rus_verbs:приглашать{}, // приглашать в дом
rus_verbs:понестись{}, // понестись в ворота
rus_verbs:заехать{}, // заехать в гаражный бокс
rus_verbs:опускаться{}, // опускаться в бездну
rus_verbs:переехать{}, // переехать в коттедж
rus_verbs:поместить{}, // поместить в карантин
rus_verbs:ползти{}, // ползти в нору
rus_verbs:добавлять{}, // добавлять в корзину
rus_verbs:уткнуться{}, // уткнуться в подушку
rus_verbs:продавать{}, // продавать в рабство
rus_verbs:спрятаться{}, // Белка спрячется в дупло.
rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию
rus_verbs:воткнуть{}, // воткни вилку в розетку
rus_verbs:нести{}, // нести в больницу
rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку
rus_verbs:впаивать{}, // впаивать деталь в плату
rus_verbs:впаиваться{}, // деталь впаивается в плату
rus_verbs:впархивать{}, // впархивать в помещение
rus_verbs:впаять{}, // впаять деталь в плату
rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат
rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат
rus_verbs:вперивать{}, // вперивать взгляд в экран
rus_verbs:впериваться{}, // впериваться в экран
rus_verbs:вперить{}, // вперить взгляд в экран
rus_verbs:впериться{}, // впериться в экран
rus_verbs:вперять{}, // вперять взгляд в экран
rus_verbs:вперяться{}, // вперяться в экран
rus_verbs:впечатать{}, // впечатать текст в первую главу
rus_verbs:впечататься{}, // впечататься в стену
rus_verbs:впечатывать{}, // впечатывать текст в первую главу
rus_verbs:впечатываться{}, // впечатываться в стену
rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами
rus_verbs:впитаться{}, // Жидкость впиталась в ткань
rus_verbs:впитываться{}, // Жидкость впитывается в ткань
rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы
rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку
rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник
rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник
rus_verbs:вплавиться{}, // Провод вплавился в плату
rus_verbs:вплеснуть{}, // вплеснуть краситель в бак
rus_verbs:вплести{}, // вплести ленту в волосы
rus_verbs:вплестись{}, // вплестись в волосы
rus_verbs:вплетать{}, // вплетать ленты в волосы
rus_verbs:вплывать{}, // корабль вплывает в порт
rus_verbs:вплыть{}, // яхта вплыла в бухту
rus_verbs:вползать{}, // дракон вползает в пещеру
rus_verbs:вползти{}, // дракон вполз в свою пещеру
rus_verbs:впорхнуть{}, // бабочка впорхнула в окно
rus_verbs:впрессовать{}, // впрессовать деталь в плиту
rus_verbs:впрессоваться{}, // впрессоваться в плиту
rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту
rus_verbs:впрессовываться{}, // впрессовываться в плиту
rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон
rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон
rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр
rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр
rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания
rus_verbs:впрягать{}, // впрягать лошадь в телегу
rus_verbs:впрягаться{}, // впрягаться в работу
rus_verbs:впрячь{}, // впрячь лошадь в телегу
rus_verbs:впрячься{}, // впрячься в работу
rus_verbs:впускать{}, // впускать посетителей в музей
rus_verbs:впускаться{}, // впускаться в помещение
rus_verbs:впустить{}, // впустить посетителей в музей
rus_verbs:впутать{}, // впутать кого-то во что-то
rus_verbs:впутаться{}, // впутаться во что-то
rus_verbs:впутывать{}, // впутывать кого-то во что-то
rus_verbs:впутываться{}, // впутываться во что-то
rus_verbs:врабатываться{}, // врабатываться в режим
rus_verbs:вработаться{}, // вработаться в режим
rus_verbs:врастать{}, // врастать в кожу
rus_verbs:врасти{}, // врасти в кожу
инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь
инфинитив:врезать{ вид:соверш },
глагол:врезать{ вид:несоверш },
глагол:врезать{ вид:соверш },
деепричастие:врезая{},
деепричастие:врезав{},
прилагательное:врезанный{},
инфинитив:врезаться{ вид:несоверш }, // врезаться в стену
инфинитив:врезаться{ вид:соверш },
глагол:врезаться{ вид:несоверш },
деепричастие:врезаясь{},
деепричастие:врезавшись{},
rus_verbs:врубить{}, // врубить в нагрузку
rus_verbs:врываться{}, // врываться в здание
rus_verbs:закачивать{}, // Насос закачивает топливо в бак
rus_verbs:ввезти{}, // Предприятие ввезло товар в страну
rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу
rus_verbs:ввивать{}, // Женщина ввивает полоску в косу
rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу
rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко
rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко
rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека
rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека
rus_verbs:вламываться{}, // Полиция вламывается в квартиру
rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом
rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом
rus_verbs:вовлечься{}, // вовлечься в занятие спортом
rus_verbs:спуститься{}, // спуститься в подвал
rus_verbs:спускаться{}, // спускаться в подвал
rus_verbs:отправляться{}, // отправляться в дальнее плавание
инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство
инфинитив:эмитировать{ вид:несоверш },
глагол:эмитировать{ вид:соверш },
глагол:эмитировать{ вид:несоверш },
деепричастие:эмитируя{},
деепричастие:эмитировав{},
прилагательное:эмитировавший{ вид:несоверш },
// прилагательное:эмитировавший{ вид:соверш },
прилагательное:эмитирующий{},
прилагательное:эмитируемый{},
прилагательное:эмитированный{},
инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию
инфинитив:этапировать{вид:соверш},
глагол:этапировать{вид:несоверш},
глагол:этапировать{вид:соверш},
деепричастие:этапируя{},
прилагательное:этапируемый{},
прилагательное:этапированный{},
rus_verbs:этапироваться{}, // Преступники этапируются в колонию
rus_verbs:баллотироваться{}, // они баллотировались в жюри
rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну
rus_verbs:бросать{}, // Они бросали в фонтан медные монетки
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:бросить{}, // Он бросил в фонтан медную монетку
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя
rus_verbs:буксировать{}, // Буксир буксирует танкер в порт
rus_verbs:буксироваться{}, // Сухогруз буксируется в порт
rus_verbs:вбегать{}, // Курьер вбегает в дверь
rus_verbs:вбежать{}, // Курьер вбежал в дверь
rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол
rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту
rus_verbs:вбиваться{}, // Штырь вбивается в плиту
rus_verbs:вбирать{}, // Вата вбирает в себя влагу
rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь
rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру
rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру
rus_verbs:вбросить{}, // Судья вбросил мяч в игру
rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон
rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон
rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект
rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача
rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру
rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта
rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту
rus_verbs:ввариваться{}, // Арматура вваривается в плиту
rus_verbs:вварить{}, // Робот вварил арматурину в плиту
rus_verbs:влезть{}, // Предприятие ввезло товар в страну
rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру
rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон
rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон
rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон
rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача
rus_verbs:вверяться{}, // Пациент вверяется в руки врача
rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров
rus_verbs:ввиваться{}, // полоска ввивается в косу
rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево
rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево
rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену
rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену
rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров
rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров
// rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье
rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну
rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон
rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон
rus_verbs:ввязаться{}, // Разведрота ввязалась в бой
rus_verbs:ввязываться{}, // Передовые части ввязываются в бой
rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор
rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор
rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию
rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида
rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида
rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали
rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку
rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку
rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь
rus_verbs:вдвинуться{}, // деталь вдвинулась в печь
rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку
rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко
rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко
rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко
rus_verbs:вделать{}, // мастер вделал розетку в стену
rus_verbs:вделывать{}, // мастер вделывает выключатель в стену
rus_verbs:вделываться{}, // кронштейн вделывается в стену
rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко
rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко
rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век
rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов
rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог
rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие
rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку
rus_verbs:вернуться{}, // Дети вернулись в библиотеку
rus_verbs:вжаться{}, // Водитель вжался в кресло
rus_verbs:вживаться{}, // Актер вживается в новую роль
rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента
rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента
rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента
rus_verbs:вживляться{}, // Стимулятор вживляется в тело
rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло
rus_verbs:вжиться{}, // Актер вжился в свою новую роль
rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо
rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо
rus_verbs:взвинтиться{}, // Цены взвинтились в небо
rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо
rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо
rus_verbs:взвиться{}, // Шарики взвились в небо
rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух
rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо
rus_verbs:взмывать{}, // шарики взмывают в небо
rus_verbs:взмыть{}, // Шарики взмыли в небо
rus_verbs:вильнуть{}, // Машина вильнула в левую сторону
rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену
rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену
rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю
rus_verbs:вкапываться{}, // Свая вкапывается в землю
rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж
rus_verbs:вкатиться{}, // машина вкатилась в гараж
rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж
rus_verbs:вкатываться{}, // машина вкатывается в гараж
rus_verbs:вкачать{}, // Механики вкачали в бак много топлива
rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак
rus_verbs:вкачиваться{}, // Топливо вкачивается в бак
rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер
rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер
rus_verbs:вкидываться{}, // Груз вкидывается в контейнер
rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции
rus_verbs:вкладываться{}, // Инвестор вкладывается в акции
rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь
rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь
rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь
rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь
rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист
rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист
rus_verbs:вклиниваться{}, // Машина вклинивается в поток
rus_verbs:вклиниться{}, // машина вклинилась в поток
rus_verbs:включать{}, // Команда включает компьютер в сеть
rus_verbs:включаться{}, // Машина включается в глобальную сеть
rus_verbs:включить{}, // Команда включила компьютер в сеть
rus_verbs:включиться{}, // Компьютер включился в сеть
rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску
rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску
rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску
rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство
rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю
rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты
rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку
rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку
rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты
rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон
rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон
rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон
rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон
rus_verbs:влазить{}, // Разъем влазит в отверствие
rus_verbs:вламывать{}, // Полиция вламывается в квартиру
rus_verbs:влетать{}, // Самолет влетает в грозовой фронт
rus_verbs:влететь{}, // Самолет влетел в грозовой фронт
rus_verbs:вливать{}, // Механик вливает масло в картер
rus_verbs:вливаться{}, // Масло вливается в картер
rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия
rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности
rus_verbs:влить{}, // Механик влил свежее масло в картер
rus_verbs:влиться{}, // Свежее масло влилось в бак
rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства
rus_verbs:вложиться{}, // Инвесторы вложились в эти акции
rus_verbs:влюбиться{}, // Коля влюбился в Олю
rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков
rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов
rus_verbs:вляпаться{}, // Коля вляпался в неприятность
rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности
rus_verbs:вменить{}, // вменить в вину
rus_verbs:вменять{}, // вменять в обязанность
rus_verbs:вмерзать{}, // Колеса вмерзают в лед
rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед
rus_verbs:вмести{}, // вмести в дом
rus_verbs:вместить{}, // вместить в ёмкость
rus_verbs:вместиться{}, // Прибор не вместился в зонд
rus_verbs:вмешаться{}, // Начальник вмешался в конфликт
rus_verbs:вмешивать{}, // Не вмешивай меня в это дело
rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры
rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус
rus_verbs:вминать{}, // вминать в корпус
rus_verbs:вминаться{}, // кронштейн вминается в корпус
rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы
rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда
rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт
rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт
rus_verbs:вморозить{}, // Установка вморозила сваи в грунт
rus_verbs:вмуровать{}, // Сейф был вмурован в стену
rus_verbs:вмуровывать{}, // вмуровывать сейф в стену
rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену
rus_verbs:внедрить{}, // внедрить инновацию в производство
rus_verbs:внедриться{}, // Шпион внедрился в руководство
rus_verbs:внедрять{}, // внедрять инновации в производство
rus_verbs:внедряться{}, // Шпионы внедряются в руководство
rus_verbs:внести{}, // внести коробку в дом
rus_verbs:внестись{}, // внестись в список приглашенных гостей
rus_verbs:вникать{}, // Разработчик вникает в детали задачи
rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи
rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев
rus_verbs:вноситься{}, // вноситься в список главных персонажей
rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса
rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом
rus_verbs:вогнать{}, // вогнал человека в тоску
rus_verbs:водворить{}, // водворить преступника в тюрьму
rus_verbs:возвернуть{}, // возвернуть в родную стихию
rus_verbs:возвернуться{}, // возвернуться в родную стихию
rus_verbs:возвести{}, // возвести число в четную степень
rus_verbs:возводить{}, // возводить число в четную степень
rus_verbs:возводиться{}, // число возводится в четную степень
rus_verbs:возвратить{}, // возвратить коров в стойло
rus_verbs:возвратиться{}, // возвратиться в родной дом
rus_verbs:возвращать{}, // возвращать коров в стойло
rus_verbs:возвращаться{}, // возвращаться в родной дом
rus_verbs:войти{}, // войти в галерею славы
rus_verbs:вонзать{}, // Коля вонзает вилку в котлету
rus_verbs:вонзаться{}, // Вилка вонзается в котлету
rus_verbs:вонзить{}, // Коля вонзил вилку в котлету
rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету
rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность
rus_verbs:воплотиться{}, // Мечты воплотились в реальность
rus_verbs:воплощать{}, // Коля воплощает мечты в реальность
rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность
rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь
rus_verbs:воспарить{}, // Душа воспарила в небо
rus_verbs:воспарять{}, // Душа воспаряет в небо
rus_verbs:врыть{}, // врыть опору в землю
rus_verbs:врыться{}, // врыться в землю
rus_verbs:всадить{}, // всадить пулю в сердце
rus_verbs:всаживать{}, // всаживать нож в бок
rus_verbs:всасывать{}, // всасывать воду в себя
rus_verbs:всасываться{}, // всасываться в ёмкость
rus_verbs:вселить{}, // вселить надежду в кого-либо
rus_verbs:вселиться{}, // вселиться в пустующее здание
rus_verbs:вселять{}, // вселять надежду в кого-то
rus_verbs:вселяться{}, // вселяться в пустующее здание
rus_verbs:вскидывать{}, // вскидывать руку в небо
rus_verbs:вскинуть{}, // вскинуть руку в небо
rus_verbs:вслушаться{}, // вслушаться в звуки
rus_verbs:вслушиваться{}, // вслушиваться в шорох
rus_verbs:всматриваться{}, // всматриваться в темноту
rus_verbs:всмотреться{}, // всмотреться в темень
rus_verbs:всовывать{}, // всовывать палец в отверстие
rus_verbs:всовываться{}, // всовываться в форточку
rus_verbs:всосать{}, // всосать жидкость в себя
rus_verbs:всосаться{}, // всосаться в кожу
rus_verbs:вставить{}, // вставить ключ в замок
rus_verbs:вставлять{}, // вставлять ключ в замок
rus_verbs:встраивать{}, // встраивать черный ход в систему защиты
rus_verbs:встраиваться{}, // встраиваться в систему безопасности
rus_verbs:встревать{}, // встревать в разговор
rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности
rus_verbs:встроиться{}, // встроиться в систему безопасности
rus_verbs:встрять{}, // встрять в разговор
rus_verbs:вступать{}, // вступать в действующую армию
rus_verbs:вступить{}, // вступить в действующую армию
rus_verbs:всунуть{}, // всунуть палец в отверстие
rus_verbs:всунуться{}, // всунуться в форточку
инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер
инфинитив:всыпать{вид:несоверш},
глагол:всыпать{вид:соверш},
глагол:всыпать{вид:несоверш},
деепричастие:всыпав{},
деепричастие:всыпая{},
прилагательное:всыпавший{ вид:соверш },
// прилагательное:всыпавший{ вид:несоверш },
прилагательное:всыпанный{},
// прилагательное:всыпающий{},
инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер
// инфинитив:всыпаться{ вид:соверш},
// глагол:всыпаться{ вид:соверш},
глагол:всыпаться{ вид:несоверш},
// деепричастие:всыпавшись{},
деепричастие:всыпаясь{},
// прилагательное:всыпавшийся{ вид:соверш },
// прилагательное:всыпавшийся{ вид:несоверш },
// прилагательное:всыпающийся{},
rus_verbs:вталкивать{}, // вталкивать деталь в ячейку
rus_verbs:вталкиваться{}, // вталкиваться в ячейку
rus_verbs:втаптывать{}, // втаптывать в грязь
rus_verbs:втаптываться{}, // втаптываться в грязь
rus_verbs:втаскивать{}, // втаскивать мешок в комнату
rus_verbs:втаскиваться{}, // втаскиваться в комнату
rus_verbs:втащить{}, // втащить мешок в комнату
rus_verbs:втащиться{}, // втащиться в комнату
rus_verbs:втекать{}, // втекать в бутылку
rus_verbs:втемяшивать{}, // втемяшивать в голову
rus_verbs:втемяшиваться{}, // втемяшиваться в голову
rus_verbs:втемяшить{}, // втемяшить в голову
rus_verbs:втемяшиться{}, // втемяшиться в голову
rus_verbs:втереть{}, // втереть крем в кожу
rus_verbs:втереться{}, // втереться в кожу
rus_verbs:втесаться{}, // втесаться в группу
rus_verbs:втесывать{}, // втесывать в группу
rus_verbs:втесываться{}, // втесываться в группу
rus_verbs:втечь{}, // втечь в бак
rus_verbs:втирать{}, // втирать крем в кожу
rus_verbs:втираться{}, // втираться в кожу
rus_verbs:втискивать{}, // втискивать сумку в вагон
rus_verbs:втискиваться{}, // втискиваться в переполненный вагон
rus_verbs:втиснуть{}, // втиснуть сумку в вагон
rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро
rus_verbs:втолкать{}, // втолкать коляску в лифт
rus_verbs:втолкаться{}, // втолкаться в вагон метро
rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт
rus_verbs:втолкнуться{}, // втолкнуться в вагон метро
rus_verbs:втолочь{}, // втолочь в смесь
rus_verbs:втоптать{}, // втоптать цветы в землю
rus_verbs:вторгаться{}, // вторгаться в чужую зону
rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь
rus_verbs:втравить{}, // втравить кого-то в неприятности
rus_verbs:втравливать{}, // втравливать кого-то в неприятности
rus_verbs:втрамбовать{}, // втрамбовать камни в землю
rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю
rus_verbs:втрамбовываться{}, // втрамбовываться в землю
rus_verbs:втрескаться{}, // втрескаться в кого-то
rus_verbs:втрескиваться{}, // втрескиваться в кого-либо
rus_verbs:втыкать{}, // втыкать вилку в котлетку
rus_verbs:втыкаться{}, // втыкаться в розетку
rus_verbs:втюриваться{}, // втюриваться в кого-либо
rus_verbs:втюриться{}, // втюриться в кого-либо
rus_verbs:втягивать{}, // втягивать что-то в себя
rus_verbs:втягиваться{}, // втягиваться в себя
rus_verbs:втянуться{}, // втянуться в себя
rus_verbs:вцементировать{}, // вцементировать сваю в фундамент
rus_verbs:вчеканить{}, // вчеканить надпись в лист
rus_verbs:вчитаться{}, // вчитаться внимательнее в текст
rus_verbs:вчитываться{}, // вчитываться внимательнее в текст
rus_verbs:вчувствоваться{}, // вчувствоваться в роль
rus_verbs:вшагивать{}, // вшагивать в новую жизнь
rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь
rus_verbs:вшивать{}, // вшивать заплату в рубашку
rus_verbs:вшиваться{}, // вшиваться в ткань
rus_verbs:вшить{}, // вшить заплату в ткань
rus_verbs:въедаться{}, // въедаться в мякоть
rus_verbs:въезжать{}, // въезжать в гараж
rus_verbs:въехать{}, // въехать в гараж
rus_verbs:выиграть{}, // Коля выиграл в шахматы
rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы
rus_verbs:выкладывать{}, // выкладывать в общий доступ
rus_verbs:выкладываться{}, // выкладываться в общий доступ
rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет
rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет
rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет
rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет
rus_verbs:вылезать{}, // вылезать в открытое пространство
rus_verbs:вылезти{}, // вылезти в открытое пространство
rus_verbs:выливать{}, // выливать в бутылку
rus_verbs:выливаться{}, // выливаться в ёмкость
rus_verbs:вылить{}, // вылить отходы в канализацию
rus_verbs:вылиться{}, // Топливо вылилось в воду
rus_verbs:выложить{}, // выложить в общий доступ
rus_verbs:выпадать{}, // выпадать в осадок
rus_verbs:выпрыгивать{}, // выпрыгивать в окно
rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно
rus_verbs:выродиться{}, // выродиться в жалкое подобие
rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков
rus_verbs:высеваться{}, // высеваться в землю
rus_verbs:высеять{}, // высеять в землю
rus_verbs:выслать{}, // выслать в страну постоянного пребывания
rus_verbs:высморкаться{}, // высморкаться в платок
rus_verbs:высморкнуться{}, // высморкнуться в платок
rus_verbs:выстреливать{}, // выстреливать в цель
rus_verbs:выстреливаться{}, // выстреливаться в цель
rus_verbs:выстрелить{}, // выстрелить в цель
rus_verbs:вытекать{}, // вытекать в озеро
rus_verbs:вытечь{}, // вытечь в воду
rus_verbs:смотреть{}, // смотреть в будущее
rus_verbs:подняться{}, // подняться в лабораторию
rus_verbs:послать{}, // послать в магазин
rus_verbs:слать{}, // слать в неизвестность
rus_verbs:добавить{}, // добавить в суп
rus_verbs:пройти{}, // пройти в лабораторию
rus_verbs:положить{}, // положить в ящик
rus_verbs:прислать{}, // прислать в полицию
rus_verbs:упасть{}, // упасть в пропасть
инфинитив:писать{ aux stress="пис^ать" }, // писать в газету
инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки
глагол:писать{ aux stress="п^исать" },
глагол:писать{ aux stress="пис^ать" },
деепричастие:писая{},
прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки
прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету
rus_verbs:собираться{}, // собираться в поход
rus_verbs:звать{}, // звать в ресторан
rus_verbs:направиться{}, // направиться в ресторан
rus_verbs:отправиться{}, // отправиться в ресторан
rus_verbs:поставить{}, // поставить в угол
rus_verbs:целить{}, // целить в мишень
rus_verbs:попасть{}, // попасть в переплет
rus_verbs:ударить{}, // ударить в больное место
rus_verbs:закричать{}, // закричать в микрофон
rus_verbs:опустить{}, // опустить в воду
rus_verbs:принести{}, // принести в дом бездомного щенка
rus_verbs:отдать{}, // отдать в хорошие руки
rus_verbs:ходить{}, // ходить в школу
rus_verbs:уставиться{}, // уставиться в экран
rus_verbs:приходить{}, // приходить в бешенство
rus_verbs:махнуть{}, // махнуть в Италию
rus_verbs:сунуть{}, // сунуть в замочную скважину
rus_verbs:явиться{}, // явиться в расположение части
rus_verbs:уехать{}, // уехать в город
rus_verbs:целовать{}, // целовать в лобик
rus_verbs:повести{}, // повести в бой
rus_verbs:опуститься{}, // опуститься в кресло
rus_verbs:передать{}, // передать в архив
rus_verbs:побежать{}, // побежать в школу
rus_verbs:стечь{}, // стечь в воду
rus_verbs:уходить{}, // уходить добровольцем в армию
rus_verbs:привести{}, // привести в дом
rus_verbs:шагнуть{}, // шагнуть в неизвестность
rus_verbs:собраться{}, // собраться в поход
rus_verbs:заглянуть{}, // заглянуть в основу
rus_verbs:поспешить{}, // поспешить в церковь
rus_verbs:поцеловать{}, // поцеловать в лоб
rus_verbs:перейти{}, // перейти в высшую лигу
rus_verbs:поверить{}, // поверить в искренность
rus_verbs:глянуть{}, // глянуть в оглавление
rus_verbs:зайти{}, // зайти в кафетерий
rus_verbs:подобрать{}, // подобрать в лесу
rus_verbs:проходить{}, // проходить в помещение
rus_verbs:глядеть{}, // глядеть в глаза
rus_verbs:пригласить{}, // пригласить в театр
rus_verbs:позвать{}, // позвать в класс
rus_verbs:усесться{}, // усесться в кресло
rus_verbs:поступить{}, // поступить в институт
rus_verbs:лечь{}, // лечь в постель
rus_verbs:поклониться{}, // поклониться в пояс
rus_verbs:потянуться{}, // потянуться в лес
rus_verbs:колоть{}, // колоть в ягодицу
rus_verbs:присесть{}, // присесть в кресло
rus_verbs:оглядеться{}, // оглядеться в зеркало
rus_verbs:поглядеть{}, // поглядеть в зеркало
rus_verbs:превратиться{}, // превратиться в лягушку
rus_verbs:принимать{}, // принимать во внимание
rus_verbs:звонить{}, // звонить в колокола
rus_verbs:привезти{}, // привезти в гостиницу
rus_verbs:рухнуть{}, // рухнуть в пропасть
rus_verbs:пускать{}, // пускать в дело
rus_verbs:отвести{}, // отвести в больницу
rus_verbs:сойти{}, // сойти в ад
rus_verbs:набрать{}, // набрать в команду
rus_verbs:собрать{}, // собрать в кулак
rus_verbs:двигаться{}, // двигаться в каюту
rus_verbs:падать{}, // падать в область нуля
rus_verbs:полезть{}, // полезть в драку
rus_verbs:направить{}, // направить в стационар
rus_verbs:приводить{}, // приводить в чувство
rus_verbs:толкнуть{}, // толкнуть в бок
rus_verbs:кинуться{}, // кинуться в драку
rus_verbs:ткнуть{}, // ткнуть в глаз
rus_verbs:заключить{}, // заключить в объятия
rus_verbs:подниматься{}, // подниматься в небо
rus_verbs:расти{}, // расти в глубину
rus_verbs:налить{}, // налить в кружку
rus_verbs:швырнуть{}, // швырнуть в бездну
rus_verbs:прыгнуть{}, // прыгнуть в дверь
rus_verbs:промолчать{}, // промолчать в тряпочку
rus_verbs:садиться{}, // садиться в кресло
rus_verbs:лить{}, // лить в кувшин
rus_verbs:дослать{}, // дослать деталь в держатель
rus_verbs:переслать{}, // переслать в обработчик
rus_verbs:удалиться{}, // удалиться в совещательную комнату
rus_verbs:разглядывать{}, // разглядывать в бинокль
rus_verbs:повесить{}, // повесить в шкаф
инфинитив:походить{ вид:соверш }, // походить в институт
глагол:походить{ вид:соверш },
деепричастие:походив{},
// прилагательное:походивший{вид:соверш},
rus_verbs:помчаться{}, // помчаться в класс
rus_verbs:свалиться{}, // свалиться в яму
rus_verbs:сбежать{}, // сбежать в Англию
rus_verbs:стрелять{}, // стрелять в цель
rus_verbs:обращать{}, // обращать в свою веру
rus_verbs:завести{}, // завести в дом
rus_verbs:приобрести{}, // приобрести в рассрочку
rus_verbs:сбросить{}, // сбросить в яму
rus_verbs:устроиться{}, // устроиться в крупную корпорацию
rus_verbs:погрузиться{}, // погрузиться в пучину
rus_verbs:течь{}, // течь в канаву
rus_verbs:произвести{}, // произвести в звание майора
rus_verbs:метать{}, // метать в цель
rus_verbs:пустить{}, // пустить в дело
rus_verbs:полететь{}, // полететь в Европу
rus_verbs:пропустить{}, // пропустить в здание
rus_verbs:рвануть{}, // рвануть в отпуск
rus_verbs:заходить{}, // заходить в каморку
rus_verbs:нырнуть{}, // нырнуть в прорубь
rus_verbs:рвануться{}, // рвануться в атаку
rus_verbs:приподняться{}, // приподняться в воздух
rus_verbs:превращаться{}, // превращаться в крупную величину
rus_verbs:прокричать{}, // прокричать в ухо
rus_verbs:записать{}, // записать в блокнот
rus_verbs:забраться{}, // забраться в шкаф
rus_verbs:приезжать{}, // приезжать в деревню
rus_verbs:продать{}, // продать в рабство
rus_verbs:проникнуть{}, // проникнуть в центр
rus_verbs:устремиться{}, // устремиться в открытое море
rus_verbs:посадить{}, // посадить в кресло
rus_verbs:упереться{}, // упереться в пол
rus_verbs:ринуться{}, // ринуться в буфет
rus_verbs:отдавать{}, // отдавать в кадетское училище
rus_verbs:отложить{}, // отложить в долгий ящик
rus_verbs:убежать{}, // убежать в приют
rus_verbs:оценить{}, // оценить в миллион долларов
rus_verbs:поднимать{}, // поднимать в стратосферу
rus_verbs:отослать{}, // отослать в квалификационную комиссию
rus_verbs:отодвинуть{}, // отодвинуть в дальний угол
rus_verbs:торопиться{}, // торопиться в школу
rus_verbs:попадаться{}, // попадаться в руки
rus_verbs:поразить{}, // поразить в самое сердце
rus_verbs:доставить{}, // доставить в квартиру
rus_verbs:заслать{}, // заслать в тыл
rus_verbs:сослать{}, // сослать в изгнание
rus_verbs:запустить{}, // запустить в космос
rus_verbs:удариться{}, // удариться в запой
rus_verbs:ударяться{}, // ударяться в крайность
rus_verbs:шептать{}, // шептать в лицо
rus_verbs:уронить{}, // уронить в унитаз
rus_verbs:прорычать{}, // прорычать в микрофон
rus_verbs:засунуть{}, // засунуть в глотку
rus_verbs:плыть{}, // плыть в открытое море
rus_verbs:перенести{}, // перенести в духовку
rus_verbs:светить{}, // светить в лицо
rus_verbs:мчаться{}, // мчаться в ремонт
rus_verbs:стукнуть{}, // стукнуть в лоб
rus_verbs:обрушиться{}, // обрушиться в котлован
rus_verbs:поглядывать{}, // поглядывать в экран
rus_verbs:уложить{}, // уложить в кроватку
инфинитив:попадать{ вид:несоверш }, // попадать в черный список
глагол:попадать{ вид:несоверш },
прилагательное:попадающий{ вид:несоверш },
прилагательное:попадавший{ вид:несоверш },
деепричастие:попадая{},
rus_verbs:провалиться{}, // провалиться в яму
rus_verbs:жаловаться{}, // жаловаться в комиссию
rus_verbs:опоздать{}, // опоздать в школу
rus_verbs:посылать{}, // посылать в парикмахерскую
rus_verbs:погнать{}, // погнать в хлев
rus_verbs:поступать{}, // поступать в институт
rus_verbs:усадить{}, // усадить в кресло
rus_verbs:проиграть{}, // проиграть в рулетку
rus_verbs:прилететь{}, // прилететь в страну
rus_verbs:повалиться{}, // повалиться в траву
rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ
rus_verbs:лезть{}, // лезть в чужие дела
rus_verbs:потащить{}, // потащить в суд
rus_verbs:направляться{}, // направляться в порт
rus_verbs:поползти{}, // поползти в другую сторону
rus_verbs:пуститься{}, // пуститься в пляс
rus_verbs:забиться{}, // забиться в нору
rus_verbs:залезть{}, // залезть в конуру
rus_verbs:сдать{}, // сдать в утиль
rus_verbs:тронуться{}, // тронуться в путь
rus_verbs:сыграть{}, // сыграть в шахматы
rus_verbs:перевернуть{}, // перевернуть в более удобную позу
rus_verbs:сжимать{}, // сжимать пальцы в кулак
rus_verbs:подтолкнуть{}, // подтолкнуть в бок
rus_verbs:отнести{}, // отнести животное в лечебницу
rus_verbs:одеться{}, // одеться в зимнюю одежду
rus_verbs:плюнуть{}, // плюнуть в колодец
rus_verbs:передавать{}, // передавать в прокуратуру
rus_verbs:отскочить{}, // отскочить в лоб
rus_verbs:призвать{}, // призвать в армию
rus_verbs:увезти{}, // увезти в деревню
rus_verbs:улечься{}, // улечься в кроватку
rus_verbs:отшатнуться{}, // отшатнуться в сторону
rus_verbs:ложиться{}, // ложиться в постель
rus_verbs:пролететь{}, // пролететь в конец
rus_verbs:класть{}, // класть в сейф
rus_verbs:доставлять{}, // доставлять в кабинет
rus_verbs:приобретать{}, // приобретать в кредит
rus_verbs:сводить{}, // сводить в театр
rus_verbs:унести{}, // унести в могилу
rus_verbs:покатиться{}, // покатиться в яму
rus_verbs:сходить{}, // сходить в магазинчик
rus_verbs:спустить{}, // спустить в канализацию
rus_verbs:проникать{}, // проникать в сердцевину
rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд
rus_verbs:пожаловаться{}, // пожаловаться в администрацию
rus_verbs:стучать{}, // стучать в металлическую дверь
rus_verbs:тащить{}, // тащить в ремонт
rus_verbs:заглядывать{}, // заглядывать в ответы
rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена
rus_verbs:увести{}, // увести в следующий кабинет
rus_verbs:успевать{}, // успевать в школу
rus_verbs:пробраться{}, // пробраться в собачью конуру
rus_verbs:подавать{}, // подавать в суд
rus_verbs:прибежать{}, // прибежать в конюшню
rus_verbs:рассмотреть{}, // рассмотреть в микроскоп
rus_verbs:пнуть{}, // пнуть в живот
rus_verbs:завернуть{}, // завернуть в декоративную пленку
rus_verbs:уезжать{}, // уезжать в деревню
rus_verbs:привлекать{}, // привлекать в свои ряды
rus_verbs:перебраться{}, // перебраться в прибрежный город
rus_verbs:долить{}, // долить в коктейль
rus_verbs:палить{}, // палить в нападающих
rus_verbs:отобрать{}, // отобрать в коллекцию
rus_verbs:улететь{}, // улететь в неизвестность
rus_verbs:выглянуть{}, // выглянуть в окно
rus_verbs:выглядывать{}, // выглядывать в окно
rus_verbs:пробираться{}, // грабитель, пробирающийся в дом
инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог
глагол:написать{ aux stress="напис^ать"},
прилагательное:написавший{ aux stress="напис^авший"},
rus_verbs:свернуть{}, // свернуть в колечко
инфинитив:сползать{ вид:несоверш }, // сползать в овраг
глагол:сползать{ вид:несоверш },
прилагательное:сползающий{ вид:несоверш },
прилагательное:сползавший{ вид:несоверш },
rus_verbs:барабанить{}, // барабанить в дверь
rus_verbs:дописывать{}, // дописывать в конец
rus_verbs:меняться{}, // меняться в лучшую сторону
rus_verbs:измениться{}, // измениться в лучшую сторону
rus_verbs:изменяться{}, // изменяться в лучшую сторону
rus_verbs:вписаться{}, // вписаться в поворот
rus_verbs:вписываться{}, // вписываться в повороты
rus_verbs:переработать{}, // переработать в удобрение
rus_verbs:перерабатывать{}, // перерабатывать в удобрение
rus_verbs:уползать{}, // уползать в тень
rus_verbs:заползать{}, // заползать в нору
rus_verbs:перепрятать{}, // перепрятать в укромное место
rus_verbs:заталкивать{}, // заталкивать в вагон
rus_verbs:преобразовывать{}, // преобразовывать в список
инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список
глагол:конвертировать{ вид:несоверш },
инфинитив:конвертировать{ вид:соверш },
глагол:конвертировать{ вид:соверш },
деепричастие:конвертировав{},
деепричастие:конвертируя{},
rus_verbs:изорвать{}, // Он изорвал газету в клочки.
rus_verbs:выходить{}, // Окна выходят в сад.
rus_verbs:говорить{}, // Он говорил в защиту своего отца.
rus_verbs:вырастать{}, // Он вырастает в большого художника.
rus_verbs:вывести{}, // Он вывел детей в сад.
// инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш },
// глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли.
// прилагательное:раненый{}, // Он был ранен в левую руку.
// прилагательное:одетый{}, // Он был одет в толстое осеннее пальто.
rus_verbs:бухнуться{}, // Он бухнулся в воду.
rus_verbs:склонять{}, // склонять защиту в свою пользу
rus_verbs:впиться{}, // Пиявка впилась в тело.
rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы
rus_verbs:сохранять{}, // сохранить данные в файл
rus_verbs:собирать{}, // собирать игрушки в ящик
rus_verbs:упаковывать{}, // упаковывать вещи в чемодан
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:стрельнуть{}, // стрельни в толпу!
rus_verbs:пулять{}, // пуляй в толпу
rus_verbs:пульнуть{}, // пульни в толпу
rus_verbs:становиться{}, // Становитесь в очередь.
rus_verbs:вписать{}, // Юля вписала свое имя в список.
rus_verbs:вписывать{}, // Мы вписывали свои имена в список
прилагательное:видный{}, // Планета Марс видна в обычный бинокль
rus_verbs:пойти{}, // Девочка рано пошла в школу
rus_verbs:отойти{}, // Эти обычаи отошли в историю.
rus_verbs:бить{}, // Холодный ветер бил ему в лицо.
rus_verbs:входить{}, // Это входит в его обязанности.
rus_verbs:принять{}, // меня приняли в пионеры
rus_verbs:уйти{}, // Правительство РФ ушло в отставку
rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году.
rus_verbs:посвятить{}, // Я посвятил друга в свою тайну.
инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока
rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза.
rus_verbs:идти{}, // Я иду гулять в парк.
rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт.
rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей.
rus_verbs:везти{}, // Учитель везёт детей в лагерь.
rus_verbs:качать{}, // Судно качает во все стороны.
rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами.
rus_verbs:связать{}, // Свяжите свои вещи в узелок.
rus_verbs:пронести{}, // Пронесите стол в дверь.
rus_verbs:вынести{}, // Надо вынести примечания в конец.
rus_verbs:устроить{}, // Она устроила сына в школу.
rus_verbs:угодить{}, // Она угодила головой в дверь.
rus_verbs:отвернуться{}, // Она резко отвернулась в сторону.
rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль.
rus_verbs:обратить{}, // Война обратила город в развалины.
rus_verbs:сойтись{}, // Мы сошлись в школьные годы.
rus_verbs:приехать{}, // Мы приехали в положенный час.
rus_verbs:встать{}, // Дети встали в круг.
rus_verbs:впасть{}, // Из-за болезни он впал в нужду.
rus_verbs:придти{}, // придти в упадок
rus_verbs:заявить{}, // Надо заявить в милицию о краже.
rus_verbs:заявлять{}, // заявлять в полицию
rus_verbs:ехать{}, // Мы будем ехать в Орёл
rus_verbs:окрашиваться{}, // окрашиваться в красный цвет
rus_verbs:решить{}, // Дело решено в пользу истца.
rus_verbs:сесть{}, // Она села в кресло
rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало.
rus_verbs:влезать{}, // он влезает в мою квартирку
rus_verbs:попасться{}, // в мою ловушку попалась мышь
rus_verbs:лететь{}, // Мы летим в Орёл
ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень
ГЛ_ИНФ(взять), // Коля взял в руку камень
ГЛ_ИНФ(поехать), // поехать в круиз
ГЛ_ИНФ(подать), // подать в отставку
инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик
инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик
ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море
ГЛ_ИНФ(постучать) // постучать в дверь
}
// Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } }
then return true
}
#endregion Винительный
// Все остальные варианты по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:в{} * }
then return false,-5
}
#endregion Предлог_В
#region Предлог_НА
// ------------------- С ПРЕДЛОГОМ 'НА' ---------------------------
#region ПРЕДЛОЖНЫЙ
// НА+предложный падеж:
// ЛЕЖАТЬ НА СТОЛЕ
#region VerbList
wordentry_set Гл_НА_Предл=
{
rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета
rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ)
rus_verbs:ПРОСТУПИТЬ{}, //
rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ)
rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ)
rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив)
rus_verbs:ЗАМИРАТЬ{}, //
rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ)
rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ)
rus_verbs:УПОЛЗАТЬ{}, //
rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ)
rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ)
rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ)
rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ)
rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:искриться{},
rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ)
rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ)
rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ)
rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ)
rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ)
rus_verbs:отвести{}, // отвести душу на людях
rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра
rus_verbs:сойтись{},
rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ)
rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ)
rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ)
глагол:ДОСТИЧЬ{},
инфинитив:ДОСТИЧЬ{},
rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте
rus_verbs:РАСКЛАДЫВАТЬ{},
rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ)
rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ)
rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ)
rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ)
rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ)
rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ)
rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта
rus_verbs:подпрыгивать{},
rus_verbs:высветиться{}, // на компьютере высветится твоя подпись
rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах
rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе
rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА)
rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл)
rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл)
rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА)
rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл)
rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл)
rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл)
rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл)
rus_verbs:ОТТОЧИТЬ{},
rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА)
rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл)
инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл)
глагол:НАХОДИТЬСЯ{ вид:несоверш },
прилагательное:находившийся{ вид:несоверш },
прилагательное:находящийся{ вид:несоверш },
деепричастие:находясь{},
rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл)
rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА)
rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА)
rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл)
rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА)
rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл)
rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА)
rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА)
rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА)
rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА)
rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА)
rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА)
rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл)
rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА)
rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА)
rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА)
rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА)
rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА)
rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл)
rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл)
rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на)
rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к)
rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на)
глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте)
деепричастие:вычитав{},
rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на)
rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере
rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере
rus_verbs:развалиться{}, // Антонио развалился на диване
rus_verbs:улечься{}, // Антонио улегся на полу
rus_verbs:зарубить{}, // Заруби себе на носу.
rus_verbs:ценить{}, // Его ценят на заводе.
rus_verbs:вернуться{}, // Отец вернулся на закате.
rus_verbs:шить{}, // Вы умеете шить на машинке?
rus_verbs:бить{}, // Скот бьют на бойне.
rus_verbs:выехать{}, // Мы выехали на рассвете.
rus_verbs:валяться{}, // На полу валяется бумага.
rus_verbs:разложить{}, // она разложила полотенце на песке
rus_verbs:заниматься{}, // я занимаюсь на тренажере
rus_verbs:позаниматься{},
rus_verbs:порхать{}, // порхать на лугу
rus_verbs:пресекать{}, // пресекать на корню
rus_verbs:изъясняться{}, // изъясняться на непонятном языке
rus_verbs:развесить{}, // развесить на столбах
rus_verbs:обрасти{}, // обрасти на южной части
rus_verbs:откладываться{}, // откладываться на стенках артерий
rus_verbs:уносить{}, // уносить на носилках
rus_verbs:проплыть{}, // проплыть на плоту
rus_verbs:подъезжать{}, // подъезжать на повозках
rus_verbs:пульсировать{}, // пульсировать на лбу
rus_verbs:рассесться{}, // птицы расселись на ветках
rus_verbs:застопориться{}, // застопориться на первом пункте
rus_verbs:изловить{}, // изловить на окраинах
rus_verbs:покататься{}, // покататься на машинках
rus_verbs:залопотать{}, // залопотать на неизвестном языке
rus_verbs:растягивать{}, // растягивать на станке
rus_verbs:поделывать{}, // поделывать на пляже
rus_verbs:подстеречь{}, // подстеречь на площадке
rus_verbs:проектировать{}, // проектировать на компьютере
rus_verbs:притулиться{}, // притулиться на кушетке
rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище
rus_verbs:пострелять{}, // пострелять на испытательном полигоне
rus_verbs:засиживаться{}, // засиживаться на работе
rus_verbs:нежиться{}, // нежиться на солнышке
rus_verbs:притомиться{}, // притомиться на рабочем месте
rus_verbs:поселяться{}, // поселяться на чердаке
rus_verbs:потягиваться{}, // потягиваться на земле
rus_verbs:отлеживаться{}, // отлеживаться на койке
rus_verbs:протаранить{}, // протаранить на танке
rus_verbs:гарцевать{}, // гарцевать на коне
rus_verbs:облупиться{}, // облупиться на носу
rus_verbs:оговорить{}, // оговорить на собеседовании
rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте
rus_verbs:отпечатать{}, // отпечатать на картоне
rus_verbs:сэкономить{}, // сэкономить на мелочах
rus_verbs:покатать{}, // покатать на пони
rus_verbs:колесить{}, // колесить на старой машине
rus_verbs:понастроить{}, // понастроить на участках
rus_verbs:поджарить{}, // поджарить на костре
rus_verbs:узнаваться{}, // узнаваться на фотографии
rus_verbs:отощать{}, // отощать на казенных харчах
rus_verbs:редеть{}, // редеть на макушке
rus_verbs:оглашать{}, // оглашать на общем собрании
rus_verbs:лопотать{}, // лопотать на иврите
rus_verbs:пригреть{}, // пригреть на груди
rus_verbs:консультироваться{}, // консультироваться на форуме
rus_verbs:приноситься{}, // приноситься на одежде
rus_verbs:сушиться{}, // сушиться на балконе
rus_verbs:наследить{}, // наследить на полу
rus_verbs:нагреться{}, // нагреться на солнце
rus_verbs:рыбачить{}, // рыбачить на озере
rus_verbs:прокатить{}, // прокатить на выборах
rus_verbs:запинаться{}, // запинаться на ровном месте
rus_verbs:отрубиться{}, // отрубиться на мягкой подушке
rus_verbs:заморозить{}, // заморозить на улице
rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе
rus_verbs:просохнуть{}, // просохнуть на батарее
rus_verbs:развозить{}, // развозить на велосипеде
rus_verbs:прикорнуть{}, // прикорнуть на диванчике
rus_verbs:отпечататься{}, // отпечататься на коже
rus_verbs:выявлять{}, // выявлять на таможне
rus_verbs:расставлять{}, // расставлять на башнях
rus_verbs:прокрутить{}, // прокрутить на пальце
rus_verbs:умываться{}, // умываться на улице
rus_verbs:пересказывать{}, // пересказывать на страницах романа
rus_verbs:удалять{}, // удалять на пуховике
rus_verbs:хозяйничать{}, // хозяйничать на складе
rus_verbs:оперировать{}, // оперировать на поле боя
rus_verbs:поносить{}, // поносить на голове
rus_verbs:замурлыкать{}, // замурлыкать на коленях
rus_verbs:передвигать{}, // передвигать на тележке
rus_verbs:прочертить{}, // прочертить на земле
rus_verbs:колдовать{}, // колдовать на кухне
rus_verbs:отвозить{}, // отвозить на казенном транспорте
rus_verbs:трахать{}, // трахать на природе
rus_verbs:мастерить{}, // мастерить на кухне
rus_verbs:ремонтировать{}, // ремонтировать на коленке
rus_verbs:развезти{}, // развезти на велосипеде
rus_verbs:робеть{}, // робеть на сцене
инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте
глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш },
деепричастие:реализовав{}, деепричастие:реализуя{},
rus_verbs:покаяться{}, // покаяться на смертном одре
rus_verbs:специализироваться{}, // специализироваться на тестировании
rus_verbs:попрыгать{}, // попрыгать на батуте
rus_verbs:переписывать{}, // переписывать на столе
rus_verbs:расписывать{}, // расписывать на доске
rus_verbs:зажимать{}, // зажимать на запястье
rus_verbs:практиковаться{}, // практиковаться на мышах
rus_verbs:уединиться{}, // уединиться на чердаке
rus_verbs:подохнуть{}, // подохнуть на чужбине
rus_verbs:приподниматься{}, // приподниматься на руках
rus_verbs:уродиться{}, // уродиться на полях
rus_verbs:продолжиться{}, // продолжиться на улице
rus_verbs:посапывать{}, // посапывать на диване
rus_verbs:ободрать{}, // ободрать на спине
rus_verbs:скрючиться{}, // скрючиться на песке
rus_verbs:тормознуть{}, // тормознуть на перекрестке
rus_verbs:лютовать{}, // лютовать на хуторе
rus_verbs:зарегистрировать{}, // зарегистрировать на сайте
rus_verbs:переждать{}, // переждать на вершине холма
rus_verbs:доминировать{}, // доминировать на территории
rus_verbs:публиковать{}, // публиковать на сайте
rus_verbs:морщить{}, // морщить на лбу
rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном
rus_verbs:подрабатывать{}, // подрабатывать на рынке
rus_verbs:репетировать{}, // репетировать на заднем дворе
rus_verbs:подвернуть{}, // подвернуть на брусчатке
rus_verbs:зашелестеть{}, // зашелестеть на ветру
rus_verbs:расчесывать{}, // расчесывать на спине
rus_verbs:одевать{}, // одевать на рынке
rus_verbs:испечь{}, // испечь на углях
rus_verbs:сбрить{}, // сбрить на затылке
rus_verbs:согреться{}, // согреться на печке
rus_verbs:замаячить{}, // замаячить на горизонте
rus_verbs:пересчитывать{}, // пересчитывать на пальцах
rus_verbs:галдеть{}, // галдеть на крыльце
rus_verbs:переплыть{}, // переплыть на плоту
rus_verbs:передохнуть{}, // передохнуть на скамейке
rus_verbs:прижиться{}, // прижиться на ферме
rus_verbs:переправляться{}, // переправляться на плотах
rus_verbs:накупить{}, // накупить на блошином рынке
rus_verbs:проторчать{}, // проторчать на виду
rus_verbs:мокнуть{}, // мокнуть на улице
rus_verbs:застукать{}, // застукать на камбузе
rus_verbs:завязывать{}, // завязывать на ботинках
rus_verbs:повисать{}, // повисать на ветке
rus_verbs:подвизаться{}, // подвизаться на государственной службе
rus_verbs:кормиться{}, // кормиться на болоте
rus_verbs:покурить{}, // покурить на улице
rus_verbs:зимовать{}, // зимовать на болотах
rus_verbs:застегивать{}, // застегивать на гимнастерке
rus_verbs:поигрывать{}, // поигрывать на гитаре
rus_verbs:погореть{}, // погореть на махинациях с землей
rus_verbs:кувыркаться{}, // кувыркаться на батуте
rus_verbs:похрапывать{}, // похрапывать на диване
rus_verbs:пригревать{}, // пригревать на груди
rus_verbs:завязнуть{}, // завязнуть на болоте
rus_verbs:шастать{}, // шастать на втором этаже
rus_verbs:заночевать{}, // заночевать на сеновале
rus_verbs:отсиживаться{}, // отсиживаться на чердаке
rus_verbs:мчать{}, // мчать на байке
rus_verbs:сгнить{}, // сгнить на урановых рудниках
rus_verbs:тренировать{}, // тренировать на манекенах
rus_verbs:повеселиться{}, // повеселиться на празднике
rus_verbs:измучиться{}, // измучиться на болоте
rus_verbs:увянуть{}, // увянуть на подоконнике
rus_verbs:раскрутить{}, // раскрутить на оси
rus_verbs:выцвести{}, // выцвести на солнечном свету
rus_verbs:изготовлять{}, // изготовлять на коленке
rus_verbs:гнездиться{}, // гнездиться на вершине дерева
rus_verbs:разогнаться{}, // разогнаться на мотоцикле
rus_verbs:излагаться{}, // излагаться на страницах доклада
rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге
rus_verbs:расчесать{}, // расчесать на макушке
rus_verbs:плавиться{}, // плавиться на солнце
rus_verbs:редактировать{}, // редактировать на ноутбуке
rus_verbs:подскакивать{}, // подскакивать на месте
rus_verbs:покупаться{}, // покупаться на рынке
rus_verbs:промышлять{}, // промышлять на мелководье
rus_verbs:приобретаться{}, // приобретаться на распродажах
rus_verbs:наигрывать{}, // наигрывать на банджо
rus_verbs:маневрировать{}, // маневрировать на флангах
rus_verbs:запечатлеться{}, // запечатлеться на записях камер
rus_verbs:укрывать{}, // укрывать на чердаке
rus_verbs:подорваться{}, // подорваться на фугасе
rus_verbs:закрепиться{}, // закрепиться на занятых позициях
rus_verbs:громыхать{}, // громыхать на кухне
инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу
деепричастие:подвигавшись{},
rus_verbs:добываться{}, // добываться на территории Анголы
rus_verbs:приплясывать{}, // приплясывать на сцене
rus_verbs:доживать{}, // доживать на больничной койке
rus_verbs:отпраздновать{}, // отпраздновать на работе
rus_verbs:сгубить{}, // сгубить на корню
rus_verbs:схоронить{}, // схоронить на кладбище
rus_verbs:тускнеть{}, // тускнеть на солнце
rus_verbs:скопить{}, // скопить на счету
rus_verbs:помыть{}, // помыть на своем этаже
rus_verbs:пороть{}, // пороть на конюшне
rus_verbs:наличествовать{}, // наличествовать на складе
rus_verbs:нащупывать{}, // нащупывать на полке
rus_verbs:змеиться{}, // змеиться на дне
rus_verbs:пожелтеть{}, // пожелтеть на солнце
rus_verbs:заостриться{}, // заостриться на конце
rus_verbs:свезти{}, // свезти на поле
rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре
rus_verbs:подкрутить{}, // подкрутить на приборной панели
rus_verbs:рубиться{}, // рубиться на мечах
rus_verbs:сиживать{}, // сиживать на крыльце
rus_verbs:тараторить{}, // тараторить на иностранном языке
rus_verbs:теплеть{}, // теплеть на сердце
rus_verbs:покачаться{}, // покачаться на ветке
rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче
rus_verbs:развязывать{}, // развязывать на ботинках
rus_verbs:подвозить{}, // подвозить на мотороллере
rus_verbs:вышивать{}, // вышивать на рубашке
rus_verbs:скупать{}, // скупать на открытом рынке
rus_verbs:оформлять{}, // оформлять на встрече
rus_verbs:распускаться{}, // распускаться на клумбах
rus_verbs:прогореть{}, // прогореть на спекуляциях
rus_verbs:приползти{}, // приползти на коленях
rus_verbs:загореть{}, // загореть на пляже
rus_verbs:остудить{}, // остудить на балконе
rus_verbs:нарвать{}, // нарвать на поляне
rus_verbs:издохнуть{}, // издохнуть на болоте
rus_verbs:разгружать{}, // разгружать на дороге
rus_verbs:произрастать{}, // произрастать на болотах
rus_verbs:разуться{}, // разуться на коврике
rus_verbs:сооружать{}, // сооружать на площади
rus_verbs:зачитывать{}, // зачитывать на митинге
rus_verbs:уместиться{}, // уместиться на ладони
rus_verbs:закупить{}, // закупить на рынке
rus_verbs:горланить{}, // горланить на улице
rus_verbs:экономить{}, // экономить на спичках
rus_verbs:исправлять{}, // исправлять на доске
rus_verbs:расслабляться{}, // расслабляться на лежаке
rus_verbs:скапливаться{}, // скапливаться на крыше
rus_verbs:сплетничать{}, // сплетничать на скамеечке
rus_verbs:отъезжать{}, // отъезжать на лимузине
rus_verbs:отчитывать{}, // отчитывать на собрании
rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке
rus_verbs:потчевать{}, // потчевать на лаврах
rus_verbs:окопаться{}, // окопаться на окраине
rus_verbs:загорать{}, // загорать на пляже
rus_verbs:обгореть{}, // обгореть на солнце
rus_verbs:распознавать{}, // распознавать на фотографии
rus_verbs:заплетаться{}, // заплетаться на макушке
rus_verbs:перегреться{}, // перегреться на жаре
rus_verbs:подметать{}, // подметать на крыльце
rus_verbs:нарисоваться{}, // нарисоваться на горизонте
rus_verbs:проскакивать{}, // проскакивать на экране
rus_verbs:попивать{}, // попивать на балконе чай
rus_verbs:отплывать{}, // отплывать на лодке
rus_verbs:чирикать{}, // чирикать на ветках
rus_verbs:скупить{}, // скупить на оптовых базах
rus_verbs:наколоть{}, // наколоть на коже картинку
rus_verbs:созревать{}, // созревать на ветке
rus_verbs:проколоться{}, // проколоться на мелочи
rus_verbs:крутнуться{}, // крутнуться на заднем колесе
rus_verbs:переночевать{}, // переночевать на постоялом дворе
rus_verbs:концентрироваться{}, // концентрироваться на фильтре
rus_verbs:одичать{}, // одичать на хуторе
rus_verbs:спасаться{}, // спасаются на лодке
rus_verbs:доказываться{}, // доказываться на страницах книги
rus_verbs:познаваться{}, // познаваться на ринге
rus_verbs:замыкаться{}, // замыкаться на металлическом предмете
rus_verbs:заприметить{}, // заприметить на пригорке
rus_verbs:продержать{}, // продержать на морозе
rus_verbs:форсировать{}, // форсировать на плотах
rus_verbs:сохнуть{}, // сохнуть на солнце
rus_verbs:выявить{}, // выявить на поверхности
rus_verbs:заседать{}, // заседать на кафедре
rus_verbs:расплачиваться{}, // расплачиваться на выходе
rus_verbs:светлеть{}, // светлеть на горизонте
rus_verbs:залепетать{}, // залепетать на незнакомом языке
rus_verbs:подсчитывать{}, // подсчитывать на пальцах
rus_verbs:зарыть{}, // зарыть на пустыре
rus_verbs:сформироваться{}, // сформироваться на месте
rus_verbs:развертываться{}, // развертываться на площадке
rus_verbs:набивать{}, // набивать на манекенах
rus_verbs:замерзать{}, // замерзать на ветру
rus_verbs:схватывать{}, // схватывать на лету
rus_verbs:перевестись{}, // перевестись на Руси
rus_verbs:смешивать{}, // смешивать на блюдце
rus_verbs:прождать{}, // прождать на входе
rus_verbs:мерзнуть{}, // мерзнуть на ветру
rus_verbs:растирать{}, // растирать на коже
rus_verbs:переспать{}, // переспал на сеновале
rus_verbs:рассекать{}, // рассекать на скутере
rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне
rus_verbs:дрыхнуть{}, // дрыхнуть на диване
rus_verbs:распять{}, // распять на кресте
rus_verbs:запечься{}, // запечься на костре
rus_verbs:застилать{}, // застилать на балконе
rus_verbs:сыскаться{}, // сыскаться на огороде
rus_verbs:разориться{}, // разориться на продаже спичек
rus_verbs:переделать{}, // переделать на станке
rus_verbs:разъяснять{}, // разъяснять на страницах газеты
rus_verbs:поседеть{}, // поседеть на висках
rus_verbs:протащить{}, // протащить на спине
rus_verbs:осуществиться{}, // осуществиться на деле
rus_verbs:селиться{}, // селиться на окраине
rus_verbs:оплачивать{}, // оплачивать на первой кассе
rus_verbs:переворачивать{}, // переворачивать на сковородке
rus_verbs:упражняться{}, // упражняться на батуте
rus_verbs:испробовать{}, // испробовать на себе
rus_verbs:разгладиться{}, // разгладиться на спине
rus_verbs:рисоваться{}, // рисоваться на стекле
rus_verbs:продрогнуть{}, // продрогнуть на морозе
rus_verbs:пометить{}, // пометить на доске
rus_verbs:приютить{}, // приютить на чердаке
rus_verbs:избирать{}, // избирать на первых свободных выборах
rus_verbs:затеваться{}, // затеваться на матче
rus_verbs:уплывать{}, // уплывать на катере
rus_verbs:замерцать{}, // замерцать на рекламном щите
rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне
rus_verbs:запираться{}, // запираться на чердаке
rus_verbs:загубить{}, // загубить на корню
rus_verbs:развеяться{}, // развеяться на природе
rus_verbs:съезжаться{}, // съезжаться на лимузинах
rus_verbs:потанцевать{}, // потанцевать на могиле
rus_verbs:дохнуть{}, // дохнуть на солнце
rus_verbs:припарковаться{}, // припарковаться на газоне
rus_verbs:отхватить{}, // отхватить на распродаже
rus_verbs:остывать{}, // остывать на улице
rus_verbs:переваривать{}, // переваривать на высокой ветке
rus_verbs:подвесить{}, // подвесить на веревке
rus_verbs:хвастать{}, // хвастать на работе
rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая
rus_verbs:разлечься{}, // разлечься на полу
rus_verbs:очертить{}, // очертить на полу
rus_verbs:председательствовать{}, // председательствовать на собрании
rus_verbs:сконфузиться{}, // сконфузиться на сцене
rus_verbs:выявляться{}, // выявляться на ринге
rus_verbs:крутануться{}, // крутануться на заднем колесе
rus_verbs:караулить{}, // караулить на входе
rus_verbs:перечислять{}, // перечислять на пальцах
rus_verbs:обрабатывать{}, // обрабатывать на станке
rus_verbs:настигать{}, // настигать на берегу
rus_verbs:разгуливать{}, // разгуливать на берегу
rus_verbs:насиловать{}, // насиловать на пляже
rus_verbs:поредеть{}, // поредеть на макушке
rus_verbs:учитывать{}, // учитывать на балансе
rus_verbs:зарождаться{}, // зарождаться на большой глубине
rus_verbs:распространять{}, // распространять на сайтах
rus_verbs:пировать{}, // пировать на вершине холма
rus_verbs:начертать{}, // начертать на стене
rus_verbs:расцветать{}, // расцветать на подоконнике
rus_verbs:умнеть{}, // умнеть на глазах
rus_verbs:царствовать{}, // царствовать на окраине
rus_verbs:закрутиться{}, // закрутиться на работе
rus_verbs:отработать{}, // отработать на шахте
rus_verbs:полечь{}, // полечь на поле брани
rus_verbs:щебетать{}, // щебетать на ветке
rus_verbs:подчеркиваться{}, // подчеркиваться на сайте
rus_verbs:посеять{}, // посеять на другом поле
rus_verbs:замечаться{}, // замечаться на пастбище
rus_verbs:просчитать{}, // просчитать на пальцах
rus_verbs:голосовать{}, // голосовать на трассе
rus_verbs:маяться{}, // маяться на пляже
rus_verbs:сколотить{}, // сколотить на службе
rus_verbs:обретаться{}, // обретаться на чужбине
rus_verbs:обливаться{}, // обливаться на улице
rus_verbs:катать{}, // катать на лошадке
rus_verbs:припрятать{}, // припрятать на теле
rus_verbs:запаниковать{}, // запаниковать на экзамене
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете
деепричастие:слетав{},
rus_verbs:срубить{}, // срубить денег на спекуляциях
rus_verbs:зажигаться{}, // зажигаться на улице
rus_verbs:жарить{}, // жарить на углях
rus_verbs:накапливаться{}, // накапливаться на счету
rus_verbs:распуститься{}, // распуститься на грядке
rus_verbs:рассаживаться{}, // рассаживаться на местах
rus_verbs:странствовать{}, // странствовать на лошади
rus_verbs:осматриваться{}, // осматриваться на месте
rus_verbs:разворачивать{}, // разворачивать на завоеванной территории
rus_verbs:согревать{}, // согревать на вершине горы
rus_verbs:заскучать{}, // заскучать на вахте
rus_verbs:перекусить{}, // перекусить на бегу
rus_verbs:приплыть{}, // приплыть на тримаране
rus_verbs:зажигать{}, // зажигать на танцах
rus_verbs:закопать{}, // закопать на поляне
rus_verbs:стирать{}, // стирать на берегу
rus_verbs:подстерегать{}, // подстерегать на подходе
rus_verbs:погулять{}, // погулять на свадьбе
rus_verbs:огласить{}, // огласить на митинге
rus_verbs:разбогатеть{}, // разбогатеть на прииске
rus_verbs:грохотать{}, // грохотать на чердаке
rus_verbs:расположить{}, // расположить на границе
rus_verbs:реализоваться{}, // реализоваться на новой работе
rus_verbs:застывать{}, // застывать на морозе
rus_verbs:запечатлеть{}, // запечатлеть на пленке
rus_verbs:тренироваться{}, // тренироваться на манекене
rus_verbs:поспорить{}, // поспорить на совещании
rus_verbs:затягивать{}, // затягивать на поясе
rus_verbs:зиждиться{}, // зиждиться на твердой основе
rus_verbs:построиться{}, // построиться на песке
rus_verbs:надрываться{}, // надрываться на работе
rus_verbs:закипать{}, // закипать на плите
rus_verbs:затонуть{}, // затонуть на мелководье
rus_verbs:побыть{}, // побыть на фазенде
rus_verbs:сгорать{}, // сгорать на солнце
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице
деепричастие:пописав{ aux stress="поп^исав" },
rus_verbs:подраться{}, // подраться на сцене
rus_verbs:заправить{}, // заправить на последней заправке
rus_verbs:обозначаться{}, // обозначаться на карте
rus_verbs:просиживать{}, // просиживать на берегу
rus_verbs:начертить{}, // начертить на листке
rus_verbs:тормозить{}, // тормозить на льду
rus_verbs:затевать{}, // затевать на космической базе
rus_verbs:задерживать{}, // задерживать на таможне
rus_verbs:прилетать{}, // прилетать на частном самолете
rus_verbs:полулежать{}, // полулежать на травке
rus_verbs:ерзать{}, // ерзать на табуретке
rus_verbs:покопаться{}, // покопаться на складе
rus_verbs:подвезти{}, // подвезти на машине
rus_verbs:полежать{}, // полежать на водном матрасе
rus_verbs:стыть{}, // стыть на улице
rus_verbs:стынуть{}, // стынуть на улице
rus_verbs:скреститься{}, // скреститься на груди
rus_verbs:припарковать{}, // припарковать на стоянке
rus_verbs:здороваться{}, // здороваться на кафедре
rus_verbs:нацарапать{}, // нацарапать на парте
rus_verbs:откопать{}, // откопать на поляне
rus_verbs:смастерить{}, // смастерить на коленках
rus_verbs:довезти{}, // довезти на машине
rus_verbs:избивать{}, // избивать на крыше
rus_verbs:сварить{}, // сварить на костре
rus_verbs:истребить{}, // истребить на корню
rus_verbs:раскопать{}, // раскопать на болоте
rus_verbs:попить{}, // попить на кухне
rus_verbs:заправлять{}, // заправлять на базе
rus_verbs:кушать{}, // кушать на кухне
rus_verbs:замолкать{}, // замолкать на половине фразы
rus_verbs:измеряться{}, // измеряться на весах
rus_verbs:сбываться{}, // сбываться на самом деле
rus_verbs:изображаться{}, // изображается на сцене
rus_verbs:фиксировать{}, // фиксировать на данной высоте
rus_verbs:ослаблять{}, // ослаблять на шее
rus_verbs:зреть{}, // зреть на грядке
rus_verbs:зеленеть{}, // зеленеть на грядке
rus_verbs:критиковать{}, // критиковать на страницах газеты
rus_verbs:облететь{}, // облететь на самолете
rus_verbs:заразиться{}, // заразиться на работе
rus_verbs:рассеять{}, // рассеять на территории
rus_verbs:печься{}, // печься на костре
rus_verbs:поспать{}, // поспать на земле
rus_verbs:сплетаться{}, // сплетаться на макушке
rus_verbs:удерживаться{}, // удерживаться на расстоянии
rus_verbs:помешаться{}, // помешаться на чистоте
rus_verbs:ликвидировать{}, // ликвидировать на полигоне
rus_verbs:проваляться{}, // проваляться на диване
rus_verbs:лечиться{}, // лечиться на дому
rus_verbs:обработать{}, // обработать на станке
rus_verbs:защелкнуть{}, // защелкнуть на руках
rus_verbs:разносить{}, // разносить на одежде
rus_verbs:чесать{}, // чесать на груди
rus_verbs:наладить{}, // наладить на конвейере выпуск
rus_verbs:отряхнуться{}, // отряхнуться на улице
rus_verbs:разыгрываться{}, // разыгрываться на скачках
rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях
rus_verbs:греться{}, // греться на вокзале
rus_verbs:засидеться{}, // засидеться на одном месте
rus_verbs:материализоваться{}, // материализоваться на границе
rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин
rus_verbs:перевозить{}, // перевозить на платформе
rus_verbs:поиграть{}, // поиграть на скрипке
rus_verbs:потоптаться{}, // потоптаться на одном месте
rus_verbs:переправиться{}, // переправиться на плоту
rus_verbs:забрезжить{}, // забрезжить на горизонте
rus_verbs:завывать{}, // завывать на опушке
rus_verbs:заваривать{}, // заваривать на кухоньке
rus_verbs:перемещаться{}, // перемещаться на спасательном плоту
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке
rus_verbs:праздновать{}, // праздновать на улицах
rus_verbs:обучить{}, // обучить на корте
rus_verbs:орудовать{}, // орудовать на складе
rus_verbs:подрасти{}, // подрасти на глядке
rus_verbs:шелестеть{}, // шелестеть на ветру
rus_verbs:раздеваться{}, // раздеваться на публике
rus_verbs:пообедать{}, // пообедать на газоне
rus_verbs:жрать{}, // жрать на помойке
rus_verbs:исполняться{}, // исполняться на флейте
rus_verbs:похолодать{}, // похолодать на улице
rus_verbs:гнить{}, // гнить на каторге
rus_verbs:прослушать{}, // прослушать на концерте
rus_verbs:совещаться{}, // совещаться на заседании
rus_verbs:покачивать{}, // покачивать на волнах
rus_verbs:отсидеть{}, // отсидеть на гаупвахте
rus_verbs:формировать{}, // формировать на секретной базе
rus_verbs:захрапеть{}, // захрапеть на кровати
rus_verbs:объехать{}, // объехать на попутке
rus_verbs:поселить{}, // поселить на верхних этажах
rus_verbs:заворочаться{}, // заворочаться на сене
rus_verbs:напрятать{}, // напрятать на теле
rus_verbs:очухаться{}, // очухаться на земле
rus_verbs:полистать{}, // полистать на досуге
rus_verbs:завертеть{}, // завертеть на шесте
rus_verbs:печатать{}, // печатать на ноуте
rus_verbs:отыскаться{}, // отыскаться на складе
rus_verbs:зафиксировать{}, // зафиксировать на пленке
rus_verbs:расстилаться{}, // расстилаться на столе
rus_verbs:заместить{}, // заместить на посту
rus_verbs:угасать{}, // угасать на неуправляемом корабле
rus_verbs:сразить{}, // сразить на ринге
rus_verbs:расплываться{}, // расплываться на жаре
rus_verbs:сосчитать{}, // сосчитать на пальцах
rus_verbs:сгуститься{}, // сгуститься на небольшой высоте
rus_verbs:цитировать{}, // цитировать на плите
rus_verbs:ориентироваться{}, // ориентироваться на местности
rus_verbs:расширить{}, // расширить на другом конце
rus_verbs:обтереть{}, // обтереть на стоянке
rus_verbs:подстрелить{}, // подстрелить на охоте
rus_verbs:растереть{}, // растереть на твердой поверхности
rus_verbs:подавлять{}, // подавлять на первом этапе
rus_verbs:смешиваться{}, // смешиваться на поверхности
// инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте
// деепричастие:вычитав{},
rus_verbs:сократиться{}, // сократиться на втором этапе
rus_verbs:занервничать{}, // занервничать на экзамене
rus_verbs:соприкоснуться{}, // соприкоснуться на трассе
rus_verbs:обозначить{}, // обозначить на плане
rus_verbs:обучаться{}, // обучаться на производстве
rus_verbs:снизиться{}, // снизиться на большой высоте
rus_verbs:простудиться{}, // простудиться на ветру
rus_verbs:поддерживаться{}, // поддерживается на встрече
rus_verbs:уплыть{}, // уплыть на лодочке
rus_verbs:резвиться{}, // резвиться на песочке
rus_verbs:поерзать{}, // поерзать на скамеечке
rus_verbs:похвастаться{}, // похвастаться на встрече
rus_verbs:знакомиться{}, // знакомиться на уроке
rus_verbs:проплывать{}, // проплывать на катере
rus_verbs:засесть{}, // засесть на чердаке
rus_verbs:подцепить{}, // подцепить на дискотеке
rus_verbs:обыскать{}, // обыскать на входе
rus_verbs:оправдаться{}, // оправдаться на суде
rus_verbs:раскрываться{}, // раскрываться на сцене
rus_verbs:одеваться{}, // одеваться на вещевом рынке
rus_verbs:засветиться{}, // засветиться на фотографиях
rus_verbs:употребляться{}, // употребляться на птицефабриках
rus_verbs:грабить{}, // грабить на пустыре
rus_verbs:гонять{}, // гонять на повышенных оборотах
rus_verbs:развеваться{}, // развеваться на древке
rus_verbs:основываться{}, // основываться на безусловных фактах
rus_verbs:допрашивать{}, // допрашивать на базе
rus_verbs:проработать{}, // проработать на стройке
rus_verbs:сосредоточить{}, // сосредоточить на месте
rus_verbs:сочинять{}, // сочинять на ходу
rus_verbs:ползать{}, // ползать на камне
rus_verbs:раскинуться{}, // раскинуться на пустыре
rus_verbs:уставать{}, // уставать на работе
rus_verbs:укрепить{}, // укрепить на конце
rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь
rus_verbs:одобрять{}, // одобрять на словах
rus_verbs:приговорить{}, // приговорить на заседании тройки
rus_verbs:чернеть{}, // чернеть на свету
rus_verbs:гнуть{}, // гнуть на станке
rus_verbs:размещаться{}, // размещаться на бирже
rus_verbs:соорудить{}, // соорудить на даче
rus_verbs:пастись{}, // пастись на лугу
rus_verbs:формироваться{}, // формироваться на дне
rus_verbs:таить{}, // таить на дне
rus_verbs:приостановиться{}, // приостановиться на середине
rus_verbs:топтаться{}, // топтаться на месте
rus_verbs:громить{}, // громить на подступах
rus_verbs:вычислить{}, // вычислить на бумажке
rus_verbs:заказывать{}, // заказывать на сайте
rus_verbs:осуществить{}, // осуществить на практике
rus_verbs:обосноваться{}, // обосноваться на верхушке
rus_verbs:пытать{}, // пытать на электрическом стуле
rus_verbs:совершиться{}, // совершиться на заседании
rus_verbs:свернуться{}, // свернуться на медленном огне
rus_verbs:пролетать{}, // пролетать на дельтаплане
rus_verbs:сбыться{}, // сбыться на самом деле
rus_verbs:разговориться{}, // разговориться на уроке
rus_verbs:разворачиваться{}, // разворачиваться на перекрестке
rus_verbs:преподнести{}, // преподнести на блюдечке
rus_verbs:напечатать{}, // напечатать на лазернике
rus_verbs:прорвать{}, // прорвать на периферии
rus_verbs:раскачиваться{}, // раскачиваться на доске
rus_verbs:задерживаться{}, // задерживаться на старте
rus_verbs:угощать{}, // угощать на вечеринке
rus_verbs:шарить{}, // шарить на столе
rus_verbs:увеличивать{}, // увеличивать на первом этапе
rus_verbs:рехнуться{}, // рехнуться на старости лет
rus_verbs:расцвести{}, // расцвести на грядке
rus_verbs:закипеть{}, // закипеть на плите
rus_verbs:подлететь{}, // подлететь на параплане
rus_verbs:рыться{}, // рыться на свалке
rus_verbs:добираться{}, // добираться на попутках
rus_verbs:продержаться{}, // продержаться на вершине
rus_verbs:разыскивать{}, // разыскивать на выставках
rus_verbs:освобождать{}, // освобождать на заседании
rus_verbs:передвигаться{}, // передвигаться на самокате
rus_verbs:проявиться{}, // проявиться на свету
rus_verbs:заскользить{}, // заскользить на льду
rus_verbs:пересказать{}, // пересказать на сцене студенческого театра
rus_verbs:протестовать{}, // протестовать на улице
rus_verbs:указываться{}, // указываться на табличках
rus_verbs:прискакать{}, // прискакать на лошадке
rus_verbs:копошиться{}, // копошиться на свежем воздухе
rus_verbs:подсчитать{}, // подсчитать на бумажке
rus_verbs:разволноваться{}, // разволноваться на экзамене
rus_verbs:завертеться{}, // завертеться на полу
rus_verbs:ознакомиться{}, // ознакомиться на ходу
rus_verbs:ржать{}, // ржать на уроке
rus_verbs:раскинуть{}, // раскинуть на грядках
rus_verbs:разгромить{}, // разгромить на ринге
rus_verbs:подслушать{}, // подслушать на совещании
rus_verbs:описываться{}, // описываться на страницах книги
rus_verbs:качаться{}, // качаться на стуле
rus_verbs:усилить{}, // усилить на флангах
rus_verbs:набросать{}, // набросать на клочке картона
rus_verbs:расстреливать{}, // расстреливать на подходе
rus_verbs:запрыгать{}, // запрыгать на одной ноге
rus_verbs:сыскать{}, // сыскать на чужбине
rus_verbs:подтвердиться{}, // подтвердиться на практике
rus_verbs:плескаться{}, // плескаться на мелководье
rus_verbs:расширяться{}, // расширяться на конце
rus_verbs:подержать{}, // подержать на солнце
rus_verbs:планироваться{}, // планироваться на общем собрании
rus_verbs:сгинуть{}, // сгинуть на чужбине
rus_verbs:замкнуться{}, // замкнуться на точке
rus_verbs:закачаться{}, // закачаться на ветру
rus_verbs:перечитывать{}, // перечитывать на ходу
rus_verbs:перелететь{}, // перелететь на дельтаплане
rus_verbs:оживать{}, // оживать на солнце
rus_verbs:женить{}, // женить на богатой невесте
rus_verbs:заглохнуть{}, // заглохнуть на старте
rus_verbs:копаться{}, // копаться на полу
rus_verbs:развлекаться{}, // развлекаться на дискотеке
rus_verbs:печататься{}, // печататься на струйном принтере
rus_verbs:обрываться{}, // обрываться на полуслове
rus_verbs:ускакать{}, // ускакать на лошадке
rus_verbs:подписывать{}, // подписывать на столе
rus_verbs:добывать{}, // добывать на выработке
rus_verbs:скопиться{}, // скопиться на выходе
rus_verbs:повстречать{}, // повстречать на пути
rus_verbs:поцеловаться{}, // поцеловаться на площади
rus_verbs:растянуть{}, // растянуть на столе
rus_verbs:подаваться{}, // подаваться на благотворительном обеде
rus_verbs:повстречаться{}, // повстречаться на митинге
rus_verbs:примоститься{}, // примоститься на ступеньках
rus_verbs:отразить{}, // отразить на страницах доклада
rus_verbs:пояснять{}, // пояснять на страницах приложения
rus_verbs:накормить{}, // накормить на кухне
rus_verbs:поужинать{}, // поужинать на веранде
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге
деепричастие:спев{},
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить на мелководье
rus_verbs:освоить{}, // освоить на практике
rus_verbs:распластаться{}, // распластаться на травке
rus_verbs:отплыть{}, // отплыть на старом каяке
rus_verbs:улетать{}, // улетать на любом самолете
rus_verbs:отстаивать{}, // отстаивать на корте
rus_verbs:осуждать{}, // осуждать на словах
rus_verbs:переговорить{}, // переговорить на обеде
rus_verbs:укрыть{}, // укрыть на чердаке
rus_verbs:томиться{}, // томиться на привязи
rus_verbs:сжигать{}, // сжигать на полигоне
rus_verbs:позавтракать{}, // позавтракать на лоне природы
rus_verbs:функционировать{}, // функционирует на солнечной энергии
rus_verbs:разместить{}, // разместить на сайте
rus_verbs:пронести{}, // пронести на теле
rus_verbs:нашарить{}, // нашарить на столе
rus_verbs:корчиться{}, // корчиться на полу
rus_verbs:распознать{}, // распознать на снимке
rus_verbs:повеситься{}, // повеситься на шнуре
rus_verbs:обозначиться{}, // обозначиться на картах
rus_verbs:оступиться{}, // оступиться на скользком льду
rus_verbs:подносить{}, // подносить на блюдечке
rus_verbs:расстелить{}, // расстелить на газоне
rus_verbs:обсуждаться{}, // обсуждаться на собрании
rus_verbs:расписаться{}, // расписаться на бланке
rus_verbs:плестись{}, // плестись на привязи
rus_verbs:объявиться{}, // объявиться на сцене
rus_verbs:повышаться{}, // повышаться на первом датчике
rus_verbs:разрабатывать{}, // разрабатывать на заводе
rus_verbs:прерывать{}, // прерывать на середине
rus_verbs:каяться{}, // каяться на публике
rus_verbs:освоиться{}, // освоиться на лошади
rus_verbs:подплыть{}, // подплыть на плоту
rus_verbs:оскорбить{}, // оскорбить на митинге
rus_verbs:торжествовать{}, // торжествовать на пьедестале
rus_verbs:поправлять{}, // поправлять на одежде
rus_verbs:отражать{}, // отражать на картине
rus_verbs:дремать{}, // дремать на кушетке
rus_verbs:применяться{}, // применяться на производстве стали
rus_verbs:поражать{}, // поражать на большой дистанции
rus_verbs:расстрелять{}, // расстрелять на окраине хутора
rus_verbs:рассчитать{}, // рассчитать на калькуляторе
rus_verbs:записывать{}, // записывать на ленте
rus_verbs:перебирать{}, // перебирать на ладони
rus_verbs:разбиться{}, // разбиться на катере
rus_verbs:поискать{}, // поискать на ферме
rus_verbs:прятать{}, // прятать на заброшенном складе
rus_verbs:пропеть{}, // пропеть на эстраде
rus_verbs:замелькать{}, // замелькать на экране
rus_verbs:грустить{}, // грустить на веранде
rus_verbs:крутить{}, // крутить на оси
rus_verbs:подготовить{}, // подготовить на конспиративной квартире
rus_verbs:различать{}, // различать на картинке
rus_verbs:киснуть{}, // киснуть на чужбине
rus_verbs:оборваться{}, // оборваться на полуслове
rus_verbs:запутаться{}, // запутаться на простейшем тесте
rus_verbs:общаться{}, // общаться на уроке
rus_verbs:производиться{}, // производиться на фабрике
rus_verbs:сочинить{}, // сочинить на досуге
rus_verbs:давить{}, // давить на лице
rus_verbs:разработать{}, // разработать на секретном предприятии
rus_verbs:качать{}, // качать на качелях
rus_verbs:тушить{}, // тушить на крыше пожар
rus_verbs:охранять{}, // охранять на территории базы
rus_verbs:приметить{}, // приметить на взгорке
rus_verbs:скрыть{}, // скрыть на теле
rus_verbs:удерживать{}, // удерживать на руке
rus_verbs:усвоить{}, // усвоить на уроке
rus_verbs:растаять{}, // растаять на солнечной стороне
rus_verbs:красоваться{}, // красоваться на виду
rus_verbs:сохраняться{}, // сохраняться на холоде
rus_verbs:лечить{}, // лечить на дому
rus_verbs:прокатиться{}, // прокатиться на уницикле
rus_verbs:договариваться{}, // договариваться на нейтральной территории
rus_verbs:качнуться{}, // качнуться на одной ноге
rus_verbs:опубликовать{}, // опубликовать на сайте
rus_verbs:отражаться{}, // отражаться на поверхности воды
rus_verbs:обедать{}, // обедать на веранде
rus_verbs:посидеть{}, // посидеть на лавочке
rus_verbs:сообщаться{}, // сообщаться на официальном сайте
rus_verbs:свершиться{}, // свершиться на заседании
rus_verbs:ночевать{}, // ночевать на даче
rus_verbs:темнеть{}, // темнеть на свету
rus_verbs:гибнуть{}, // гибнуть на территории полигона
rus_verbs:усиливаться{}, // усиливаться на территории округа
rus_verbs:проживать{}, // проживать на даче
rus_verbs:исследовать{}, // исследовать на большой глубине
rus_verbs:обитать{}, // обитать на громадной глубине
rus_verbs:сталкиваться{}, // сталкиваться на большой высоте
rus_verbs:таиться{}, // таиться на большой глубине
rus_verbs:спасать{}, // спасать на пожаре
rus_verbs:сказываться{}, // сказываться на общем результате
rus_verbs:заблудиться{}, // заблудиться на стройке
rus_verbs:пошарить{}, // пошарить на полках
rus_verbs:планировать{}, // планировать на бумаге
rus_verbs:ранить{}, // ранить на полигоне
rus_verbs:хлопать{}, // хлопать на сцене
rus_verbs:основать{}, // основать на горе новый монастырь
rus_verbs:отбить{}, // отбить на столе
rus_verbs:отрицать{}, // отрицать на заседании комиссии
rus_verbs:устоять{}, // устоять на ногах
rus_verbs:отзываться{}, // отзываться на страницах отчёта
rus_verbs:притормозить{}, // притормозить на обочине
rus_verbs:читаться{}, // читаться на лице
rus_verbs:заиграть{}, // заиграть на саксофоне
rus_verbs:зависнуть{}, // зависнуть на игровой площадке
rus_verbs:сознаться{}, // сознаться на допросе
rus_verbs:выясняться{}, // выясняться на очной ставке
rus_verbs:наводить{}, // наводить на столе порядок
rus_verbs:покоиться{}, // покоиться на кладбище
rus_verbs:значиться{}, // значиться на бейджике
rus_verbs:съехать{}, // съехать на санках
rus_verbs:познакомить{}, // познакомить на свадьбе
rus_verbs:завязать{}, // завязать на спине
rus_verbs:грохнуть{}, // грохнуть на площади
rus_verbs:разъехаться{}, // разъехаться на узкой дороге
rus_verbs:столпиться{}, // столпиться на крыльце
rus_verbs:порыться{}, // порыться на полках
rus_verbs:ослабить{}, // ослабить на шее
rus_verbs:оправдывать{}, // оправдывать на суде
rus_verbs:обнаруживаться{}, // обнаруживаться на складе
rus_verbs:спастись{}, // спастись на дереве
rus_verbs:прерваться{}, // прерваться на полуслове
rus_verbs:строиться{}, // строиться на пустыре
rus_verbs:познать{}, // познать на практике
rus_verbs:путешествовать{}, // путешествовать на поезде
rus_verbs:побеждать{}, // побеждать на ринге
rus_verbs:рассматриваться{}, // рассматриваться на заседании
rus_verbs:продаваться{}, // продаваться на открытом рынке
rus_verbs:разместиться{}, // разместиться на базе
rus_verbs:завыть{}, // завыть на холме
rus_verbs:настигнуть{}, // настигнуть на окраине
rus_verbs:укрыться{}, // укрыться на чердаке
rus_verbs:расплакаться{}, // расплакаться на заседании комиссии
rus_verbs:заканчивать{}, // заканчивать на последнем задании
rus_verbs:пролежать{}, // пролежать на столе
rus_verbs:громоздиться{}, // громоздиться на полу
rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе
rus_verbs:поскользнуться{}, // поскользнуться на льду
rus_verbs:таскать{}, // таскать на спине
rus_verbs:просматривать{}, // просматривать на сайте
rus_verbs:обдумать{}, // обдумать на досуге
rus_verbs:гадать{}, // гадать на кофейной гуще
rus_verbs:останавливать{}, // останавливать на выходе
rus_verbs:обозначать{}, // обозначать на странице
rus_verbs:долететь{}, // долететь на спортивном байке
rus_verbs:тесниться{}, // тесниться на чердачке
rus_verbs:хоронить{}, // хоронить на частном кладбище
rus_verbs:установиться{}, // установиться на юге
rus_verbs:прикидывать{}, // прикидывать на клочке бумаги
rus_verbs:затаиться{}, // затаиться на дереве
rus_verbs:раздобыть{}, // раздобыть на складе
rus_verbs:перебросить{}, // перебросить на вертолетах
rus_verbs:захватывать{}, // захватывать на базе
rus_verbs:сказаться{}, // сказаться на итоговых оценках
rus_verbs:покачиваться{}, // покачиваться на волнах
rus_verbs:крутиться{}, // крутиться на кухне
rus_verbs:помещаться{}, // помещаться на полке
rus_verbs:питаться{}, // питаться на помойке
rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле
rus_verbs:кататься{}, // кататься на велике
rus_verbs:поработать{}, // поработать на стройке
rus_verbs:ограбить{}, // ограбить на пустыре
rus_verbs:зарабатывать{}, // зарабатывать на бирже
rus_verbs:преуспеть{}, // преуспеть на ниве искусства
rus_verbs:заерзать{}, // заерзать на стуле
rus_verbs:разъяснить{}, // разъяснить на полях
rus_verbs:отчеканить{}, // отчеканить на медной пластине
rus_verbs:торговать{}, // торговать на рынке
rus_verbs:поколебаться{}, // поколебаться на пороге
rus_verbs:прикинуть{}, // прикинуть на бумажке
rus_verbs:рассечь{}, // рассечь на тупом конце
rus_verbs:посмеяться{}, // посмеяться на переменке
rus_verbs:остыть{}, // остыть на морозном воздухе
rus_verbs:запереться{}, // запереться на чердаке
rus_verbs:обогнать{}, // обогнать на повороте
rus_verbs:подтянуться{}, // подтянуться на турнике
rus_verbs:привозить{}, // привозить на машине
rus_verbs:подбирать{}, // подбирать на полу
rus_verbs:уничтожать{}, // уничтожать на подходе
rus_verbs:притаиться{}, // притаиться на вершине
rus_verbs:плясать{}, // плясать на костях
rus_verbs:поджидать{}, // поджидать на вокзале
rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!)
rus_verbs:смениться{}, // смениться на посту
rus_verbs:посчитать{}, // посчитать на пальцах
rus_verbs:прицелиться{}, // прицелиться на бегу
rus_verbs:нарисовать{}, // нарисовать на стене
rus_verbs:прыгать{}, // прыгать на сцене
rus_verbs:повертеть{}, // повертеть на пальце
rus_verbs:попрощаться{}, // попрощаться на панихиде
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване
rus_verbs:разобрать{}, // разобрать на столе
rus_verbs:помереть{}, // помереть на чужбине
rus_verbs:различить{}, // различить на нечеткой фотографии
rus_verbs:рисовать{}, // рисовать на доске
rus_verbs:проследить{}, // проследить на экране
rus_verbs:задремать{}, // задремать на диване
rus_verbs:ругаться{}, // ругаться на людях
rus_verbs:сгореть{}, // сгореть на работе
rus_verbs:зазвучать{}, // зазвучать на коротких волнах
rus_verbs:задохнуться{}, // задохнуться на вершине горы
rus_verbs:порождать{}, // порождать на поверхности небольшую рябь
rus_verbs:отдыхать{}, // отдыхать на курорте
rus_verbs:образовать{}, // образовать на дне толстый слой
rus_verbs:поправиться{}, // поправиться на дармовых харчах
rus_verbs:отмечать{}, // отмечать на календаре
rus_verbs:реять{}, // реять на флагштоке
rus_verbs:ползти{}, // ползти на коленях
rus_verbs:продавать{}, // продавать на аукционе
rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче
rus_verbs:рыскать{}, // мышки рыскали на кухне
rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы
rus_verbs:напасть{}, // напасть на территории другого государства
rus_verbs:издать{}, // издать на западе
rus_verbs:оставаться{}, // оставаться на страже порядка
rus_verbs:появиться{}, // наконец появиться на экране
rus_verbs:лежать{}, // лежать на столе
rus_verbs:ждать{}, // ждать на берегу
инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге
глагол:писать{aux stress="пис^ать"},
rus_verbs:оказываться{}, // оказываться на полу
rus_verbs:поставить{}, // поставить на столе
rus_verbs:держать{}, // держать на крючке
rus_verbs:выходить{}, // выходить на остановке
rus_verbs:заговорить{}, // заговорить на китайском языке
rus_verbs:ожидать{}, // ожидать на стоянке
rus_verbs:закричать{}, // закричал на минарете муэдзин
rus_verbs:простоять{}, // простоять на посту
rus_verbs:продолжить{}, // продолжить на первом этаже
rus_verbs:ощутить{}, // ощутить на себе влияние кризиса
rus_verbs:состоять{}, // состоять на учете
rus_verbs:готовиться{},
инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте
глагол:акклиматизироваться{вид:несоверш},
rus_verbs:арестовать{}, // грабители были арестованы на месте преступления
rus_verbs:схватить{}, // грабители были схвачены на месте преступления
инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{ вид:соверш },
прилагательное:атаковавший{ вид:соверш },
rus_verbs:базировать{}, // установка будет базирована на границе
rus_verbs:базироваться{}, // установка базируется на границе
rus_verbs:барахтаться{}, // дети барахтались на мелководье
rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке
rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке
rus_verbs:бренчать{}, // парень что-то бренчал на гитаре
rus_verbs:бренькать{}, // парень что-то бренькает на гитаре
rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории.
rus_verbs:буксовать{}, // Колеса буксуют на льду
rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле
rus_verbs:взвести{}, // Боец взвел на оружии предохранитель
rus_verbs:вилять{}, // Машина сильно виляла на дороге
rus_verbs:висеть{}, // Яблоко висит на ветке
rus_verbs:возлежать{}, // возлежать на лежанке
rus_verbs:подниматься{}, // Мы поднимаемся на лифте
rus_verbs:подняться{}, // Мы поднимемся на лифте
rus_verbs:восседать{}, // Коля восседает на лошади
rus_verbs:воссиять{}, // Луна воссияла на небе
rus_verbs:воцариться{}, // Мир воцарился на всей земле
rus_verbs:воцаряться{}, // Мир воцаряется на всей земле
rus_verbs:вращать{}, // вращать на поясе
rus_verbs:вращаться{}, // вращаться на поясе
rus_verbs:встретить{}, // встретить друга на улице
rus_verbs:встретиться{}, // встретиться на занятиях
rus_verbs:встречать{}, // встречать на занятиях
rus_verbs:въебывать{}, // въебывать на работе
rus_verbs:въезжать{}, // въезжать на автомобиле
rus_verbs:въехать{}, // въехать на автомобиле
rus_verbs:выгорать{}, // ткань выгорает на солнце
rus_verbs:выгореть{}, // ткань выгорела на солнце
rus_verbs:выгравировать{}, // выгравировать на табличке надпись
rus_verbs:выжить{}, // выжить на необитаемом острове
rus_verbs:вылежаться{}, // помидоры вылежались на солнце
rus_verbs:вылеживаться{}, // вылеживаться на солнце
rus_verbs:выместить{}, // выместить на ком-то злобу
rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение
rus_verbs:вымещаться{}, // вымещаться на ком-то
rus_verbs:выращивать{}, // выращивать на грядке помидоры
rus_verbs:выращиваться{}, // выращиваться на грядке
инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись
глагол:вырезать{вид:соверш},
инфинитив:вырезать{вид:несоверш},
глагол:вырезать{вид:несоверш},
rus_verbs:вырисоваться{}, // вырисоваться на графике
rus_verbs:вырисовываться{}, // вырисовываться на графике
rus_verbs:высаживать{}, // высаживать на необитаемом острове
rus_verbs:высаживаться{}, // высаживаться на острове
rus_verbs:высвечивать{}, // высвечивать на дисплее температуру
rus_verbs:высвечиваться{}, // высвечиваться на дисплее
rus_verbs:выстроить{}, // выстроить на фундаменте
rus_verbs:выстроиться{}, // выстроиться на плацу
rus_verbs:выстудить{}, // выстудить на морозе
rus_verbs:выстудиться{}, // выстудиться на морозе
rus_verbs:выстужать{}, // выстужать на морозе
rus_verbs:выстуживать{}, // выстуживать на морозе
rus_verbs:выстуживаться{}, // выстуживаться на морозе
rus_verbs:выстукать{}, // выстукать на клавиатуре
rus_verbs:выстукивать{}, // выстукивать на клавиатуре
rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре
rus_verbs:выступать{}, // выступать на сцене
rus_verbs:выступить{}, // выступить на сцене
rus_verbs:выстучать{}, // выстучать на клавиатуре
rus_verbs:выстывать{}, // выстывать на морозе
rus_verbs:выстыть{}, // выстыть на морозе
rus_verbs:вытатуировать{}, // вытатуировать на руке якорь
rus_verbs:говорить{}, // говорить на повышенных тонах
rus_verbs:заметить{}, // заметить на берегу
rus_verbs:стоять{}, // твёрдо стоять на ногах
rus_verbs:оказаться{}, // оказаться на передовой линии
rus_verbs:почувствовать{}, // почувствовать на своей шкуре
rus_verbs:остановиться{}, // остановиться на первом пункте
rus_verbs:показаться{}, // показаться на горизонте
rus_verbs:чувствовать{}, // чувствовать на своей шкуре
rus_verbs:искать{}, // искать на открытом пространстве
rus_verbs:иметься{}, // иметься на складе
rus_verbs:клясться{}, // клясться на Коране
rus_verbs:прервать{}, // прервать на полуслове
rus_verbs:играть{}, // играть на чувствах
rus_verbs:спуститься{}, // спуститься на парашюте
rus_verbs:понадобиться{}, // понадобиться на экзамене
rus_verbs:служить{}, // служить на флоте
rus_verbs:подобрать{}, // подобрать на улице
rus_verbs:появляться{}, // появляться на сцене
rus_verbs:селить{}, // селить на чердаке
rus_verbs:поймать{}, // поймать на границе
rus_verbs:увидать{}, // увидать на опушке
rus_verbs:подождать{}, // подождать на перроне
rus_verbs:прочесть{}, // прочесть на полях
rus_verbs:тонуть{}, // тонуть на мелководье
rus_verbs:ощущать{}, // ощущать на коже
rus_verbs:отметить{}, // отметить на полях
rus_verbs:показывать{}, // показывать на графике
rus_verbs:разговаривать{}, // разговаривать на иностранном языке
rus_verbs:прочитать{}, // прочитать на сайте
rus_verbs:попробовать{}, // попробовать на практике
rus_verbs:замечать{}, // замечать на коже грязь
rus_verbs:нести{}, // нести на плечах
rus_verbs:носить{}, // носить на голове
rus_verbs:гореть{}, // гореть на работе
rus_verbs:застыть{}, // застыть на пороге
инфинитив:жениться{ вид:соверш }, // жениться на королеве
глагол:жениться{ вид:соверш },
прилагательное:женатый{},
прилагательное:женившийся{},
rus_verbs:спрятать{}, // спрятать на чердаке
rus_verbs:развернуться{}, // развернуться на плацу
rus_verbs:строить{}, // строить на песке
rus_verbs:устроить{}, // устроить на даче тестральный вечер
rus_verbs:настаивать{}, // настаивать на выполнении приказа
rus_verbs:находить{}, // находить на берегу
rus_verbs:мелькнуть{}, // мелькнуть на экране
rus_verbs:очутиться{}, // очутиться на опушке леса
инфинитив:использовать{вид:соверш}, // использовать на работе
глагол:использовать{вид:соверш},
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
прилагательное:использованный{},
прилагательное:использующий{},
прилагательное:использовавший{},
rus_verbs:лететь{}, // лететь на воздушном шаре
rus_verbs:смеяться{}, // смеяться на сцене
rus_verbs:ездить{}, // ездить на мопеде
rus_verbs:заснуть{}, // заснуть на диване
rus_verbs:застать{}, // застать на рабочем месте
rus_verbs:очнуться{}, // очнуться на больничной койке
rus_verbs:разглядеть{}, // разглядеть на фотографии
rus_verbs:обойти{}, // обойти на вираже
rus_verbs:удержаться{}, // удержаться на троне
rus_verbs:побывать{}, // побывать на другой планете
rus_verbs:заняться{}, // заняться на выходных делом
rus_verbs:вянуть{}, // вянуть на солнце
rus_verbs:постоять{}, // постоять на голове
rus_verbs:приобрести{}, // приобрести на распродаже
rus_verbs:попасться{}, // попасться на краже
rus_verbs:продолжаться{}, // продолжаться на земле
rus_verbs:открывать{}, // открывать на арене
rus_verbs:создавать{}, // создавать на сцене
rus_verbs:обсуждать{}, // обсуждать на кухне
rus_verbs:отыскать{}, // отыскать на полу
rus_verbs:уснуть{}, // уснуть на диване
rus_verbs:задержаться{}, // задержаться на работе
rus_verbs:курить{}, // курить на свежем воздухе
rus_verbs:приподняться{}, // приподняться на локтях
rus_verbs:установить{}, // установить на вершине
rus_verbs:запереть{}, // запереть на балконе
rus_verbs:синеть{}, // синеть на воздухе
rus_verbs:убивать{}, // убивать на нейтральной территории
rus_verbs:скрываться{}, // скрываться на даче
rus_verbs:родить{}, // родить на полу
rus_verbs:описать{}, // описать на страницах книги
rus_verbs:перехватить{}, // перехватить на подлете
rus_verbs:скрывать{}, // скрывать на даче
rus_verbs:сменить{}, // сменить на посту
rus_verbs:мелькать{}, // мелькать на экране
rus_verbs:присутствовать{}, // присутствовать на мероприятии
rus_verbs:украсть{}, // украсть на рынке
rus_verbs:победить{}, // победить на ринге
rus_verbs:упомянуть{}, // упомянуть на страницах романа
rus_verbs:плыть{}, // плыть на старой лодке
rus_verbs:повиснуть{}, // повиснуть на перекладине
rus_verbs:нащупать{}, // нащупать на дне
rus_verbs:затихнуть{}, // затихнуть на дне
rus_verbs:построить{}, // построить на участке
rus_verbs:поддерживать{}, // поддерживать на поверхности
rus_verbs:заработать{}, // заработать на бирже
rus_verbs:провалиться{}, // провалиться на экзамене
rus_verbs:сохранить{}, // сохранить на диске
rus_verbs:располагаться{}, // располагаться на софе
rus_verbs:поклясться{}, // поклясться на библии
rus_verbs:сражаться{}, // сражаться на арене
rus_verbs:спускаться{}, // спускаться на дельтаплане
rus_verbs:уничтожить{}, // уничтожить на подступах
rus_verbs:изучить{}, // изучить на практике
rus_verbs:рождаться{}, // рождаться на праздниках
rus_verbs:прилететь{}, // прилететь на самолете
rus_verbs:догнать{}, // догнать на перекрестке
rus_verbs:изобразить{}, // изобразить на бумаге
rus_verbs:проехать{}, // проехать на тракторе
rus_verbs:приготовить{}, // приготовить на масле
rus_verbs:споткнуться{}, // споткнуться на полу
rus_verbs:собирать{}, // собирать на берегу
rus_verbs:отсутствовать{}, // отсутствовать на тусовке
rus_verbs:приземлиться{}, // приземлиться на военном аэродроме
rus_verbs:сыграть{}, // сыграть на трубе
rus_verbs:прятаться{}, // прятаться на даче
rus_verbs:спрятаться{}, // спрятаться на чердаке
rus_verbs:провозгласить{}, // провозгласить на митинге
rus_verbs:изложить{}, // изложить на бумаге
rus_verbs:использоваться{}, // использоваться на практике
rus_verbs:замяться{}, // замяться на входе
rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота
rus_verbs:сверкнуть{}, // сверкнуть на солнце
rus_verbs:сверкать{}, // сверкать на свету
rus_verbs:задержать{}, // задержать на митинге
rus_verbs:осечься{}, // осечься на первом слове
rus_verbs:хранить{}, // хранить на банковском счету
rus_verbs:шутить{}, // шутить на уроке
rus_verbs:кружиться{}, // кружиться на балу
rus_verbs:чертить{}, // чертить на доске
rus_verbs:отразиться{}, // отразиться на оценках
rus_verbs:греть{}, // греть на солнце
rus_verbs:рассуждать{}, // рассуждать на страницах своей книги
rus_verbs:окружать{}, // окружать на острове
rus_verbs:сопровождать{}, // сопровождать на охоте
rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте
rus_verbs:содержаться{}, // содержаться на приусадебном участке
rus_verbs:поселиться{}, // поселиться на даче
rus_verbs:запеть{}, // запеть на сцене
инфинитив:провозить{ вид:несоверш }, // провозить на теле
глагол:провозить{ вид:несоверш },
прилагательное:провезенный{},
прилагательное:провозивший{вид:несоверш},
прилагательное:провозящий{вид:несоверш},
деепричастие:провозя{},
rus_verbs:мочить{}, // мочить на месте
rus_verbs:преследовать{}, // преследовать на территории другого штата
rus_verbs:пролететь{}, // пролетел на параплане
rus_verbs:драться{}, // драться на рапирах
rus_verbs:просидеть{}, // просидеть на занятиях
rus_verbs:убираться{}, // убираться на балконе
rus_verbs:таять{}, // таять на солнце
rus_verbs:проверять{}, // проверять на полиграфе
rus_verbs:убеждать{}, // убеждать на примере
rus_verbs:скользить{}, // скользить на льду
rus_verbs:приобретать{}, // приобретать на распродаже
rus_verbs:летать{}, // летать на метле
rus_verbs:толпиться{}, // толпиться на перроне
rus_verbs:плавать{}, // плавать на надувном матрасе
rus_verbs:описывать{}, // описывать на страницах повести
rus_verbs:пробыть{}, // пробыть на солнце слишком долго
rus_verbs:застрять{}, // застрять на верхнем этаже
rus_verbs:метаться{}, // метаться на полу
rus_verbs:сжечь{}, // сжечь на костре
rus_verbs:расслабиться{}, // расслабиться на кушетке
rus_verbs:услыхать{}, // услыхать на рынке
rus_verbs:удержать{}, // удержать на прежнем уровне
rus_verbs:образоваться{}, // образоваться на дне
rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа
rus_verbs:уезжать{}, // уезжать на попутке
rus_verbs:похоронить{}, // похоронить на закрытом кладбище
rus_verbs:настоять{}, // настоять на пересмотре оценок
rus_verbs:растянуться{}, // растянуться на горячем песке
rus_verbs:покрутить{}, // покрутить на шесте
rus_verbs:обнаружиться{}, // обнаружиться на болоте
rus_verbs:гулять{}, // гулять на свадьбе
rus_verbs:утонуть{}, // утонуть на курорте
rus_verbs:храниться{}, // храниться на депозите
rus_verbs:танцевать{}, // танцевать на свадьбе
rus_verbs:трудиться{}, // трудиться на заводе
инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати
глагол:засыпать{переходность:непереходный вид:несоверш},
деепричастие:засыпая{переходность:непереходный вид:несоверш},
прилагательное:засыпавший{переходность:непереходный вид:несоверш},
прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках
rus_verbs:сушить{}, // сушить на открытом воздухе
rus_verbs:зашевелиться{}, // зашевелиться на чердаке
rus_verbs:обдумывать{}, // обдумывать на досуге
rus_verbs:докладывать{}, // докладывать на научной конференции
rus_verbs:промелькнуть{}, // промелькнуть на экране
// прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории
прилагательное:написанный{}, // слово, написанное на заборе
rus_verbs:умещаться{}, // компьютер, умещающийся на ладони
rus_verbs:открыть{}, // книга, открытая на последней странице
rus_verbs:спать{}, // йог, спящий на гвоздях
rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте
rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте
rus_verbs:отобразиться{}, // удивление, отобразившееся на лице
rus_verbs:увидеть{}, // на полу я увидел чьи-то следы
rus_verbs:видеть{}, // на полу я вижу чьи-то следы
rus_verbs:оставить{}, // Мел оставил на доске белый след.
rus_verbs:оставлять{}, // Мел оставляет на доске белый след.
rus_verbs:встречаться{}, // встречаться на лекциях
rus_verbs:познакомиться{}, // познакомиться на занятиях
rus_verbs:устроиться{}, // она устроилась на кровати
rus_verbs:ложиться{}, // ложись на полу
rus_verbs:останавливаться{}, // останавливаться на достигнутом
rus_verbs:спотыкаться{}, // спотыкаться на ровном месте
rus_verbs:распечатать{}, // распечатать на бумаге
rus_verbs:распечатывать{}, // распечатывать на бумаге
rus_verbs:просмотреть{}, // просмотреть на бумаге
rus_verbs:закрепляться{}, // закрепляться на плацдарме
rus_verbs:погреться{}, // погреться на солнышке
rus_verbs:мешать{}, // Он мешал краски на палитре.
rus_verbs:занять{}, // Он занял первое место на соревнованиях.
rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках.
деепричастие:женившись{ вид:соверш },
rus_verbs:везти{}, // Он везёт песок на тачке.
прилагательное:казненный{}, // Он был казнён на электрическом стуле.
rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче.
rus_verbs:принести{}, // Официантка принесла нам обед на подносе.
rus_verbs:переписать{}, // Перепишите эту рукопись на машинке.
rus_verbs:идти{}, // Поезд идёт на малой скорости.
rus_verbs:петь{}, // птички поют на рассвете
rus_verbs:смотреть{}, // Смотри на обороте.
rus_verbs:прибрать{}, // прибрать на столе
rus_verbs:прибраться{}, // прибраться на столе
rus_verbs:растить{}, // растить капусту на огороде
rus_verbs:тащить{}, // тащить ребенка на руках
rus_verbs:убирать{}, // убирать на столе
rus_verbs:простыть{}, // Я простыл на морозе.
rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе.
rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде
rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках.
rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге.
rus_verbs:вскочить{}, // У него вскочил прыщ на носу.
rus_verbs:свить{}, // У нас на балконе воробей свил гнездо.
rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица.
rus_verbs:восходить{}, // Солнце восходит на востоке.
rus_verbs:блестеть{}, // Снег блестит на солнце.
rus_verbs:побить{}, // Рысак побил всех лошадей на скачках.
rus_verbs:литься{}, // Реки крови льются на войне.
rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах.
rus_verbs:клубиться{}, // Пыль клубится на дороге.
инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке
глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке.
// глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути
// инфинитив:находиться{вид:несоверш},
rus_verbs:жить{}, // Было интересно жить на курорте.
rus_verbs:повидать{}, // Он много повидал на своём веку.
rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду.
rus_verbs:расположиться{}, // Оба села расположились на берегу реки.
rus_verbs:объясняться{}, // Они объясняются на иностранном языке.
rus_verbs:прощаться{}, // Они долго прощались на вокзале.
rus_verbs:работать{}, // Она работает на ткацкой фабрике.
rus_verbs:купить{}, // Она купила молоко на рынке.
rus_verbs:поместиться{}, // Все книги поместились на полке.
глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике.
rus_verbs:пожить{}, // Недолго она пожила на свете.
rus_verbs:краснеть{}, // Небо краснеет на закате.
rus_verbs:бывать{}, // На Волге бывает сильное волнение.
rus_verbs:ехать{}, // Мы туда ехали на автобусе.
rus_verbs:провести{}, // Мы провели месяц на даче.
rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице.
rus_verbs:расти{}, // Арбузы растут теперь не только на юге.
ГЛ_ИНФ(сидеть), // три больших пса сидят на траве
ГЛ_ИНФ(сесть), // три больших пса сели на траву
ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль
ГЛ_ИНФ(повезти), // я повезу тебя на машине
ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси
ГЛ_ИНФ(пить), // пить на кухне чай
ГЛ_ИНФ(найти), // найти на острове
ГЛ_ИНФ(быть), // на этих костях есть следы зубов
ГЛ_ИНФ(высадиться), // помощники высадились на острове
ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове
ГЛ_ИНФ(случиться), // это случилось на опушке леса
ГЛ_ИНФ(продать),
ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: смотреть на youtube
fact гл_предл
{
if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
// локатив
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
#endregion ПРЕДЛОЖНЫЙ
#region ВИНИТЕЛЬНЫЙ
// НА+винительный падеж:
// ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ
#region VerbList
wordentry_set Гл_НА_Вин=
{
rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили.
rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку.
rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай.
rus_verbs:умножить{}, // Умножьте это количество примерно на 10.
//rus_verbs:умножать{},
rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу.
rus_verbs:откатывать{},
rus_verbs:доносить{}, // Вот и побежали на вас доносить.
rus_verbs:донести{},
rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
безлич_глагол:хватит{}, // - На одну атаку хватит.
rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты.
rus_verbs:поскупиться{}, // Не поскупись на похвалы!
rus_verbs:подыматься{},
rus_verbs:транспортироваться{},
rus_verbs:бахнуть{}, // Бахнуть стакан на пол
rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ)
rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ)
rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ)
rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ)
rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ)
rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ)
rus_verbs:БРЫЗГАТЬ{},
rus_verbs:БРЫЗНУТЬ{},
rus_verbs:КАПНУТЬ{},
rus_verbs:КАПАТЬ{},
rus_verbs:ПОКАПАТЬ{},
rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ)
rus_verbs:ОХОТИТЬСЯ{}, //
rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ)
rus_verbs:НАРВАТЬСЯ{}, //
rus_verbs:НАТОЛКНУТЬСЯ{}, //
rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ)
прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ)
rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ)
rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ)
rus_verbs:СТАЛКИВАТЬ{}, //
rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ)
rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ)
rus_verbs:ПЕРЕБРОСИТЬ{}, //
rus_verbs:НАБРАСЫВАТЬ{}, //
rus_verbs:НАБРОСИТЬ{}, //
rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ)
rus_verbs:СВОРАЧИВАТЬ{}, // //
rus_verbs:ПОВЕРНУТЬ{}, //
rus_verbs:ПОВОРАЧИВАТЬ{}, //
rus_verbs:наорать{},
rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ)
rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ)
rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:перегонять{},
rus_verbs:выгонять{},
rus_verbs:выгнать{},
rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ)
rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ)
rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ)
rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ)
rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций
rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин)
rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА)
// rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА)
rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА)
rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин)
rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА)
rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА)
rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин)
rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА)
rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА)
прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА)
rus_verbs:посыпаться{}, // на Нину посыпались снежинки
инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод.
глагол:нарезаться{ вид:несоверш },
rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу
rus_verbs:показать{}, // Вадим показал на Колю
rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА)
rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на)
rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА)
rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА)
rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на)
rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА)
rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА)
rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на)
rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на)
rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на)
rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на)
rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на)
rus_verbs:верить{}, // верить людям на слово (верить на слово)
rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру.
rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору.
rus_verbs:пасть{}, // Жребий пал на меня.
rus_verbs:ездить{}, // Вчера мы ездили на оперу.
rus_verbs:влезть{}, // Мальчик влез на дерево.
rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу.
rus_verbs:разбиться{}, // окно разбилось на мелкие осколки
rus_verbs:бежать{}, // я бегу на урок
rus_verbs:сбегаться{}, // сбегаться на происшествие
rus_verbs:присылать{}, // присылать на испытание
rus_verbs:надавить{}, // надавить на педать
rus_verbs:внести{}, // внести законопроект на рассмотрение
rus_verbs:вносить{}, // вносить законопроект на рассмотрение
rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов
rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров
rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова
rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек.
rus_verbs:оглядываться{}, // оглядываться на девушек
rus_verbs:расходиться{}, // расходиться на отдых
rus_verbs:поскакать{}, // поскакать на службу
rus_verbs:прыгать{}, // прыгать на сцену
rus_verbs:приглашать{}, // приглашать на обед
rus_verbs:рваться{}, // Кусок ткани рвется на части
rus_verbs:понестись{}, // понестись на волю
rus_verbs:распространяться{}, // распространяться на всех жителей штата
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш },
деепричастие:просыпавшись{}, деепричастие:просыпаясь{},
rus_verbs:заехать{}, // заехать на пандус
rus_verbs:разобрать{}, // разобрать на составляющие
rus_verbs:опускаться{}, // опускаться на колени
rus_verbs:переехать{}, // переехать на конспиративную квартиру
rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов
rus_verbs:поместить{}, // поместить на поднос
rus_verbs:отходить{}, // отходить на подготовленные позиции
rus_verbs:сыпаться{}, // сыпаться на плечи
rus_verbs:отвезти{}, // отвезти на занятия
rus_verbs:накинуть{}, // накинуть на плечи
rus_verbs:отлететь{}, // отлететь на пол
rus_verbs:закинуть{}, // закинуть на чердак
rus_verbs:зашипеть{}, // зашипеть на собаку
rus_verbs:прогреметь{}, // прогреметь на всю страну
rus_verbs:повалить{}, // повалить на стол
rus_verbs:опереть{}, // опереть на фундамент
rus_verbs:забросить{}, // забросить на антресоль
rus_verbs:подействовать{}, // подействовать на материал
rus_verbs:разделять{}, // разделять на части
rus_verbs:прикрикнуть{}, // прикрикнуть на детей
rus_verbs:разложить{}, // разложить на множители
rus_verbs:провожать{}, // провожать на работу
rus_verbs:катить{}, // катить на стройку
rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью
rus_verbs:сохранять{}, // сохранять на память
rus_verbs:злиться{}, // злиться на друга
rus_verbs:оборачиваться{}, // оборачиваться на свист
rus_verbs:сползти{}, // сползти на землю
rus_verbs:записывать{}, // записывать на ленту
rus_verbs:загнать{}, // загнать на дерево
rus_verbs:забормотать{}, // забормотать на ухо
rus_verbs:протиснуться{}, // протиснуться на самый край
rus_verbs:заторопиться{}, // заторопиться на вручение премии
rus_verbs:гаркнуть{}, // гаркнуть на шалунов
rus_verbs:навалиться{}, // навалиться на виновника всей толпой
rus_verbs:проскользнуть{}, // проскользнуть на крышу дома
rus_verbs:подтянуть{}, // подтянуть на палубу
rus_verbs:скатиться{}, // скатиться на двойки
rus_verbs:давить{}, // давить на жалость
rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства
rus_verbs:замахнуться{}, // замахнуться на святое
rus_verbs:заменить{}, // заменить на свежую салфетку
rus_verbs:свалить{}, // свалить на землю
rus_verbs:стекать{}, // стекать на оголенные провода
rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов
rus_verbs:развалиться{}, // развалиться на части
rus_verbs:сердиться{}, // сердиться на товарища
rus_verbs:обронить{}, // обронить на пол
rus_verbs:подсесть{}, // подсесть на наркоту
rus_verbs:реагировать{}, // реагировать на импульсы
rus_verbs:отпускать{}, // отпускать на волю
rus_verbs:прогнать{}, // прогнать на рабочее место
rus_verbs:ложить{}, // ложить на стол
rus_verbs:рвать{}, // рвать на части
rus_verbs:разлететься{}, // разлететься на кусочки
rus_verbs:превышать{}, // превышать на существенную величину
rus_verbs:сбиться{}, // сбиться на рысь
rus_verbs:пристроиться{}, // пристроиться на хорошую работу
rus_verbs:удрать{}, // удрать на пастбище
rus_verbs:толкать{}, // толкать на преступление
rus_verbs:посматривать{}, // посматривать на экран
rus_verbs:набирать{}, // набирать на судно
rus_verbs:отступать{}, // отступать на дерево
rus_verbs:подуть{}, // подуть на молоко
rus_verbs:плеснуть{}, // плеснуть на голову
rus_verbs:соскользнуть{}, // соскользнуть на землю
rus_verbs:затаить{}, // затаить на кого-то обиду
rus_verbs:обижаться{}, // обижаться на Колю
rus_verbs:смахнуть{}, // смахнуть на пол
rus_verbs:застегнуть{}, // застегнуть на все пуговицы
rus_verbs:спускать{}, // спускать на землю
rus_verbs:греметь{}, // греметь на всю округу
rus_verbs:скосить{}, // скосить на соседа глаз
rus_verbs:отважиться{}, // отважиться на прыжок
rus_verbs:литься{}, // литься на землю
rus_verbs:порвать{}, // порвать на тряпки
rus_verbs:проследовать{}, // проследовать на сцену
rus_verbs:надевать{}, // надевать на голову
rus_verbs:проскочить{}, // проскочить на красный свет
rus_verbs:прилечь{}, // прилечь на диванчик
rus_verbs:разделиться{}, // разделиться на небольшие группы
rus_verbs:завыть{}, // завыть на луну
rus_verbs:переносить{}, // переносить на другую машину
rus_verbs:наговорить{}, // наговорить на сотню рублей
rus_verbs:намекать{}, // намекать на новые обстоятельства
rus_verbs:нападать{}, // нападать на охранников
rus_verbs:убегать{}, // убегать на другое место
rus_verbs:тратить{}, // тратить на развлечения
rus_verbs:присаживаться{}, // присаживаться на корточки
rus_verbs:переместиться{}, // переместиться на вторую линию
rus_verbs:завалиться{}, // завалиться на диван
rus_verbs:удалиться{}, // удалиться на покой
rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов
rus_verbs:обрушить{}, // обрушить на голову
rus_verbs:резать{}, // резать на части
rus_verbs:умчаться{}, // умчаться на юг
rus_verbs:навернуться{}, // навернуться на камень
rus_verbs:примчаться{}, // примчаться на матч
rus_verbs:издавать{}, // издавать на собственные средства
rus_verbs:переключить{}, // переключить на другой язык
rus_verbs:отправлять{}, // отправлять на пенсию
rus_verbs:залечь{}, // залечь на дно
rus_verbs:установиться{}, // установиться на диск
rus_verbs:направлять{}, // направлять на дополнительное обследование
rus_verbs:разрезать{}, // разрезать на части
rus_verbs:оскалиться{}, // оскалиться на прохожего
rus_verbs:рычать{}, // рычать на пьяных
rus_verbs:погружаться{}, // погружаться на дно
rus_verbs:опираться{}, // опираться на костыли
rus_verbs:поторопиться{}, // поторопиться на учебу
rus_verbs:сдвинуться{}, // сдвинуться на сантиметр
rus_verbs:увеличить{}, // увеличить на процент
rus_verbs:опускать{}, // опускать на землю
rus_verbs:созвать{}, // созвать на митинг
rus_verbs:делить{}, // делить на части
rus_verbs:пробиться{}, // пробиться на заключительную часть
rus_verbs:простираться{}, // простираться на много миль
rus_verbs:забить{}, // забить на учебу
rus_verbs:переложить{}, // переложить на чужие плечи
rus_verbs:грохнуться{}, // грохнуться на землю
rus_verbs:прорваться{}, // прорваться на сцену
rus_verbs:разлить{}, // разлить на землю
rus_verbs:укладываться{}, // укладываться на ночевку
rus_verbs:уволить{}, // уволить на пенсию
rus_verbs:наносить{}, // наносить на кожу
rus_verbs:набежать{}, // набежать на берег
rus_verbs:заявиться{}, // заявиться на стрельбище
rus_verbs:налиться{}, // налиться на крышку
rus_verbs:надвигаться{}, // надвигаться на берег
rus_verbs:распустить{}, // распустить на каникулы
rus_verbs:переключиться{}, // переключиться на другую задачу
rus_verbs:чихнуть{}, // чихнуть на окружающих
rus_verbs:шлепнуться{}, // шлепнуться на спину
rus_verbs:устанавливать{}, // устанавливать на крышу
rus_verbs:устанавливаться{}, // устанавливаться на крышу
rus_verbs:устраиваться{}, // устраиваться на работу
rus_verbs:пропускать{}, // пропускать на стадион
инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш },
деепричастие:сбегав{}, деепричастие:сбегая{},
rus_verbs:показываться{}, // показываться на глаза
rus_verbs:прибегать{}, // прибегать на урок
rus_verbs:съездить{}, // съездить на ферму
rus_verbs:прославиться{}, // прославиться на всю страну
rus_verbs:опрокинуться{}, // опрокинуться на спину
rus_verbs:насыпать{}, // насыпать на землю
rus_verbs:употреблять{}, // употреблять на корм скоту
rus_verbs:пристроить{}, // пристроить на работу
rus_verbs:заворчать{}, // заворчать на вошедшего
rus_verbs:завязаться{}, // завязаться на поставщиков
rus_verbs:сажать{}, // сажать на стул
rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры
rus_verbs:заменять{}, // заменять на исправную
rus_verbs:нацепить{}, // нацепить на голову
rus_verbs:сыпать{}, // сыпать на землю
rus_verbs:закрываться{}, // закрываться на ремонт
rus_verbs:распространиться{}, // распространиться на всю популяцию
rus_verbs:поменять{}, // поменять на велосипед
rus_verbs:пересесть{}, // пересесть на велосипеды
rus_verbs:подоспеть{}, // подоспеть на разбор
rus_verbs:шипеть{}, // шипеть на собак
rus_verbs:поделить{}, // поделить на части
rus_verbs:подлететь{}, // подлететь на расстояние выстрела
rus_verbs:нажимать{}, // нажимать на все кнопки
rus_verbs:распасться{}, // распасться на части
rus_verbs:приволочь{}, // приволочь на диван
rus_verbs:пожить{}, // пожить на один доллар
rus_verbs:устремляться{}, // устремляться на свободу
rus_verbs:смахивать{}, // смахивать на пол
rus_verbs:забежать{}, // забежать на обед
rus_verbs:увеличиться{}, // увеличиться на существенную величину
rus_verbs:прокрасться{}, // прокрасться на склад
rus_verbs:пущать{}, // пущать на постой
rus_verbs:отклонить{}, // отклонить на несколько градусов
rus_verbs:насмотреться{}, // насмотреться на безобразия
rus_verbs:настроить{}, // настроить на короткие волны
rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров
rus_verbs:поменяться{}, // поменяться на другую книжку
rus_verbs:расколоться{}, // расколоться на части
rus_verbs:разлиться{}, // разлиться на землю
rus_verbs:срываться{}, // срываться на жену
rus_verbs:осудить{}, // осудить на пожизненное заключение
rus_verbs:передвинуть{}, // передвинуть на первое место
rus_verbs:допускаться{}, // допускаться на полигон
rus_verbs:задвинуть{}, // задвинуть на полку
rus_verbs:повлиять{}, // повлиять на оценку
rus_verbs:отбавлять{}, // отбавлять на осмотр
rus_verbs:сбрасывать{}, // сбрасывать на землю
rus_verbs:накинуться{}, // накинуться на случайных прохожих
rus_verbs:пролить{}, // пролить на кожу руки
rus_verbs:затащить{}, // затащить на сеновал
rus_verbs:перебежать{}, // перебежать на сторону противника
rus_verbs:наливать{}, // наливать на скатерть
rus_verbs:пролезть{}, // пролезть на сцену
rus_verbs:откладывать{}, // откладывать на черный день
rus_verbs:распадаться{}, // распадаться на небольшие фрагменты
rus_verbs:перечислить{}, // перечислить на счет
rus_verbs:закачаться{}, // закачаться на верхний уровень
rus_verbs:накрениться{}, // накрениться на правый борт
rus_verbs:подвинуться{}, // подвинуться на один уровень
rus_verbs:разнести{}, // разнести на мелкие кусочки
rus_verbs:зажить{}, // зажить на широкую ногу
rus_verbs:оглохнуть{}, // оглохнуть на правое ухо
rus_verbs:посетовать{}, // посетовать на бюрократизм
rus_verbs:уводить{}, // уводить на осмотр
rus_verbs:ускакать{}, // ускакать на забег
rus_verbs:посветить{}, // посветить на стену
rus_verbs:разрываться{}, // разрываться на части
rus_verbs:побросать{}, // побросать на землю
rus_verbs:карабкаться{}, // карабкаться на скалу
rus_verbs:нахлынуть{}, // нахлынуть на кого-то
rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки
rus_verbs:среагировать{}, // среагировать на сигнал
rus_verbs:претендовать{}, // претендовать на приз
rus_verbs:дунуть{}, // дунуть на одуванчик
rus_verbs:переводиться{}, // переводиться на другую работу
rus_verbs:перевезти{}, // перевезти на другую площадку
rus_verbs:топать{}, // топать на урок
rus_verbs:относить{}, // относить на склад
rus_verbs:сбивать{}, // сбивать на землю
rus_verbs:укладывать{}, // укладывать на спину
rus_verbs:укатить{}, // укатить на отдых
rus_verbs:убирать{}, // убирать на полку
rus_verbs:опасть{}, // опасть на землю
rus_verbs:ронять{}, // ронять на снег
rus_verbs:пялиться{}, // пялиться на тело
rus_verbs:глазеть{}, // глазеть на тело
rus_verbs:снижаться{}, // снижаться на безопасную высоту
rus_verbs:запрыгнуть{}, // запрыгнуть на платформу
rus_verbs:разбиваться{}, // разбиваться на главы
rus_verbs:сгодиться{}, // сгодиться на фарш
rus_verbs:перескочить{}, // перескочить на другую страницу
rus_verbs:нацелиться{}, // нацелиться на главную добычу
rus_verbs:заезжать{}, // заезжать на бордюр
rus_verbs:забираться{}, // забираться на крышу
rus_verbs:проорать{}, // проорать на всё село
rus_verbs:сбежаться{}, // сбежаться на шум
rus_verbs:сменять{}, // сменять на хлеб
rus_verbs:мотать{}, // мотать на ус
rus_verbs:раскалываться{}, // раскалываться на две половинки
rus_verbs:коситься{}, // коситься на режиссёра
rus_verbs:плевать{}, // плевать на законы
rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение
rus_verbs:наставить{}, // наставить на путь истинный
rus_verbs:завывать{}, // завывать на Луну
rus_verbs:опаздывать{}, // опаздывать на совещание
rus_verbs:залюбоваться{}, // залюбоваться на пейзаж
rus_verbs:повергнуть{}, // повергнуть на землю
rus_verbs:надвинуть{}, // надвинуть на лоб
rus_verbs:стекаться{}, // стекаться на площадь
rus_verbs:обозлиться{}, // обозлиться на тренера
rus_verbs:оттянуть{}, // оттянуть на себя
rus_verbs:истратить{}, // истратить на дешевых шлюх
rus_verbs:вышвырнуть{}, // вышвырнуть на улицу
rus_verbs:затолкать{}, // затолкать на верхнюю полку
rus_verbs:заскочить{}, // заскочить на огонек
rus_verbs:проситься{}, // проситься на улицу
rus_verbs:натыкаться{}, // натыкаться на борщевик
rus_verbs:обрушиваться{}, // обрушиваться на митингующих
rus_verbs:переписать{}, // переписать на чистовик
rus_verbs:переноситься{}, // переноситься на другое устройство
rus_verbs:напроситься{}, // напроситься на обидный ответ
rus_verbs:натягивать{}, // натягивать на ноги
rus_verbs:кидаться{}, // кидаться на прохожих
rus_verbs:откликаться{}, // откликаться на призыв
rus_verbs:поспевать{}, // поспевать на балет
rus_verbs:обратиться{}, // обратиться на кафедру
rus_verbs:полюбоваться{}, // полюбоваться на бюст
rus_verbs:таращиться{}, // таращиться на мустангов
rus_verbs:напороться{}, // напороться на колючки
rus_verbs:раздать{}, // раздать на руки
rus_verbs:дивиться{}, // дивиться на танцовщиц
rus_verbs:назначать{}, // назначать на ответственнейший пост
rus_verbs:кидать{}, // кидать на балкон
rus_verbs:нахлобучить{}, // нахлобучить на башку
rus_verbs:увлекать{}, // увлекать на луг
rus_verbs:ругнуться{}, // ругнуться на животину
rus_verbs:переселиться{}, // переселиться на хутор
rus_verbs:разрывать{}, // разрывать на части
rus_verbs:утащить{}, // утащить на дерево
rus_verbs:наставлять{}, // наставлять на путь
rus_verbs:соблазнить{}, // соблазнить на обмен
rus_verbs:накладывать{}, // накладывать на рану
rus_verbs:набрести{}, // набрести на грибную поляну
rus_verbs:наведываться{}, // наведываться на прежнюю работу
rus_verbs:погулять{}, // погулять на чужие деньги
rus_verbs:уклоняться{}, // уклоняться на два градуса влево
rus_verbs:слезать{}, // слезать на землю
rus_verbs:клевать{}, // клевать на мотыля
// rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:напялить{}, // напялить на голову
rus_verbs:натянуться{}, // натянуться на рамку
rus_verbs:разгневаться{}, // разгневаться на придворных
rus_verbs:эмигрировать{}, // эмигрировать на Кипр
rus_verbs:накатить{}, // накатить на основу
rus_verbs:пригнать{}, // пригнать на пастбище
rus_verbs:обречь{}, // обречь на мучения
rus_verbs:сокращаться{}, // сокращаться на четверть
rus_verbs:оттеснить{}, // оттеснить на пристань
rus_verbs:подбить{}, // подбить на аферу
rus_verbs:заманить{}, // заманить на дерево
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик
// деепричастие:пописав{ aux stress="поп^исать" },
rus_verbs:посходить{}, // посходить на перрон
rus_verbs:налечь{}, // налечь на мясцо
rus_verbs:отбирать{}, // отбирать на флот
rus_verbs:нашептывать{}, // нашептывать на ухо
rus_verbs:откладываться{}, // откладываться на будущее
rus_verbs:залаять{}, // залаять на грабителя
rus_verbs:настроиться{}, // настроиться на прием
rus_verbs:разбивать{}, // разбивать на куски
rus_verbs:пролиться{}, // пролиться на почву
rus_verbs:сетовать{}, // сетовать на объективные трудности
rus_verbs:подвезти{}, // подвезти на митинг
rus_verbs:припереться{}, // припереться на праздник
rus_verbs:подталкивать{}, // подталкивать на прыжок
rus_verbs:прорываться{}, // прорываться на сцену
rus_verbs:снижать{}, // снижать на несколько процентов
rus_verbs:нацелить{}, // нацелить на танк
rus_verbs:расколоть{}, // расколоть на два куска
rus_verbs:увозить{}, // увозить на обкатку
rus_verbs:оседать{}, // оседать на дно
rus_verbs:съедать{}, // съедать на ужин
rus_verbs:навлечь{}, // навлечь на себя
rus_verbs:равняться{}, // равняться на лучших
rus_verbs:сориентироваться{}, // сориентироваться на местности
rus_verbs:снизить{}, // снизить на несколько процентов
rus_verbs:перенестись{}, // перенестись на много лет назад
rus_verbs:завезти{}, // завезти на склад
rus_verbs:проложить{}, // проложить на гору
rus_verbs:понадеяться{}, // понадеяться на удачу
rus_verbs:заступить{}, // заступить на вахту
rus_verbs:засеменить{}, // засеменить на выход
rus_verbs:запирать{}, // запирать на ключ
rus_verbs:скатываться{}, // скатываться на землю
rus_verbs:дробить{}, // дробить на части
rus_verbs:разваливаться{}, // разваливаться на кусочки
rus_verbs:завозиться{}, // завозиться на склад
rus_verbs:нанимать{}, // нанимать на дневную работу
rus_verbs:поспеть{}, // поспеть на концерт
rus_verbs:променять{}, // променять на сытость
rus_verbs:переправить{}, // переправить на север
rus_verbs:налетать{}, // налетать на силовое поле
rus_verbs:затворить{}, // затворить на замок
rus_verbs:подогнать{}, // подогнать на пристань
rus_verbs:наехать{}, // наехать на камень
rus_verbs:распевать{}, // распевать на разные голоса
rus_verbs:разносить{}, // разносить на клочки
rus_verbs:преувеличивать{}, // преувеличивать на много килограммов
rus_verbs:хромать{}, // хромать на одну ногу
rus_verbs:телеграфировать{}, // телеграфировать на базу
rus_verbs:порезать{}, // порезать на лоскуты
rus_verbs:порваться{}, // порваться на части
rus_verbs:загонять{}, // загонять на дерево
rus_verbs:отбывать{}, // отбывать на место службы
rus_verbs:усаживаться{}, // усаживаться на трон
rus_verbs:накопить{}, // накопить на квартиру
rus_verbs:зыркнуть{}, // зыркнуть на визитера
rus_verbs:копить{}, // копить на машину
rus_verbs:помещать{}, // помещать на верхнюю грань
rus_verbs:сползать{}, // сползать на снег
rus_verbs:попроситься{}, // попроситься на улицу
rus_verbs:перетащить{}, // перетащить на чердак
rus_verbs:растащить{}, // растащить на сувениры
rus_verbs:ниспадать{}, // ниспадать на землю
rus_verbs:сфотографировать{}, // сфотографировать на память
rus_verbs:нагонять{}, // нагонять на конкурентов страх
rus_verbs:покушаться{}, // покушаться на понтифика
rus_verbs:покуситься{},
rus_verbs:наняться{}, // наняться на службу
rus_verbs:просачиваться{}, // просачиваться на поверхность
rus_verbs:пускаться{}, // пускаться на ветер
rus_verbs:отваживаться{}, // отваживаться на прыжок
rus_verbs:досадовать{}, // досадовать на объективные трудности
rus_verbs:унестись{}, // унестись на небо
rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов
rus_verbs:насадить{}, // насадить на копьё
rus_verbs:нагрянуть{}, // нагрянуть на праздник
rus_verbs:зашвырнуть{}, // зашвырнуть на полку
rus_verbs:грешить{}, // грешить на постояльцев
rus_verbs:просочиться{}, // просочиться на поверхность
rus_verbs:надоумить{}, // надоумить на глупость
rus_verbs:намотать{}, // намотать на шпиндель
rus_verbs:замкнуть{}, // замкнуть на корпус
rus_verbs:цыкнуть{}, // цыкнуть на детей
rus_verbs:переворачиваться{}, // переворачиваться на спину
rus_verbs:соваться{}, // соваться на площать
rus_verbs:отлучиться{}, // отлучиться на обед
rus_verbs:пенять{}, // пенять на себя
rus_verbs:нарезать{}, // нарезать на ломтики
rus_verbs:поставлять{}, // поставлять на Кипр
rus_verbs:залезать{}, // залезать на балкон
rus_verbs:отлучаться{}, // отлучаться на обед
rus_verbs:сбиваться{}, // сбиваться на шаг
rus_verbs:таращить{}, // таращить глаза на вошедшего
rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню
rus_verbs:опережать{}, // опережать на пару сантиметров
rus_verbs:переставить{}, // переставить на стол
rus_verbs:раздирать{}, // раздирать на части
rus_verbs:затвориться{}, // затвориться на засовы
rus_verbs:материться{}, // материться на кого-то
rus_verbs:наскочить{}, // наскочить на риф
rus_verbs:набираться{}, // набираться на борт
rus_verbs:покрикивать{}, // покрикивать на помощников
rus_verbs:заменяться{}, // заменяться на более новый
rus_verbs:подсадить{}, // подсадить на верхнюю полку
rus_verbs:проковылять{}, // проковылять на кухню
rus_verbs:прикатить{}, // прикатить на старт
rus_verbs:залететь{}, // залететь на чужую территорию
rus_verbs:загрузить{}, // загрузить на конвейер
rus_verbs:уплывать{}, // уплывать на материк
rus_verbs:опозорить{}, // опозорить на всю деревню
rus_verbs:провоцировать{}, // провоцировать на ответную агрессию
rus_verbs:забивать{}, // забивать на учебу
rus_verbs:набегать{}, // набегать на прибрежные деревни
rus_verbs:запираться{}, // запираться на ключ
rus_verbs:фотографировать{}, // фотографировать на мыльницу
rus_verbs:подымать{}, // подымать на недосягаемую высоту
rus_verbs:съезжаться{}, // съезжаться на симпозиум
rus_verbs:отвлекаться{}, // отвлекаться на игру
rus_verbs:проливать{}, // проливать на брюки
rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца
rus_verbs:уползти{}, // уползти на вершину холма
rus_verbs:переместить{}, // переместить на вторую палубу
rus_verbs:превысить{}, // превысить на несколько метров
rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку
rus_verbs:спровоцировать{}, // спровоцировать на бросок
rus_verbs:сместиться{}, // сместиться на соседнюю клетку
rus_verbs:заготовить{}, // заготовить на зиму
rus_verbs:плеваться{}, // плеваться на пол
rus_verbs:переселить{}, // переселить на север
rus_verbs:напирать{}, // напирать на дверь
rus_verbs:переезжать{}, // переезжать на другой этаж
rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров
rus_verbs:трогаться{}, // трогаться на красный свет
rus_verbs:надвинуться{}, // надвинуться на глаза
rus_verbs:засмотреться{}, // засмотреться на купальники
rus_verbs:убыть{}, // убыть на фронт
rus_verbs:передвигать{}, // передвигать на второй уровень
rus_verbs:отвозить{}, // отвозить на свалку
rus_verbs:обрекать{}, // обрекать на гибель
rus_verbs:записываться{}, // записываться на танцы
rus_verbs:настраивать{}, // настраивать на другой диапазон
rus_verbs:переписывать{}, // переписывать на диск
rus_verbs:израсходовать{}, // израсходовать на гонки
rus_verbs:обменять{}, // обменять на перспективного игрока
rus_verbs:трубить{}, // трубить на всю округу
rus_verbs:набрасываться{}, // набрасываться на жертву
rus_verbs:чихать{}, // чихать на правила
rus_verbs:наваливаться{}, // наваливаться на рычаг
rus_verbs:сподобиться{}, // сподобиться на повторный анализ
rus_verbs:намазать{}, // намазать на хлеб
rus_verbs:прореагировать{}, // прореагировать на вызов
rus_verbs:зачислить{}, // зачислить на факультет
rus_verbs:наведаться{}, // наведаться на склад
rus_verbs:откидываться{}, // откидываться на спинку кресла
rus_verbs:захромать{}, // захромать на левую ногу
rus_verbs:перекочевать{}, // перекочевать на другой берег
rus_verbs:накатываться{}, // накатываться на песчаный берег
rus_verbs:приостановить{}, // приостановить на некоторое время
rus_verbs:запрятать{}, // запрятать на верхнюю полочку
rus_verbs:прихрамывать{}, // прихрамывать на правую ногу
rus_verbs:упорхнуть{}, // упорхнуть на свободу
rus_verbs:расстегивать{}, // расстегивать на пальто
rus_verbs:напуститься{}, // напуститься на бродягу
rus_verbs:накатывать{}, // накатывать на оригинал
rus_verbs:наезжать{}, // наезжать на простофилю
rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека
rus_verbs:отрядить{}, // отрядить на починку
rus_verbs:положиться{}, // положиться на главаря
rus_verbs:опрокидывать{}, // опрокидывать на голову
rus_verbs:поторапливаться{}, // поторапливаться на рейс
rus_verbs:налагать{}, // налагать на заемщика
rus_verbs:скопировать{}, // скопировать на диск
rus_verbs:опадать{}, // опадать на землю
rus_verbs:купиться{}, // купиться на посулы
rus_verbs:гневаться{}, // гневаться на слуг
rus_verbs:слететься{}, // слететься на раздачу
rus_verbs:убавить{}, // убавить на два уровня
rus_verbs:спихнуть{}, // спихнуть на соседа
rus_verbs:накричать{}, // накричать на ребенка
rus_verbs:приберечь{}, // приберечь на ужин
rus_verbs:приклеить{}, // приклеить на ветровое стекло
rus_verbs:ополчиться{}, // ополчиться на посредников
rus_verbs:тратиться{}, // тратиться на сувениры
rus_verbs:слетаться{}, // слетаться на свет
rus_verbs:доставляться{}, // доставляться на базу
rus_verbs:поплевать{}, // поплевать на руки
rus_verbs:огрызаться{}, // огрызаться на замечание
rus_verbs:попереться{}, // попереться на рынок
rus_verbs:растягиваться{}, // растягиваться на полу
rus_verbs:повергать{}, // повергать на землю
rus_verbs:ловиться{}, // ловиться на мотыля
rus_verbs:наседать{}, // наседать на обороняющихся
rus_verbs:развалить{}, // развалить на кирпичи
rus_verbs:разломить{}, // разломить на несколько частей
rus_verbs:примерить{}, // примерить на себя
rus_verbs:лепиться{}, // лепиться на стену
rus_verbs:скопить{}, // скопить на старость
rus_verbs:затратить{}, // затратить на ликвидацию последствий
rus_verbs:притащиться{}, // притащиться на гулянку
rus_verbs:осерчать{}, // осерчать на прислугу
rus_verbs:натравить{}, // натравить на медведя
rus_verbs:ссыпать{}, // ссыпать на землю
rus_verbs:подвозить{}, // подвозить на пристань
rus_verbs:мобилизовать{}, // мобилизовать на сборы
rus_verbs:смотаться{}, // смотаться на работу
rus_verbs:заглядеться{}, // заглядеться на девчонок
rus_verbs:таскаться{}, // таскаться на работу
rus_verbs:разгружать{}, // разгружать на транспортер
rus_verbs:потреблять{}, // потреблять на кондиционирование
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу
деепричастие:сгоняв{},
rus_verbs:посылаться{}, // посылаться на разведку
rus_verbs:окрыситься{}, // окрыситься на кого-то
rus_verbs:отлить{}, // отлить на сковороду
rus_verbs:шикнуть{}, // шикнуть на детишек
rus_verbs:уповать{}, // уповать на бескорысную помощь
rus_verbs:класться{}, // класться на стол
rus_verbs:поковылять{}, // поковылять на выход
rus_verbs:навевать{}, // навевать на собравшихся скуку
rus_verbs:накладываться{}, // накладываться на грунтовку
rus_verbs:наноситься{}, // наноситься на чистую кожу
// rus_verbs:запланировать{}, // запланировать на среду
rus_verbs:кувыркнуться{}, // кувыркнуться на землю
rus_verbs:гавкнуть{}, // гавкнуть на хозяина
rus_verbs:перестроиться{}, // перестроиться на новый лад
rus_verbs:расходоваться{}, // расходоваться на образование
rus_verbs:дуться{}, // дуться на бабушку
rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол
rus_verbs:издаться{}, // издаться на деньги спонсоров
rus_verbs:смещаться{}, // смещаться на несколько миллиметров
rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу
rus_verbs:пикировать{}, // пикировать на окопы
rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей
rus_verbs:зудить{}, // зудить на ухо
rus_verbs:подразделяться{}, // подразделяться на группы
rus_verbs:изливаться{}, // изливаться на землю
rus_verbs:помочиться{}, // помочиться на траву
rus_verbs:примерять{}, // примерять на себя
rus_verbs:разрядиться{}, // разрядиться на землю
rus_verbs:мотнуться{}, // мотнуться на крышу
rus_verbs:налегать{}, // налегать на весла
rus_verbs:зацокать{}, // зацокать на куриц
rus_verbs:наниматься{}, // наниматься на корабль
rus_verbs:сплевывать{}, // сплевывать на землю
rus_verbs:настучать{}, // настучать на саботажника
rus_verbs:приземляться{}, // приземляться на брюхо
rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности
rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу
rus_verbs:серчать{}, // серчать на нерасторопную помощницу
rus_verbs:сваливать{}, // сваливать на подоконник
rus_verbs:засобираться{}, // засобираться на работу
rus_verbs:распилить{}, // распилить на одинаковые бруски
//rus_verbs:умножать{}, // умножать на константу
rus_verbs:копировать{}, // копировать на диск
rus_verbs:накрутить{}, // накрутить на руку
rus_verbs:навалить{}, // навалить на телегу
rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль
rus_verbs:шлепаться{}, // шлепаться на бетон
rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства
rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение
rus_verbs:посягнуть{}, // посягнуть на святое
rus_verbs:разменять{}, // разменять на мелочь
rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции
rus_verbs:усаживать{}, // усаживать на скамейку
rus_verbs:натаскать{}, // натаскать на поиск наркотиков
rus_verbs:зашикать{}, // зашикать на кошку
rus_verbs:разломать{}, // разломать на равные части
rus_verbs:приглашаться{}, // приглашаться на сцену
rus_verbs:присягать{}, // присягать на верность
rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку
rus_verbs:расщедриться{}, // расщедриться на новый компьютер
rus_verbs:насесть{}, // насесть на двоечников
rus_verbs:созывать{}, // созывать на собрание
rus_verbs:позариться{}, // позариться на чужое добро
rus_verbs:перекидываться{}, // перекидываться на соседние здания
rus_verbs:наползать{}, // наползать на неповрежденную ткань
rus_verbs:изрубить{}, // изрубить на мелкие кусочки
rus_verbs:наворачиваться{}, // наворачиваться на глаза
rus_verbs:раскричаться{}, // раскричаться на всю округу
rus_verbs:переползти{}, // переползти на светлую сторону
rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию
rus_verbs:мочиться{}, // мочиться на трупы убитых врагов
rus_verbs:радировать{}, // радировать на базу
rus_verbs:промотать{}, // промотать на начало
rus_verbs:заснять{}, // заснять на видео
rus_verbs:подбивать{}, // подбивать на матч-реванш
rus_verbs:наплевать{}, // наплевать на справедливость
rus_verbs:подвывать{}, // подвывать на луну
rus_verbs:расплескать{}, // расплескать на пол
rus_verbs:польститься{}, // польститься на бесплатный сыр
rus_verbs:помчать{}, // помчать на работу
rus_verbs:съезжать{}, // съезжать на обочину
rus_verbs:нашептать{}, // нашептать кому-то на ухо
rus_verbs:наклеить{}, // наклеить на доску объявлений
rus_verbs:завозить{}, // завозить на склад
rus_verbs:заявляться{}, // заявляться на любимую работу
rus_verbs:наглядеться{}, // наглядеться на воробьев
rus_verbs:хлопнуться{}, // хлопнуться на живот
rus_verbs:забредать{}, // забредать на поляну
rus_verbs:посягать{}, // посягать на исконные права собственности
rus_verbs:сдвигать{}, // сдвигать на одну позицию
rus_verbs:спрыгивать{}, // спрыгивать на землю
rus_verbs:сдвигаться{}, // сдвигаться на две позиции
rus_verbs:разделать{}, // разделать на орехи
rus_verbs:разлагать{}, // разлагать на элементарные элементы
rus_verbs:обрушивать{}, // обрушивать на головы врагов
rus_verbs:натечь{}, // натечь на пол
rus_verbs:политься{}, // вода польется на землю
rus_verbs:успеть{}, // Они успеют на поезд.
инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш },
деепричастие:мигрируя{},
инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш },
деепричастие:мигрировав{},
rus_verbs:двинуться{}, // Мы скоро двинемся на дачу.
rus_verbs:подойти{}, // Он не подойдёт на должность секретаря.
rus_verbs:потянуть{}, // Он не потянет на директора.
rus_verbs:тянуть{}, // Он не тянет на директора.
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:жаловаться{}, // Он жалуется на нездоровье.
rus_verbs:издать{}, // издать на деньги спонсоров
rus_verbs:показаться{}, // показаться на глаза
rus_verbs:высаживать{}, // высаживать на необитаемый остров
rus_verbs:вознестись{}, // вознестись на самую вершину славы
rus_verbs:залить{}, // залить на youtube
rus_verbs:закачать{}, // закачать на youtube
rus_verbs:сыграть{}, // сыграть на деньги
rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных
инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных
глагол:экстраполироваться{ вид:несоверш},
инфинитив:экстраполироваться{ вид:соверш},
глагол:экстраполироваться{ вид:соверш},
деепричастие:экстраполируясь{},
инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы
глагол:акцентировать{вид:соверш},
инфинитив:акцентировать{вид:несоверш},
глагол:акцентировать{вид:несоверш},
прилагательное:акцентировавший{вид:несоверш},
//прилагательное:акцентировавший{вид:соверш},
прилагательное:акцентирующий{},
деепричастие:акцентировав{},
деепричастие:акцентируя{},
rus_verbs:бабахаться{}, // он бабахался на пол
rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт
rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина
rus_verbs:бахаться{}, // Наездники бахались на землю
rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю
rus_verbs:благословить{}, // батюшка благословил отрока на подвиг
rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг
rus_verbs:блевануть{}, // Он блеванул на землю
rus_verbs:блевать{}, // Он блюет на землю
rus_verbs:бухнуться{}, // Наездник бухнулся на землю
rus_verbs:валить{}, // Ветер валил деревья на землю
rus_verbs:спилить{}, // Спиленное дерево валится на землю
rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню
rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес
rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход
rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес
rus_verbs:вестись{}, // Не ведись на эти уловки!
rus_verbs:вешать{}, // Гости вешают одежду на вешалку
rus_verbs:вешаться{}, // Одежда вешается на вешалки
rus_verbs:вещать{}, // радиостанция вещает на всю страну
rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм
rus_verbs:взбредать{}, // Что иногда взбредает на ум
rus_verbs:взбрести{}, // Что-то взбрело на ум
rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство
rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи
rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи
rus_verbs:взглянуть{}, // Кошка взглянула на мышку
rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол
rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол
rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол
rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул
rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект
rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух
rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух
rus_verbs:взобраться{}, // Туристы взобрались на гору
rus_verbs:взойти{}, // Туристы взошли на гору
rus_verbs:взъесться{}, // Отец взъелся на непутевого сына
rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына
rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус
rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус
rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка
rus_verbs:водворить{}, // водворить нарушителя на место
rus_verbs:водвориться{}, // водвориться на свое место
rus_verbs:водворять{}, // водворять вещь на свое место
rus_verbs:водворяться{}, // водворяться на свое место
rus_verbs:водружать{}, // водружать флаг на флагшток
rus_verbs:водружаться{}, // Флаг водружается на флагшток
rus_verbs:водрузить{}, // водрузить флаг на флагшток
rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы
rus_verbs:воздействовать{}, // Излучение воздействует на кожу
rus_verbs:воззреть{}, // воззреть на поле боя
rus_verbs:воззриться{}, // воззриться на поле боя
rus_verbs:возить{}, // возить туристов на гору
rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу
rus_verbs:возлагаться{}, // Ответственность возлагается на начальство
rus_verbs:возлечь{}, // возлечь на лежанку
rus_verbs:возложить{}, // возложить цветы на могилу поэта
rus_verbs:вознести{}, // вознести кого-то на вершину славы
rus_verbs:возноситься{}, // возносится на вершину успеха
rus_verbs:возносить{}, // возносить счастливчика на вершину успеха
rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж
rus_verbs:подняться{}, // Мы поднялись на восьмой этаж
rus_verbs:вонять{}, // Кусок сыра воняет на всю округу
rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги
rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги
rus_verbs:ворчать{}, // Старый пес ворчит на прохожих
rus_verbs:воспринимать{}, // воспринимать сообщение на слух
rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух
rus_verbs:воспринять{}, // воспринять сообщение на слух
rus_verbs:восприняться{}, // восприняться на слух
rus_verbs:воссесть{}, // Коля воссел на трон
rus_verbs:вправить{}, // вправить мозг на место
rus_verbs:вправлять{}, // вправлять мозги на место
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:врубать{}, // врубать на полную мощность
rus_verbs:врубить{}, // врубить на полную мощность
rus_verbs:врубиться{}, // врубиться на полную мощность
rus_verbs:врываться{}, // врываться на собрание
rus_verbs:вскарабкаться{}, // вскарабкаться на утёс
rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс
rus_verbs:вскочить{}, // вскочить на ноги
rus_verbs:всплывать{}, // всплывать на поверхность воды
rus_verbs:всплыть{}, // всплыть на поверхность воды
rus_verbs:вспрыгивать{}, // вспрыгивать на платформу
rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу
rus_verbs:встать{}, // встать на защиту чести и достоинства
rus_verbs:вторгаться{}, // вторгаться на чужую территорию
rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию
rus_verbs:въезжать{}, // въезжать на пандус
rus_verbs:наябедничать{}, // наябедничать на соседа по парте
rus_verbs:выблевать{}, // выблевать завтрак на пол
rus_verbs:выблеваться{}, // выблеваться на пол
rus_verbs:выблевывать{}, // выблевывать завтрак на пол
rus_verbs:выблевываться{}, // выблевываться на пол
rus_verbs:вывезти{}, // вывезти мусор на свалку
rus_verbs:вывесить{}, // вывесить белье на просушку
rus_verbs:вывести{}, // вывести собаку на прогулку
rus_verbs:вывешивать{}, // вывешивать белье на веревку
rus_verbs:вывозить{}, // вывозить детей на природу
rus_verbs:вызывать{}, // Начальник вызывает на ковер
rus_verbs:выйти{}, // выйти на свободу
rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение
rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение
rus_verbs:выливать{}, // выливать на землю
rus_verbs:выливаться{}, // выливаться на землю
rus_verbs:вылить{}, // вылить жидкость на землю
rus_verbs:вылиться{}, // Топливо вылилось на землю
rus_verbs:выложить{}, // выложить на берег
rus_verbs:выменивать{}, // выменивать золото на хлеб
rus_verbs:вымениваться{}, // Золото выменивается на хлеб
rus_verbs:выменять{}, // выменять золото на хлеб
rus_verbs:выпадать{}, // снег выпадает на землю
rus_verbs:выплевывать{}, // выплевывать на землю
rus_verbs:выплевываться{}, // выплевываться на землю
rus_verbs:выплескать{}, // выплескать на землю
rus_verbs:выплескаться{}, // выплескаться на землю
rus_verbs:выплескивать{}, // выплескивать на землю
rus_verbs:выплескиваться{}, // выплескиваться на землю
rus_verbs:выплывать{}, // выплывать на поверхность
rus_verbs:выплыть{}, // выплыть на поверхность
rus_verbs:выплюнуть{}, // выплюнуть на пол
rus_verbs:выползать{}, // выползать на свежий воздух
rus_verbs:выпроситься{}, // выпроситься на улицу
rus_verbs:выпрыгивать{}, // выпрыгивать на свободу
rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон
rus_verbs:выпускать{}, // выпускать на свободу
rus_verbs:выпустить{}, // выпустить на свободу
rus_verbs:выпучивать{}, // выпучивать на кого-то глаза
rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то
rus_verbs:выпучить{}, // выпучить глаза на кого-то
rus_verbs:выпучиться{}, // выпучиться на кого-то
rus_verbs:выронить{}, // выронить на землю
rus_verbs:высадить{}, // высадить на берег
rus_verbs:высадиться{}, // высадиться на берег
rus_verbs:высаживаться{}, // высаживаться на остров
rus_verbs:выскальзывать{}, // выскальзывать на землю
rus_verbs:выскочить{}, // выскочить на сцену
rus_verbs:высморкаться{}, // высморкаться на землю
rus_verbs:высморкнуться{}, // высморкнуться на землю
rus_verbs:выставить{}, // выставить на всеобщее обозрение
rus_verbs:выставиться{}, // выставиться на всеобщее обозрение
rus_verbs:выставлять{}, // выставлять на всеобщее обозрение
rus_verbs:выставляться{}, // выставляться на всеобщее обозрение
инфинитив:высыпать{вид:соверш}, // высыпать на землю
инфинитив:высыпать{вид:несоверш},
глагол:высыпать{вид:соверш},
глагол:высыпать{вид:несоверш},
деепричастие:высыпав{},
деепричастие:высыпая{},
прилагательное:высыпавший{вид:соверш},
//++прилагательное:высыпавший{вид:несоверш},
прилагательное:высыпающий{вид:несоверш},
rus_verbs:высыпаться{}, // высыпаться на землю
rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя
rus_verbs:вытаращиваться{}, // вытаращиваться на медведя
rus_verbs:вытаращить{}, // вытаращить глаза на медведя
rus_verbs:вытаращиться{}, // вытаращиться на медведя
rus_verbs:вытекать{}, // вытекать на землю
rus_verbs:вытечь{}, // вытечь на землю
rus_verbs:выучиваться{}, // выучиваться на кого-то
rus_verbs:выучиться{}, // выучиться на кого-то
rus_verbs:посмотреть{}, // посмотреть на экран
rus_verbs:нашить{}, // нашить что-то на одежду
rus_verbs:придти{}, // придти на помощь кому-то
инфинитив:прийти{}, // прийти на помощь кому-то
глагол:прийти{},
деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты.
rus_verbs:поднять{}, // поднять на вершину
rus_verbs:согласиться{}, // согласиться на ничью
rus_verbs:послать{}, // послать на фронт
rus_verbs:слать{}, // слать на фронт
rus_verbs:надеяться{}, // надеяться на лучшее
rus_verbs:крикнуть{}, // крикнуть на шалунов
rus_verbs:пройти{}, // пройти на пляж
rus_verbs:прислать{}, // прислать на экспертизу
rus_verbs:жить{}, // жить на подачки
rus_verbs:становиться{}, // становиться на ноги
rus_verbs:наслать{}, // наслать на кого-то
rus_verbs:принять{}, // принять на заметку
rus_verbs:собираться{}, // собираться на экзамен
rus_verbs:оставить{}, // оставить на всякий случай
rus_verbs:звать{}, // звать на помощь
rus_verbs:направиться{}, // направиться на прогулку
rus_verbs:отвечать{}, // отвечать на звонки
rus_verbs:отправиться{}, // отправиться на прогулку
rus_verbs:поставить{}, // поставить на пол
rus_verbs:обернуться{}, // обернуться на зов
rus_verbs:отозваться{}, // отозваться на просьбу
rus_verbs:закричать{}, // закричать на собаку
rus_verbs:опустить{}, // опустить на землю
rus_verbs:принести{}, // принести на пляж свой жезлонг
rus_verbs:указать{}, // указать на дверь
rus_verbs:ходить{}, // ходить на занятия
rus_verbs:уставиться{}, // уставиться на листок
rus_verbs:приходить{}, // приходить на экзамен
rus_verbs:махнуть{}, // махнуть на пляж
rus_verbs:явиться{}, // явиться на допрос
rus_verbs:оглянуться{}, // оглянуться на дорогу
rus_verbs:уехать{}, // уехать на заработки
rus_verbs:повести{}, // повести на штурм
rus_verbs:опуститься{}, // опуститься на колени
//rus_verbs:передать{}, // передать на проверку
rus_verbs:побежать{}, // побежать на занятия
rus_verbs:прибыть{}, // прибыть на место службы
rus_verbs:кричать{}, // кричать на медведя
rus_verbs:стечь{}, // стечь на землю
rus_verbs:обратить{}, // обратить на себя внимание
rus_verbs:подать{}, // подать на пропитание
rus_verbs:привести{}, // привести на съемки
rus_verbs:испытывать{}, // испытывать на животных
rus_verbs:перевести{}, // перевести на жену
rus_verbs:купить{}, // купить на заемные деньги
rus_verbs:собраться{}, // собраться на встречу
rus_verbs:заглянуть{}, // заглянуть на огонёк
rus_verbs:нажать{}, // нажать на рычаг
rus_verbs:поспешить{}, // поспешить на праздник
rus_verbs:перейти{}, // перейти на русский язык
rus_verbs:поверить{}, // поверить на честное слово
rus_verbs:глянуть{}, // глянуть на обложку
rus_verbs:зайти{}, // зайти на огонёк
rus_verbs:проходить{}, // проходить на сцену
rus_verbs:глядеть{}, // глядеть на актрису
//rus_verbs:решиться{}, // решиться на прыжок
rus_verbs:пригласить{}, // пригласить на танец
rus_verbs:позвать{}, // позвать на экзамен
rus_verbs:усесться{}, // усесться на стул
rus_verbs:поступить{}, // поступить на математический факультет
rus_verbs:лечь{}, // лечь на живот
rus_verbs:потянуться{}, // потянуться на юг
rus_verbs:присесть{}, // присесть на корточки
rus_verbs:наступить{}, // наступить на змею
rus_verbs:заорать{}, // заорать на попрошаек
rus_verbs:надеть{}, // надеть на голову
rus_verbs:поглядеть{}, // поглядеть на девчонок
rus_verbs:принимать{}, // принимать на гарантийное обслуживание
rus_verbs:привезти{}, // привезти на испытания
rus_verbs:рухнуть{}, // рухнуть на асфальт
rus_verbs:пускать{}, // пускать на корм
rus_verbs:отвести{}, // отвести на приём
rus_verbs:отправить{}, // отправить на утилизацию
rus_verbs:двигаться{}, // двигаться на восток
rus_verbs:нести{}, // нести на пляж
rus_verbs:падать{}, // падать на руки
rus_verbs:откинуться{}, // откинуться на спинку кресла
rus_verbs:рявкнуть{}, // рявкнуть на детей
rus_verbs:получать{}, // получать на проживание
rus_verbs:полезть{}, // полезть на рожон
rus_verbs:направить{}, // направить на дообследование
rus_verbs:приводить{}, // приводить на проверку
rus_verbs:потребоваться{}, // потребоваться на замену
rus_verbs:кинуться{}, // кинуться на нападавшего
rus_verbs:учиться{}, // учиться на токаря
rus_verbs:приподнять{}, // приподнять на один метр
rus_verbs:налить{}, // налить на стол
rus_verbs:играть{}, // играть на деньги
rus_verbs:рассчитывать{}, // рассчитывать на подмогу
rus_verbs:шепнуть{}, // шепнуть на ухо
rus_verbs:швырнуть{}, // швырнуть на землю
rus_verbs:прыгнуть{}, // прыгнуть на оленя
rus_verbs:предлагать{}, // предлагать на выбор
rus_verbs:садиться{}, // садиться на стул
rus_verbs:лить{}, // лить на землю
rus_verbs:испытать{}, // испытать на животных
rus_verbs:фыркнуть{}, // фыркнуть на детеныша
rus_verbs:годиться{}, // мясо годится на фарш
rus_verbs:проверить{}, // проверить высказывание на истинность
rus_verbs:откликнуться{}, // откликнуться на призывы
rus_verbs:полагаться{}, // полагаться на интуицию
rus_verbs:покоситься{}, // покоситься на соседа
rus_verbs:повесить{}, // повесить на гвоздь
инфинитив:походить{вид:соверш}, // походить на занятия
глагол:походить{вид:соверш},
деепричастие:походив{},
прилагательное:походивший{},
rus_verbs:помчаться{}, // помчаться на экзамен
rus_verbs:ставить{}, // ставить на контроль
rus_verbs:свалиться{}, // свалиться на землю
rus_verbs:валиться{}, // валиться на землю
rus_verbs:подарить{}, // подарить на день рожденья
rus_verbs:сбежать{}, // сбежать на необитаемый остров
rus_verbs:стрелять{}, // стрелять на поражение
rus_verbs:обращать{}, // обращать на себя внимание
rus_verbs:наступать{}, // наступать на те же грабли
rus_verbs:сбросить{}, // сбросить на землю
rus_verbs:обидеться{}, // обидеться на друга
rus_verbs:устроиться{}, // устроиться на стажировку
rus_verbs:погрузиться{}, // погрузиться на большую глубину
rus_verbs:течь{}, // течь на землю
rus_verbs:отбросить{}, // отбросить на землю
rus_verbs:метать{}, // метать на дно
rus_verbs:пустить{}, // пустить на переплавку
rus_verbs:прожить{}, // прожить на пособие
rus_verbs:полететь{}, // полететь на континент
rus_verbs:пропустить{}, // пропустить на сцену
rus_verbs:указывать{}, // указывать на ошибку
rus_verbs:наткнуться{}, // наткнуться на клад
rus_verbs:рвануть{}, // рвануть на юг
rus_verbs:ступать{}, // ступать на землю
rus_verbs:спрыгнуть{}, // спрыгнуть на берег
rus_verbs:заходить{}, // заходить на огонёк
rus_verbs:нырнуть{}, // нырнуть на глубину
rus_verbs:рвануться{}, // рвануться на свободу
rus_verbs:натянуть{}, // натянуть на голову
rus_verbs:забраться{}, // забраться на стол
rus_verbs:помахать{}, // помахать на прощание
rus_verbs:содержать{}, // содержать на спонсорскую помощь
rus_verbs:приезжать{}, // приезжать на праздники
rus_verbs:проникнуть{}, // проникнуть на территорию
rus_verbs:подъехать{}, // подъехать на митинг
rus_verbs:устремиться{}, // устремиться на волю
rus_verbs:посадить{}, // посадить на стул
rus_verbs:ринуться{}, // ринуться на голкипера
rus_verbs:подвигнуть{}, // подвигнуть на подвиг
rus_verbs:отдавать{}, // отдавать на перевоспитание
rus_verbs:отложить{}, // отложить на черный день
rus_verbs:убежать{}, // убежать на танцы
rus_verbs:поднимать{}, // поднимать на верхний этаж
rus_verbs:переходить{}, // переходить на цифровой сигнал
rus_verbs:отослать{}, // отослать на переаттестацию
rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола
rus_verbs:назначить{}, // назначить на должность
rus_verbs:осесть{}, // осесть на дно
rus_verbs:торопиться{}, // торопиться на экзамен
rus_verbs:менять{}, // менять на еду
rus_verbs:доставить{}, // доставить на шестой этаж
rus_verbs:заслать{}, // заслать на проверку
rus_verbs:дуть{}, // дуть на воду
rus_verbs:сослать{}, // сослать на каторгу
rus_verbs:останавливаться{}, // останавливаться на отдых
rus_verbs:сдаваться{}, // сдаваться на милость победителя
rus_verbs:сослаться{}, // сослаться на презумпцию невиновности
rus_verbs:рассердиться{}, // рассердиться на дочь
rus_verbs:кинуть{}, // кинуть на землю
rus_verbs:расположиться{}, // расположиться на ночлег
rus_verbs:осмелиться{}, // осмелиться на подлог
rus_verbs:шептать{}, // шептать на ушко
rus_verbs:уронить{}, // уронить на землю
rus_verbs:откинуть{}, // откинуть на спинку кресла
rus_verbs:перенести{}, // перенести на рабочий стол
rus_verbs:сдаться{}, // сдаться на милость победителя
rus_verbs:светить{}, // светить на дорогу
rus_verbs:мчаться{}, // мчаться на бал
rus_verbs:нестись{}, // нестись на свидание
rus_verbs:поглядывать{}, // поглядывать на экран
rus_verbs:орать{}, // орать на детей
rus_verbs:уложить{}, // уложить на лопатки
rus_verbs:решаться{}, // решаться на поступок
rus_verbs:попадать{}, // попадать на карандаш
rus_verbs:сплюнуть{}, // сплюнуть на землю
rus_verbs:снимать{}, // снимать на телефон
rus_verbs:опоздать{}, // опоздать на работу
rus_verbs:посылать{}, // посылать на проверку
rus_verbs:погнать{}, // погнать на пастбище
rus_verbs:поступать{}, // поступать на кибернетический факультет
rus_verbs:спускаться{}, // спускаться на уровень моря
rus_verbs:усадить{}, // усадить на диван
rus_verbs:проиграть{}, // проиграть на спор
rus_verbs:прилететь{}, // прилететь на фестиваль
rus_verbs:повалиться{}, // повалиться на спину
rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина
rus_verbs:задавать{}, // задавать на выходные
rus_verbs:запасть{}, // запасть на девочку
rus_verbs:лезть{}, // лезть на забор
rus_verbs:потащить{}, // потащить на выборы
rus_verbs:направляться{}, // направляться на экзамен
rus_verbs:определять{}, // определять на вкус
rus_verbs:поползти{}, // поползти на стену
rus_verbs:поплыть{}, // поплыть на берег
rus_verbs:залезть{}, // залезть на яблоню
rus_verbs:сдать{}, // сдать на мясокомбинат
rus_verbs:приземлиться{}, // приземлиться на дорогу
rus_verbs:лаять{}, // лаять на прохожих
rus_verbs:перевернуть{}, // перевернуть на бок
rus_verbs:ловить{}, // ловить на живца
rus_verbs:отнести{}, // отнести животное на хирургический стол
rus_verbs:плюнуть{}, // плюнуть на условности
rus_verbs:передавать{}, // передавать на проверку
rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек
rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике
инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали
инфинитив:рассыпаться{вид:соверш},
глагол:рассыпаться{вид:несоверш},
глагол:рассыпаться{вид:соверш},
деепричастие:рассыпавшись{},
деепричастие:рассыпаясь{},
прилагательное:рассыпавшийся{вид:несоверш},
прилагательное:рассыпавшийся{вид:соверш},
прилагательное:рассыпающийся{},
rus_verbs:зарычать{}, // Медведица зарычала на медвежонка
rus_verbs:призвать{}, // призвать на сборы
rus_verbs:увезти{}, // увезти на дачу
rus_verbs:содержаться{}, // содержаться на пожертвования
rus_verbs:навести{}, // навести на скопление телескоп
rus_verbs:отправляться{}, // отправляться на утилизацию
rus_verbs:улечься{}, // улечься на животик
rus_verbs:налететь{}, // налететь на препятствие
rus_verbs:перевернуться{}, // перевернуться на спину
rus_verbs:улететь{}, // улететь на родину
rus_verbs:ложиться{}, // ложиться на бок
rus_verbs:класть{}, // класть на место
rus_verbs:отреагировать{}, // отреагировать на выступление
rus_verbs:доставлять{}, // доставлять на дом
rus_verbs:отнять{}, // отнять на благо правящей верхушки
rus_verbs:ступить{}, // ступить на землю
rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы
rus_verbs:унести{}, // унести на работу
rus_verbs:сходить{}, // сходить на концерт
rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги
rus_verbs:соскочить{}, // соскочить на землю
rus_verbs:пожаловаться{}, // пожаловаться на соседей
rus_verbs:тащить{}, // тащить на замену
rus_verbs:замахать{}, // замахать руками на паренька
rus_verbs:заглядывать{}, // заглядывать на обед
rus_verbs:соглашаться{}, // соглашаться на равный обмен
rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик
rus_verbs:увести{}, // увести на осмотр
rus_verbs:успевать{}, // успевать на контрольную работу
rus_verbs:опрокинуть{}, // опрокинуть на себя
rus_verbs:подавать{}, // подавать на апелляцию
rus_verbs:прибежать{}, // прибежать на вокзал
rus_verbs:отшвырнуть{}, // отшвырнуть на замлю
rus_verbs:привлекать{}, // привлекать на свою сторону
rus_verbs:опереться{}, // опереться на палку
rus_verbs:перебраться{}, // перебраться на маленький островок
rus_verbs:уговорить{}, // уговорить на новые траты
rus_verbs:гулять{}, // гулять на спонсорские деньги
rus_verbs:переводить{}, // переводить на другой путь
rus_verbs:заколебаться{}, // заколебаться на один миг
rus_verbs:зашептать{}, // зашептать на ушко
rus_verbs:привстать{}, // привстать на цыпочки
rus_verbs:хлынуть{}, // хлынуть на берег
rus_verbs:наброситься{}, // наброситься на еду
rus_verbs:напасть{}, // повстанцы, напавшие на конвой
rus_verbs:убрать{}, // книга, убранная на полку
rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию
rus_verbs:засматриваться{}, // засматриваться на девчонок
rus_verbs:застегнуться{}, // застегнуться на все пуговицы
rus_verbs:провериться{}, // провериться на заболевания
rus_verbs:проверяться{}, // проверяться на заболевания
rus_verbs:тестировать{}, // тестировать на профпригодность
rus_verbs:протестировать{}, // протестировать на профпригодность
rus_verbs:уходить{}, // отец, уходящий на работу
rus_verbs:налипнуть{}, // снег, налипший на провода
rus_verbs:налипать{}, // снег, налипающий на провода
rus_verbs:улетать{}, // Многие птицы улетают осенью на юг.
rus_verbs:поехать{}, // она поехала на встречу с заказчиком
rus_verbs:переключать{}, // переключать на резервную линию
rus_verbs:переключаться{}, // переключаться на резервную линию
rus_verbs:подписаться{}, // подписаться на обновление
rus_verbs:нанести{}, // нанести на кожу
rus_verbs:нарываться{}, // нарываться на неприятности
rus_verbs:выводить{}, // выводить на орбиту
rus_verbs:вернуться{}, // вернуться на родину
rus_verbs:возвращаться{}, // возвращаться на родину
прилагательное:падкий{}, // Он падок на деньги.
прилагательное:обиженный{}, // Он обижен на отца.
rus_verbs:косить{}, // Он косит на оба глаза.
rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок.
прилагательное:готовый{}, // Он готов на всякие жертвы.
rus_verbs:говорить{}, // Он говорит на скользкую тему.
прилагательное:глухой{}, // Он глух на одно ухо.
rus_verbs:взять{}, // Он взял ребёнка себе на колени.
rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия.
rus_verbs:вести{}, // Лестница ведёт на третий этаж.
rus_verbs:уполномочивать{}, // уполномочивать на что-либо
глагол:спешить{ вид:несоверш }, // Я спешу на поезд.
rus_verbs:брать{}, // Я беру всю ответственность на себя.
rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление.
rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики.
rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку.
rus_verbs:разбираться{}, // Эта машина разбирается на части.
rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние.
rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп.
rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье.
rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно.
rus_verbs:делиться{}, // Тридцать делится на пять без остатка.
rus_verbs:удаляться{}, // Суд удаляется на совещание.
rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север.
rus_verbs:сохранить{}, // Сохраните это на память обо мне.
rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию.
rus_verbs:лететь{}, // Самолёт летит на север.
rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров.
// rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи.
rus_verbs:смотреть{}, // Она смотрит на нас из окна.
rus_verbs:отдать{}, // Она отдала мне деньги на сохранение.
rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину.
rus_verbs:любоваться{}, // гости любовались на картину
rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь.
прилагательное:действительный{}, // Прививка оспы действительна только на три года.
rus_verbs:спуститься{}, // На город спустился смог
прилагательное:нечистый{}, // Он нечист на руку.
прилагательное:неспособный{}, // Он неспособен на такую низость.
прилагательное:злой{}, // кот очень зол на хозяина
rus_verbs:пойти{}, // Девочка не пошла на урок физультуры
rus_verbs:прибывать{}, // мой поезд прибывает на первый путь
rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу
rus_verbs:идти{}, // Дело идёт на лад.
rus_verbs:лазить{}, // Он лазил на чердак.
rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры.
// rus_verbs:действовать{}, // действующий на нервы
rus_verbs:выходить{}, // Балкон выходит на площадь.
rus_verbs:работать{}, // Время работает на нас.
глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина.
rus_verbs:бросить{}, // Они бросили все силы на строительство.
// глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков.
rus_verbs:броситься{}, // Она радостно бросилась мне на шею.
rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью.
rus_verbs:ответить{}, // Она не ответила на мой поклон.
rus_verbs:нашивать{}, // Она нашивала заплату на локоть.
rus_verbs:молиться{}, // Она молится на свою мать.
rus_verbs:запереть{}, // Она заперла дверь на замок.
rus_verbs:заявить{}, // Она заявила свои права на наследство.
rus_verbs:уйти{}, // Все деньги ушли на путешествие.
rus_verbs:вступить{}, // Водолаз вступил на берег.
rus_verbs:сойти{}, // Ночь сошла на землю.
rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано.
rus_verbs:рыдать{}, // Не рыдай так безумно над ним.
rus_verbs:подписать{}, // Не забудьте подписать меня на газету.
rus_verbs:держать{}, // Наш пароход держал курс прямо на север.
rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира.
rus_verbs:ехать{}, // Мы сейчас едем на завод.
rus_verbs:выбросить{}, // Волнами лодку выбросило на берег.
ГЛ_ИНФ(сесть), // сесть на снег
ГЛ_ИНФ(записаться),
ГЛ_ИНФ(положить) // положи книгу на стол
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: залить на youtube
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} }
then return true
}
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } }
then return true
}
// смещаться на несколько миллиметров
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} наречие:*{} }
then return true
}
// партия взяла на себя нереалистичные обязательства
fact гл_предл
{
if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} }
then return true
}
#endregion ВИНИТЕЛЬНЫЙ
// Все остальные варианты с предлогом 'НА' по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-4
}
// Этот вариант нужен для обработки конструкций с числительными:
// Президентские выборы разделили Венесуэлу на два непримиримых лагеря
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:род } }
then return false,-4
}
// Продавать на eBay
fact гл_предл
{
if context { * предлог:на{} * }
then return false,-6
}
#endregion Предлог_НА
#region Предлог_С
// ------------- ПРЕДЛОГ 'С' -----------------
// У этого предлога предпочтительная семантика привязывает его обычно к существительному.
// Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим.
#region ТВОРИТЕЛЬНЫЙ
wordentry_set Гл_С_Твор={
rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов
rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться
rus_verbs:забраться{},
rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ)
rus_verbs:БИТЬСЯ{}, //
rus_verbs:ПОДРАТЬСЯ{}, //
прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ)
rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ)
rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ)
rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ)
rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ)
прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра
rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом.
rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ)
rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ)
rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ)
rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ)
rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом
rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками
rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу
rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ)
rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ)
rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ)
rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ)
rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ)
rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ)
rus_verbs:отправить{}, // вы можете отправить со мной человека
rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам
rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор)
rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С)
rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С)
прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С)
rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С)
rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С)
rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С)
rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С)
rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С)
rus_verbs:СВЫКАТЬСЯ{},
rus_verbs:стаскиваться{},
rus_verbs:спиливаться{},
rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С)
rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор)
rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С)
rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С)
rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С)
rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С)
rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С)
rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С)
rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С)
rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С)
rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор)
rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С)
rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С)
rus_verbs:согласиться{}, // с этим согласились все (согласиться с)
rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор)
rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С)
rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С)
rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор)
rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор)
rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С)
rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С)
rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор)
rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор)
rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор)
rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор)
rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор)
rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор)
rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор)
rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор)
rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор)
rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ)
rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ)
rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много)
rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С)
rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С)
rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С)
rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С)
rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С)
rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор)
rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С)
rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С)
rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С)
rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С)
rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С)
инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара.
инфинитив:кристаллизоваться{ вид:несоверш },
глагол:кристаллизоваться{ вид:соверш },
глагол:кристаллизоваться{ вид:несоверш },
rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С)
rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С)
rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С)
rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С)
rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С)
rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор)
rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С)
rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С)
rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с)
rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с)
rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с)
rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с)
rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело.
rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором
rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором
rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором
rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором
rus_verbs:стирать{}, // стирать с мылом рубашку в тазу
rus_verbs:прыгать{}, // парашютист прыгает с парашютом
rus_verbs:выступить{}, // Он выступил с приветствием съезду.
rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят.
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой.
rus_verbs:вставать{}, // он встаёт с зарёй
rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером.
rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью.
rus_verbs:договориться{}, // мы договоримся с вами
rus_verbs:побыть{}, // он хотел побыть с тобой
rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью
rus_verbs:вязаться{}, // вязаться с фактами
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:относиться{}, // относиться с пониманием
rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов.
rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней
rus_verbs:гулять{}, // бабушка гуляет с внуком
rus_verbs:разбираться{}, // разбираться с задачей
rus_verbs:сверить{}, // Данные были сверены с эталонными значениями
rus_verbs:делать{}, // Что делать со старым телефоном
rus_verbs:осматривать{}, // осматривать с удивлением
rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре
rus_verbs:попрощаться{}, // попрощаться с талантливым актером
rus_verbs:задремать{}, // задремать с кружкой чая в руке
rus_verbs:связать{}, // связать катастрофу с действиями конкурентов
rus_verbs:носиться{}, // носиться с безумной идеей
rus_verbs:кончать{}, // кончать с собой
rus_verbs:обмениваться{}, // обмениваться с собеседниками
rus_verbs:переговариваться{}, // переговариваться с маяком
rus_verbs:общаться{}, // общаться с полицией
rus_verbs:завершить{}, // завершить с ошибкой
rus_verbs:обняться{}, // обняться с подругой
rus_verbs:сливаться{}, // сливаться с фоном
rus_verbs:смешаться{}, // смешаться с толпой
rus_verbs:договариваться{}, // договариваться с потерпевшим
rus_verbs:обедать{}, // обедать с гостями
rus_verbs:сообщаться{}, // сообщаться с подземной рекой
rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц
rus_verbs:читаться{}, // читаться с трудом
rus_verbs:смириться{}, // смириться с утратой
rus_verbs:разделить{}, // разделить с другими ответственность
rus_verbs:роднить{}, // роднить с медведем
rus_verbs:медлить{}, // медлить с ответом
rus_verbs:скрестить{}, // скрестить с ужом
rus_verbs:покоиться{}, // покоиться с миром
rus_verbs:делиться{}, // делиться с друзьями
rus_verbs:познакомить{}, // познакомить с Олей
rus_verbs:порвать{}, // порвать с Олей
rus_verbs:завязать{}, // завязать с Олей знакомство
rus_verbs:суетиться{}, // суетиться с изданием романа
rus_verbs:соединиться{}, // соединиться с сервером
rus_verbs:справляться{}, // справляться с нуждой
rus_verbs:замешкаться{}, // замешкаться с ответом
rus_verbs:поссориться{}, // поссориться с подругой
rus_verbs:ссориться{}, // ссориться с друзьями
rus_verbs:торопить{}, // торопить с решением
rus_verbs:поздравить{}, // поздравить с победой
rus_verbs:проститься{}, // проститься с человеком
rus_verbs:поработать{}, // поработать с деревом
rus_verbs:приключиться{}, // приключиться с Колей
rus_verbs:сговориться{}, // сговориться с Ваней
rus_verbs:отъехать{}, // отъехать с ревом
rus_verbs:объединять{}, // объединять с другой кампанией
rus_verbs:употребить{}, // употребить с молоком
rus_verbs:перепутать{}, // перепутать с другой книгой
rus_verbs:запоздать{}, // запоздать с ответом
rus_verbs:подружиться{}, // подружиться с другими детьми
rus_verbs:дружить{}, // дружить с Сережей
rus_verbs:поравняться{}, // поравняться с финишной чертой
rus_verbs:ужинать{}, // ужинать с гостями
rus_verbs:расставаться{}, // расставаться с приятелями
rus_verbs:завтракать{}, // завтракать с семьей
rus_verbs:объединиться{}, // объединиться с соседями
rus_verbs:сменяться{}, // сменяться с напарником
rus_verbs:соединить{}, // соединить с сетью
rus_verbs:разговориться{}, // разговориться с охранником
rus_verbs:преподнести{}, // преподнести с помпой
rus_verbs:напечатать{}, // напечатать с картинками
rus_verbs:соединять{}, // соединять с сетью
rus_verbs:расправиться{}, // расправиться с беззащитным человеком
rus_verbs:распрощаться{}, // распрощаться с деньгами
rus_verbs:сравнить{}, // сравнить с конкурентами
rus_verbs:ознакомиться{}, // ознакомиться с выступлением
инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой
деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{},
rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия
rus_verbs:прощаться{}, // прощаться с боевым товарищем
rus_verbs:сравнивать{}, // сравнивать с конкурентами
rus_verbs:складывать{}, // складывать с весом упаковки
rus_verbs:повестись{}, // повестись с ворами
rus_verbs:столкнуть{}, // столкнуть с отбойником
rus_verbs:переглядываться{}, // переглядываться с соседом
rus_verbs:поторопить{}, // поторопить с откликом
rus_verbs:развлекаться{}, // развлекаться с подружками
rus_verbs:заговаривать{}, // заговаривать с незнакомцами
rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой
инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим
деепричастие:согласуясь{}, прилагательное:согласующийся{},
rus_verbs:совпасть{}, // совпасть с оригиналом
rus_verbs:соединяться{}, // соединяться с куратором
rus_verbs:повстречаться{}, // повстречаться с героями
rus_verbs:поужинать{}, // поужинать с родителями
rus_verbs:развестись{}, // развестись с первым мужем
rus_verbs:переговорить{}, // переговорить с коллегами
rus_verbs:сцепиться{}, // сцепиться с бродячей собакой
rus_verbs:сожрать{}, // сожрать с потрохами
rus_verbs:побеседовать{}, // побеседовать со шпаной
rus_verbs:поиграть{}, // поиграть с котятами
rus_verbs:сцепить{}, // сцепить с тягачом
rus_verbs:помириться{}, // помириться с подружкой
rus_verbs:связываться{}, // связываться с бандитами
rus_verbs:совещаться{}, // совещаться с мастерами
rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой
rus_verbs:переплестись{}, // переплестись с кустами
rus_verbs:мутить{}, // мутить с одногрупницами
rus_verbs:приглядываться{}, // приглядываться с интересом
rus_verbs:сблизиться{}, // сблизиться с врагами
rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой
rus_verbs:растереть{}, // растереть с солью
rus_verbs:смешиваться{}, // смешиваться с известью
rus_verbs:соприкоснуться{}, // соприкоснуться с тайной
rus_verbs:ладить{}, // ладить с родственниками
rus_verbs:сотрудничать{}, // сотрудничать с органами дознания
rus_verbs:съехаться{}, // съехаться с родственниками
rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов
rus_verbs:советоваться{}, // советоваться с отчимом
rus_verbs:сравниться{}, // сравниться с лучшими
rus_verbs:знакомиться{}, // знакомиться с абитуриентами
rus_verbs:нырять{}, // нырять с аквалангом
rus_verbs:забавляться{}, // забавляться с куклой
rus_verbs:перекликаться{}, // перекликаться с другой статьей
rus_verbs:тренироваться{}, // тренироваться с партнершей
rus_verbs:поспорить{}, // поспорить с казночеем
инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком
деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш },
rus_verbs:примириться{}, // примириться с утратой
rus_verbs:раскланяться{}, // раскланяться с фрейлинами
rus_verbs:слечь{}, // слечь с ангиной
rus_verbs:соприкасаться{}, // соприкасаться со стеной
rus_verbs:смешать{}, // смешать с грязью
rus_verbs:пересекаться{}, // пересекаться с трассой
rus_verbs:путать{}, // путать с государственной шерстью
rus_verbs:поболтать{}, // поболтать с ученицами
rus_verbs:здороваться{}, // здороваться с профессором
rus_verbs:просчитаться{}, // просчитаться с покупкой
rus_verbs:сторожить{}, // сторожить с собакой
rus_verbs:обыскивать{}, // обыскивать с собаками
rus_verbs:переплетаться{}, // переплетаться с другой веткой
rus_verbs:обниматься{}, // обниматься с Ксюшей
rus_verbs:объединяться{}, // объединяться с конкурентами
rus_verbs:погорячиться{}, // погорячиться с покупкой
rus_verbs:мыться{}, // мыться с мылом
rus_verbs:свериться{}, // свериться с эталоном
rus_verbs:разделаться{}, // разделаться с кем-то
rus_verbs:чередоваться{}, // чередоваться с партнером
rus_verbs:налететь{}, // налететь с соратниками
rus_verbs:поспать{}, // поспать с включенным светом
rus_verbs:управиться{}, // управиться с собакой
rus_verbs:согрешить{}, // согрешить с замужней
rus_verbs:определиться{}, // определиться с победителем
rus_verbs:перемешаться{}, // перемешаться с гранулами
rus_verbs:затрудняться{}, // затрудняться с ответом
rus_verbs:обождать{}, // обождать со стартом
rus_verbs:фыркать{}, // фыркать с презрением
rus_verbs:засидеться{}, // засидеться с приятелем
rus_verbs:крепнуть{}, // крепнуть с годами
rus_verbs:пировать{}, // пировать с дружиной
rus_verbs:щебетать{}, // щебетать с сестричками
rus_verbs:маяться{}, // маяться с кашлем
rus_verbs:сближать{}, // сближать с центральным светилом
rus_verbs:меркнуть{}, // меркнуть с возрастом
rus_verbs:заспорить{}, // заспорить с оппонентами
rus_verbs:граничить{}, // граничить с Ливаном
rus_verbs:перестараться{}, // перестараться со стимуляторами
rus_verbs:объединить{}, // объединить с филиалом
rus_verbs:свыкнуться{}, // свыкнуться с утратой
rus_verbs:посоветоваться{}, // посоветоваться с адвокатами
rus_verbs:напутать{}, // напутать с ведомостями
rus_verbs:нагрянуть{}, // нагрянуть с обыском
rus_verbs:посовещаться{}, // посовещаться с судьей
rus_verbs:провернуть{}, // провернуть с друганом
rus_verbs:разделяться{}, // разделяться с сотрапезниками
rus_verbs:пересечься{}, // пересечься с второй колонной
rus_verbs:опережать{}, // опережать с большим запасом
rus_verbs:перепутаться{}, // перепутаться с другой линией
rus_verbs:соотноситься{}, // соотноситься с затратами
rus_verbs:смешивать{}, // смешивать с золой
rus_verbs:свидеться{}, // свидеться с тобой
rus_verbs:переспать{}, // переспать с графиней
rus_verbs:поладить{}, // поладить с соседями
rus_verbs:протащить{}, // протащить с собой
rus_verbs:разминуться{}, // разминуться с встречным потоком
rus_verbs:перемежаться{}, // перемежаться с успехами
rus_verbs:рассчитаться{}, // рассчитаться с кредиторами
rus_verbs:срастись{}, // срастись с телом
rus_verbs:знакомить{}, // знакомить с родителями
rus_verbs:поругаться{}, // поругаться с родителями
rus_verbs:совладать{}, // совладать с чувствами
rus_verbs:обручить{}, // обручить с богатой невестой
rus_verbs:сближаться{}, // сближаться с вражеским эсминцем
rus_verbs:замутить{}, // замутить с Ксюшей
rus_verbs:повозиться{}, // повозиться с настройкой
rus_verbs:торговаться{}, // торговаться с продавцами
rus_verbs:уединиться{}, // уединиться с девчонкой
rus_verbs:переборщить{}, // переборщить с добавкой
rus_verbs:ознакомить{}, // ознакомить с пожеланиями
rus_verbs:прочесывать{}, // прочесывать с собаками
rus_verbs:переписываться{}, // переписываться с корреспондентами
rus_verbs:повздорить{}, // повздорить с сержантом
rus_verbs:разлучить{}, // разлучить с семьей
rus_verbs:соседствовать{}, // соседствовать с цыганами
rus_verbs:застукать{}, // застукать с проститутками
rus_verbs:напуститься{}, // напуститься с кулаками
rus_verbs:сдружиться{}, // сдружиться с ребятами
rus_verbs:соперничать{}, // соперничать с параллельным классом
rus_verbs:прочесать{}, // прочесать с собаками
rus_verbs:кокетничать{}, // кокетничать с гимназистками
rus_verbs:мириться{}, // мириться с убытками
rus_verbs:оплошать{}, // оплошать с билетами
rus_verbs:отождествлять{}, // отождествлять с литературным героем
rus_verbs:хитрить{}, // хитрить с зарплатой
rus_verbs:провозиться{}, // провозиться с задачкой
rus_verbs:коротать{}, // коротать с друзьями
rus_verbs:соревноваться{}, // соревноваться с машиной
rus_verbs:уживаться{}, // уживаться с местными жителями
rus_verbs:отождествляться{}, // отождествляться с литературным героем
rus_verbs:сопоставить{}, // сопоставить с эталоном
rus_verbs:пьянствовать{}, // пьянствовать с друзьями
rus_verbs:залетать{}, // залетать с паленой водкой
rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой
rus_verbs:запаздывать{}, // запаздывать с кормлением
rus_verbs:таскаться{}, // таскаться с сумками
rus_verbs:контрастировать{}, // контрастировать с туфлями
rus_verbs:сшибиться{}, // сшибиться с форвардом
rus_verbs:состязаться{}, // состязаться с лучшей командой
rus_verbs:затрудниться{}, // затрудниться с объяснением
rus_verbs:объясниться{}, // объясниться с пострадавшими
rus_verbs:разводиться{}, // разводиться со сварливой женой
rus_verbs:препираться{}, // препираться с адвокатами
rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками
rus_verbs:свестись{}, // свестись с нулевым счетом
rus_verbs:обговорить{}, // обговорить с директором
rus_verbs:обвенчаться{}, // обвенчаться с ведьмой
rus_verbs:экспериментировать{}, // экспериментировать с генами
rus_verbs:сверять{}, // сверять с таблицей
rus_verbs:сверяться{}, // свериться с таблицей
rus_verbs:сблизить{}, // сблизить с точкой
rus_verbs:гармонировать{}, // гармонировать с обоями
rus_verbs:перемешивать{}, // перемешивать с молоком
rus_verbs:трепаться{}, // трепаться с сослуживцами
rus_verbs:перемигиваться{}, // перемигиваться с соседкой
rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем
rus_verbs:распить{}, // распить с собутыльниками
rus_verbs:скрестись{}, // скрестись с дикой лошадью
rus_verbs:передраться{}, // передраться с дворовыми собаками
rus_verbs:умыть{}, // умыть с мылом
rus_verbs:грызться{}, // грызться с соседями
rus_verbs:переругиваться{}, // переругиваться с соседями
rus_verbs:доиграться{}, // доиграться со спичками
rus_verbs:заладиться{}, // заладиться с подругой
rus_verbs:скрещиваться{}, // скрещиваться с дикими видами
rus_verbs:повидаться{}, // повидаться с дедушкой
rus_verbs:повоевать{}, // повоевать с орками
rus_verbs:сразиться{}, // сразиться с лучшим рыцарем
rus_verbs:кипятить{}, // кипятить с отбеливателем
rus_verbs:усердствовать{}, // усердствовать с наказанием
rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером
rus_verbs:пошептаться{}, // пошептаться с судьями
rus_verbs:сравняться{}, // сравняться с лучшими экземплярами
rus_verbs:церемониться{}, // церемониться с пьяницами
rus_verbs:консультироваться{}, // консультироваться со специалистами
rus_verbs:переусердствовать{}, // переусердствовать с наказанием
rus_verbs:проноситься{}, // проноситься с собой
rus_verbs:перемешать{}, // перемешать с гипсом
rus_verbs:темнить{}, // темнить с долгами
rus_verbs:сталкивать{}, // сталкивать с черной дырой
rus_verbs:увольнять{}, // увольнять с волчьим билетом
rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным
rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами
rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт
rus_verbs:созвониться{}, // созвониться с мамой
rus_verbs:спеться{}, // спеться с отъявленными хулиганами
rus_verbs:интриговать{}, // интриговать с придворными
rus_verbs:приобрести{}, // приобрести со скидкой
rus_verbs:задержаться{}, // задержаться со сдачей работы
rus_verbs:плавать{}, // плавать со спасательным кругом
rus_verbs:якшаться{}, // Не якшайся с врагами
инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
инфинитив:ассоциировать{вид:несоверш},
глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
глагол:ассоциировать{вид:несоверш},
//+прилагательное:ассоциировавший{вид:несоверш},
прилагательное:ассоциировавший{вид:соверш},
прилагательное:ассоциирующий{},
деепричастие:ассоциируя{},
деепричастие:ассоциировав{},
rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем
rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов
rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов
//+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом
//+глагол:аффилировать{вид:соверш},
прилагательное:аффилированный{},
rus_verbs:баловаться{}, // мальчик баловался с молотком
rus_verbs:балясничать{}, // женщина балясничала с товарками
rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями
rus_verbs:бодаться{}, // теленок бодается с деревом
rus_verbs:боксировать{}, // Майкл дважды боксировал с ним
rus_verbs:брататься{}, // Солдаты братались с бойцами союзников
rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:происходить{}, // Что происходит с мировой экономикой?
rus_verbs:произойти{}, // Что произошло с экономикой?
rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами
rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями
rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:водиться{}, // Няня водится с детьми
rus_verbs:воевать{}, // Фермеры воевали с волками
rus_verbs:возиться{}, // Няня возится с детьми
rus_verbs:ворковать{}, // Голубь воркует с голубкой
rus_verbs:воссоединиться{}, // Дети воссоединились с семьей
rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей
rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой
rus_verbs:враждовать{}, // враждовать с соседями
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:расстаться{}, // я не могу расстаться с тобой
rus_verbs:выдирать{}, // выдирать с мясом
rus_verbs:выдираться{}, // выдираться с мясом
rus_verbs:вытворить{}, // вытворить что-либо с чем-либо
rus_verbs:вытворять{}, // вытворять что-либо с чем-либо
rus_verbs:сделать{}, // сделать с чем-то
rus_verbs:домыть{}, // домыть с мылом
rus_verbs:случиться{}, // случиться с кем-то
rus_verbs:остаться{}, // остаться с кем-то
rus_verbs:случать{}, // случать с породистым кобельком
rus_verbs:послать{}, // послать с весточкой
rus_verbs:работать{}, // работать с роботами
rus_verbs:провести{}, // провести с девчонками время
rus_verbs:заговорить{}, // заговорить с незнакомкой
rus_verbs:прошептать{}, // прошептать с придыханием
rus_verbs:читать{}, // читать с выражением
rus_verbs:слушать{}, // слушать с повышенным вниманием
rus_verbs:принести{}, // принести с собой
rus_verbs:спать{}, // спать с женщинами
rus_verbs:закончить{}, // закончить с приготовлениями
rus_verbs:помочь{}, // помочь с перестановкой
rus_verbs:уехать{}, // уехать с семьей
rus_verbs:случаться{}, // случаться с кем-то
rus_verbs:кутить{}, // кутить с проститутками
rus_verbs:разговаривать{}, // разговаривать с ребенком
rus_verbs:погодить{}, // погодить с ликвидацией
rus_verbs:считаться{}, // считаться с чужим мнением
rus_verbs:носить{}, // носить с собой
rus_verbs:хорошеть{}, // хорошеть с каждым днем
rus_verbs:приводить{}, // приводить с собой
rus_verbs:прыгнуть{}, // прыгнуть с парашютом
rus_verbs:петь{}, // петь с чувством
rus_verbs:сложить{}, // сложить с результатом
rus_verbs:познакомиться{}, // познакомиться с другими студентами
rus_verbs:обращаться{}, // обращаться с животными
rus_verbs:съесть{}, // съесть с хлебом
rus_verbs:ошибаться{}, // ошибаться с дозировкой
rus_verbs:столкнуться{}, // столкнуться с медведем
rus_verbs:справиться{}, // справиться с нуждой
rus_verbs:торопиться{}, // торопиться с ответом
rus_verbs:поздравлять{}, // поздравлять с победой
rus_verbs:объясняться{}, // объясняться с начальством
rus_verbs:пошутить{}, // пошутить с подругой
rus_verbs:поздороваться{}, // поздороваться с коллегами
rus_verbs:поступать{}, // Как поступать с таким поведением?
rus_verbs:определяться{}, // определяться с кандидатами
rus_verbs:связаться{}, // связаться с поставщиком
rus_verbs:спорить{}, // спорить с собеседником
rus_verbs:разобраться{}, // разобраться с делами
rus_verbs:ловить{}, // ловить с удочкой
rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос
rus_verbs:шутить{}, // шутить с диким зверем
rus_verbs:разорвать{}, // разорвать с поставщиком контракт
rus_verbs:увезти{}, // увезти с собой
rus_verbs:унести{}, // унести с собой
rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее
rus_verbs:складываться{}, // складываться с первым импульсом
rus_verbs:соглашаться{}, // соглашаться с предложенным договором
//rus_verbs:покончить{}, // покончить с развратом
rus_verbs:прихватить{}, // прихватить с собой
rus_verbs:похоронить{}, // похоронить с почестями
rus_verbs:связывать{}, // связывать с компанией свою судьбу
rus_verbs:совпадать{}, // совпадать с предсказанием
rus_verbs:танцевать{}, // танцевать с девушками
rus_verbs:поделиться{}, // поделиться с выжившими
rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате.
rus_verbs:беседовать{}, // преподаватель, беседующий со студентами
rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью
rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой
rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками
rus_verbs:поговорить{}, // поговорить с виновниками
rus_verbs:сказать{}, // сказать с трудом
rus_verbs:произнести{}, // произнести с трудом
rus_verbs:говорить{}, // говорить с акцентом
rus_verbs:произносить{}, // произносить с трудом
rus_verbs:встречаться{}, // кто с Антонио встречался?
rus_verbs:посидеть{}, // посидеть с друзьями
rus_verbs:расквитаться{}, // расквитаться с обидчиком
rus_verbs:поквитаться{}, // поквитаться с обидчиком
rus_verbs:ругаться{}, // ругаться с женой
rus_verbs:поскандалить{}, // поскандалить с женой
rus_verbs:потанцевать{}, // потанцевать с подругой
rus_verbs:скандалить{}, // скандалить с соседями
rus_verbs:разругаться{}, // разругаться с другом
rus_verbs:болтать{}, // болтать с подругами
rus_verbs:потрепаться{}, // потрепаться с соседкой
rus_verbs:войти{}, // войти с регистрацией
rus_verbs:входить{}, // входить с регистрацией
rus_verbs:возвращаться{}, // возвращаться с триумфом
rus_verbs:опоздать{}, // Он опоздал с подачей сочинения.
rus_verbs:молчать{}, // Он молчал с ледяным спокойствием.
rus_verbs:сражаться{}, // Он героически сражался с врагами.
rus_verbs:выходить{}, // Он всегда выходит с зонтиком.
rus_verbs:сличать{}, // сличать перевод с оригиналом
rus_verbs:начать{}, // я начал с товарищем спор о религии
rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки
rus_verbs:приходить{}, // Приходите с нею.
rus_verbs:жить{}, // кто с тобой жил?
rus_verbs:расходиться{}, // Маша расходится с Петей
rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой
rus_verbs:торговать{}, // мы торгуем с ними нефтью
rus_verbs:уединяться{}, // уединяться с подругой в доме
rus_verbs:уладить{}, // уладить конфликт с соседями
rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем.
rus_verbs:разделять{}, // Я разделяю с вами горе и радость.
rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи.
rus_verbs:захватить{}, // Я не захватил с собой денег.
прилагательное:знакомый{}, // Я знаком с ними обоими.
rus_verbs:вести{}, // Я веду с ней переписку.
прилагательное:сопряженный{}, // Это сопряжено с большими трудностями.
прилагательное:связанный{причастие}, // Это дело связано с риском.
rus_verbs:поехать{}, // Хотите поехать со мной в театр?
rus_verbs:проснуться{}, // Утром я проснулся с ясной головой.
rus_verbs:лететь{}, // Самолёт летел со скоростью звука.
rus_verbs:играть{}, // С огнём играть опасно!
rus_verbs:поделать{}, // С ним ничего не поделаешь.
rus_verbs:стрястись{}, // С ней стряслось несчастье.
rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием.
rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием.
rus_verbs:разойтись{}, // Она разошлась с мужем.
rus_verbs:пристать{}, // Она пристала ко мне с расспросами.
rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением.
rus_verbs:поступить{}, // Она плохо поступила с ним.
rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом.
rus_verbs:взять{}, // Возьмите с собой только самое необходимое.
rus_verbs:наплакаться{}, // Наплачется она с ним.
rus_verbs:лежать{}, // Он лежит с воспалением лёгких.
rus_verbs:дышать{}, // дышащий с трудом
rus_verbs:брать{}, // брать с собой
rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой.
rus_verbs:упасть{}, // Ваза упала со звоном.
rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком
rus_verbs:сидеть{}, // Она сидит дома с ребенком
rus_verbs:встретиться{}, // встречаться с кем-либо
ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом
ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{},
rus_verbs:мыть{}
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} }
then return true
}
#endregion ТВОРИТЕЛЬНЫЙ
#region РОДИТЕЛЬНЫЙ
wordentry_set Гл_С_Род=
{
rus_verbs:УХОДИТЬ{}, // Но с базы не уходить.
rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ)
rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ)
rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ)
rus_verbs:РАЗГЛЯДЕТЬ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ)
rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ)
rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ)
rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ)
rus_verbs:ЗАРЕВЕТЬ{}, //
rus_verbs:ПРОРЕВЕТЬ{}, //
rus_verbs:ЗАОРАТЬ{}, //
rus_verbs:ПРООРАТЬ{}, //
rus_verbs:ОРАТЬ{}, //
rus_verbs:ЗАКРИЧАТЬ{},
rus_verbs:ВОПИТЬ{}, //
rus_verbs:ЗАВОПИТЬ{}, //
rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ)
rus_verbs:СТАСКИВАТЬ{}, //
rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ)
rus_verbs:ЗАВЫТЬ{}, //
rus_verbs:ВЫТЬ{}, //
rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ)
rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:собирать{}, // мальчики начали собирать со столов посуду
rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал
rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ)
rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ)
rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ)
rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ)
rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ)
rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род)
rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род)
rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С)
rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С)
rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род)
rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С)
rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С)
rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С)
rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род)
rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род)
rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род)
rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род)
rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род)
rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С)
rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род)
rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род)
rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род)
rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род)
rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род)
rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род)
rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С)
rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род)
rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род)
rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род)
rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С)
rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С)
rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С)
прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С)
rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С)
rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род)
rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С)
rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с)
rus_verbs:спасть{}, // тяжесть спала с души. (спасть с)
rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С)
rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С)
rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С)
rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то)
rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С)
rus_verbs:приближаться{}, // со стороны острова приближалась лодка.
rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С)
rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с)
rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с)
rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С)
rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С)
rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С)
rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С)
rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С)
rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С)
rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С)
rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С)
rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С)
rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С)
rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с)
rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С)
rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с)
rus_verbs:вставать{}, // Он не встает с кровати. (вставать с)
rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с)
rus_verbs:причитаться{}, // С вас причитается 50 рублей.
rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки.
rus_verbs:сократить{}, // Его сократили со службы.
rus_verbs:поднять{}, // рука подняла с пола
rus_verbs:поднимать{},
rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни.
rus_verbs:полететь{}, // Мальчик полетел с лестницы.
rus_verbs:литься{}, // вода льется с неба
rus_verbs:натечь{}, // натечь с сапог
rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая
rus_verbs:съезжать{}, // съезжать с заявленной темы
rus_verbs:покатываться{}, // покатываться со смеху
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:сдирать{}, // сдирать с тела кожу
rus_verbs:соскальзывать{}, // соскальзывать с крючка
rus_verbs:сметать{}, // сметать с прилавков
rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки
rus_verbs:прокаркать{}, // прокаркать с ветки
rus_verbs:стряхивать{}, // стряхивать с одежды
rus_verbs:сваливаться{}, // сваливаться с лестницы
rus_verbs:слизнуть{}, // слизнуть с лица
rus_verbs:доставляться{}, // доставляться с фермы
rus_verbs:обступать{}, // обступать с двух сторон
rus_verbs:повскакивать{}, // повскакивать с мест
rus_verbs:обозревать{}, // обозревать с вершины
rus_verbs:слинять{}, // слинять с урока
rus_verbs:смывать{}, // смывать с лица
rus_verbs:спихнуть{}, // спихнуть со стола
rus_verbs:обозреть{}, // обозреть с вершины
rus_verbs:накупить{}, // накупить с рук
rus_verbs:схлынуть{}, // схлынуть с берега
rus_verbs:спикировать{}, // спикировать с километровой высоты
rus_verbs:уползти{}, // уползти с поля боя
rus_verbs:сбиваться{}, // сбиваться с пути
rus_verbs:отлучиться{}, // отлучиться с поста
rus_verbs:сигануть{}, // сигануть с крыши
rus_verbs:сместить{}, // сместить с поста
rus_verbs:списать{}, // списать с оригинального устройства
инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы
деепричастие:слетая{},
rus_verbs:напиваться{}, // напиваться с горя
rus_verbs:свесить{}, // свесить с крыши
rus_verbs:заполучить{}, // заполучить со склада
rus_verbs:спадать{}, // спадать с глаз
rus_verbs:стартовать{}, // стартовать с мыса
rus_verbs:спереть{}, // спереть со склада
rus_verbs:согнать{}, // согнать с живота
rus_verbs:скатываться{}, // скатываться со стога
rus_verbs:сняться{}, // сняться с выборов
rus_verbs:слезать{}, // слезать со стола
rus_verbs:деваться{}, // деваться с подводной лодки
rus_verbs:огласить{}, // огласить с трибуны
rus_verbs:красть{}, // красть со склада
rus_verbs:расширить{}, // расширить с торца
rus_verbs:угадывать{}, // угадывать с полуслова
rus_verbs:оскорбить{}, // оскорбить со сцены
rus_verbs:срывать{}, // срывать с головы
rus_verbs:сшибить{}, // сшибить с коня
rus_verbs:сбивать{}, // сбивать с одежды
rus_verbs:содрать{}, // содрать с посетителей
rus_verbs:столкнуть{}, // столкнуть с горы
rus_verbs:отряхнуть{}, // отряхнуть с одежды
rus_verbs:сбрасывать{}, // сбрасывать с борта
rus_verbs:расстреливать{}, // расстреливать с борта вертолета
rus_verbs:придти{}, // мать скоро придет с работы
rus_verbs:съехать{}, // Миша съехал с горки
rus_verbs:свисать{}, // свисать с веток
rus_verbs:стянуть{}, // стянуть с кровати
rus_verbs:скинуть{}, // скинуть снег с плеча
rus_verbs:загреметь{}, // загреметь со стула
rus_verbs:сыпаться{}, // сыпаться с неба
rus_verbs:стряхнуть{}, // стряхнуть с головы
rus_verbs:сползти{}, // сползти со стула
rus_verbs:стереть{}, // стереть с экрана
rus_verbs:прогнать{}, // прогнать с фермы
rus_verbs:смахнуть{}, // смахнуть со стола
rus_verbs:спускать{}, // спускать с поводка
rus_verbs:деться{}, // деться с подводной лодки
rus_verbs:сдернуть{}, // сдернуть с себя
rus_verbs:сдвинуться{}, // сдвинуться с места
rus_verbs:слететь{}, // слететь с катушек
rus_verbs:обступить{}, // обступить со всех сторон
rus_verbs:снести{}, // снести с плеч
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков
деепричастие:сбегая{}, прилагательное:сбегающий{},
// прилагательное:сбегавший{ вид:несоверш },
rus_verbs:запить{}, // запить с горя
rus_verbs:рубануть{}, // рубануть с плеча
rus_verbs:чертыхнуться{}, // чертыхнуться с досады
rus_verbs:срываться{}, // срываться с цепи
rus_verbs:смыться{}, // смыться с уроков
rus_verbs:похитить{}, // похитить со склада
rus_verbs:смести{}, // смести со своего пути
rus_verbs:отгружать{}, // отгружать со склада
rus_verbs:отгрузить{}, // отгрузить со склада
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя
rus_verbs:взиматься{}, // Плата взимается с любого посетителя
rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги
rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги
rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков
rus_verbs:вспархивать{}, // вспархивать с цветка
rus_verbs:вспорхнуть{}, // вспорхнуть с ветки
rus_verbs:выбросить{}, // выбросить что-то с балкона
rus_verbs:выводить{}, // выводить с одежды пятна
rus_verbs:снять{}, // снять с головы
rus_verbs:начинать{}, // начинать с эскиза
rus_verbs:двинуться{}, // двинуться с места
rus_verbs:начинаться{}, // начинаться с гардероба
rus_verbs:стечь{}, // стечь с крыши
rus_verbs:слезть{}, // слезть с кучи
rus_verbs:спуститься{}, // спуститься с крыши
rus_verbs:сойти{}, // сойти с пьедестала
rus_verbs:свернуть{}, // свернуть с пути
rus_verbs:сорвать{}, // сорвать с цепи
rus_verbs:сорваться{}, // сорваться с поводка
rus_verbs:тронуться{}, // тронуться с места
rus_verbs:угадать{}, // угадать с первой попытки
rus_verbs:спустить{}, // спустить с лестницы
rus_verbs:соскочить{}, // соскочить с крючка
rus_verbs:сдвинуть{}, // сдвинуть с места
rus_verbs:подниматься{}, // туман, поднимающийся с болота
rus_verbs:подняться{}, // туман, поднявшийся с болота
rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног.
rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног.
rus_verbs:донестись{}, // С улицы донесся шум дождя.
rus_verbs:опасть{}, // Опавшие с дерева листья.
rus_verbs:махнуть{}, // Он махнул с берега в воду.
rus_verbs:исчезнуть{}, // исчезнуть с экрана
rus_verbs:свалиться{}, // свалиться со сцены
rus_verbs:упасть{}, // упасть с дерева
rus_verbs:вернуться{}, // Он ещё не вернулся с работы.
rus_verbs:сдувать{}, // сдувать пух с одуванчиков
rus_verbs:свергать{}, // свергать царя с трона
rus_verbs:сбиться{}, // сбиться с пути
rus_verbs:стирать{}, // стирать тряпкой надпись с доски
rus_verbs:убирать{}, // убирать мусор c пола
rus_verbs:удалять{}, // удалять игрока с поля
rus_verbs:окружить{}, // Япония окружена со всех сторон морями.
rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение.
глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы.
прилагательное:спокойный{}, // С этой стороны я спокоен.
rus_verbs:спросить{}, // С тебя за всё спросят.
rus_verbs:течь{}, // С него течёт пот.
rus_verbs:дуть{}, // С моря дует ветер.
rus_verbs:капать{}, // С его лица капали крупные капли пота.
rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол.
rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня.
rus_verbs:встать{}, // Все встали со стульев.
rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто.
rus_verbs:взять{}, // Возьми книгу с полки.
rus_verbs:спускаться{}, // Мы спускались с горы.
rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы.
rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок.
rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы.
rus_verbs:двигаться{}, // Он не двигался с места.
rus_verbs:отходить{}, // мой поезд отходит с первого пути
rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции
rus_verbs:падать{}, // снег падает с ветвей
rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия.
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:род} }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:парт} }
then return true
}
#endregion РОДИТЕЛЬНЫЙ
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:твор } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:род } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:с{} * }
then return false,-5
}
#endregion Предлог_С
/*
#region Предлог_ПОД
// -------------- ПРЕДЛОГ 'ПОД' -----------------------
fact гл_предл
{
if context { * предлог:под{} @regex("[a-z]+[0-9]*") }
then return true
}
// ПОД+вин.п. не может присоединяться к существительным, поэтому
// он присоединяется к любым глаголам.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return true
}
wordentry_set Гл_ПОД_твор=
{
rus_verbs:извиваться{}, // извивалась под его длинными усами
rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ)
rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ)
rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ)
rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ)
rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ)
rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ)
rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть)
rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ)
rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ)
rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ)
rus_verbs:ПРОПОЛЗТИ{}, //
rus_verbs:ПРОПОЛЗАТЬ{}, //
rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ)
rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ)
rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ)
rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ)
rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ)
rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом
rus_verbs:иметься{}, // у каждого под рукой имелся арбалет
rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ)
rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ)
rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ)
rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ)
rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ)
rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ)
rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ)
rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ)
rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ)
rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ)
rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ)
rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ)
rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ)
rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор)
rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ)
rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ)
rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ)
rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ)
rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ)
rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ)
rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ)
rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ)
rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ)
rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ)
rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ)
rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ)
rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ)
rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ)
rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ)
rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ)
rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ)
rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ)
rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ)
rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ)
rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД)
rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ)
rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД)
rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ)
rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ)
rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ)
rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ)
rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ)
rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ)
rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ)
rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ)
rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ)
rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ)
rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ)
rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ)
rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ)
rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ)
rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ)
rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ)
rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ)
rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ)
rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ)
rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ)
rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ)
rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ)
rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ)
rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ)
rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ)
rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ)
rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ)
rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ)
rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ)
rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ)
rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД)
rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД)
rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД)
rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД)
rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД)
rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД)
rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД)
rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД)
rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор)
rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД)
rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД)
rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД)
rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД)
rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД)
rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД)
rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД)
rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД)
rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД)
rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД)
rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД)
rus_verbs:уснуть{}, // Миша уснет под одеялом
rus_verbs:пошевелиться{}, // пошевелиться под одеялом
rus_verbs:задохнуться{}, // задохнуться под слоем снега
rus_verbs:потечь{}, // потечь под избыточным давлением
rus_verbs:уцелеть{}, // уцелеть под завалами
rus_verbs:мерцать{}, // мерцать под лучами софитов
rus_verbs:поискать{}, // поискать под кроватью
rus_verbs:гудеть{}, // гудеть под нагрузкой
rus_verbs:посидеть{}, // посидеть под навесом
rus_verbs:укрыться{}, // укрыться под навесом
rus_verbs:утихнуть{}, // утихнуть под одеялом
rus_verbs:заскрипеть{}, // заскрипеть под тяжестью
rus_verbs:шелохнуться{}, // шелохнуться под одеялом
инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень
деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш },
инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш },
деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш },
rus_verbs:пониматься{}, // пониматься под успехом
rus_verbs:подразумеваться{}, // подразумеваться под правильным решением
rus_verbs:промокнуть{}, // промокнуть под проливным дождем
rus_verbs:засосать{}, // засосать под ложечкой
rus_verbs:подписаться{}, // подписаться под воззванием
rus_verbs:укрываться{}, // укрываться под навесом
rus_verbs:запыхтеть{}, // запыхтеть под одеялом
rus_verbs:мокнуть{}, // мокнуть под лождем
rus_verbs:сгибаться{}, // сгибаться под тяжестью снега
rus_verbs:намокнуть{}, // намокнуть под дождем
rus_verbs:подписываться{}, // подписываться под обращением
rus_verbs:тарахтеть{}, // тарахтеть под окнами
инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача.
деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{},
rus_verbs:лежать{}, // лежать под капельницей
rus_verbs:вымокать{}, // вымокать под дождём
rus_verbs:вымокнуть{}, // вымокнуть под дождём
rus_verbs:проворчать{}, // проворчать под нос
rus_verbs:хмыкнуть{}, // хмыкнуть под нос
rus_verbs:отыскать{}, // отыскать под кроватью
rus_verbs:дрогнуть{}, // дрогнуть под ударами
rus_verbs:проявляться{}, // проявляться под нагрузкой
rus_verbs:сдержать{}, // сдержать под контролем
rus_verbs:ложиться{}, // ложиться под клиента
rus_verbs:таять{}, // таять под весенним солнцем
rus_verbs:покатиться{}, // покатиться под откос
rus_verbs:лечь{}, // он лег под навесом
rus_verbs:идти{}, // идти под дождем
прилагательное:известный{}, // Он известен под этим именем.
rus_verbs:стоять{}, // Ящик стоит под столом.
rus_verbs:отступить{}, // Враг отступил под ударами наших войск.
rus_verbs:царапаться{}, // Мышь царапается под полом.
rus_verbs:спать{}, // заяц спокойно спал у себя под кустом
rus_verbs:загорать{}, // мы загораем под солнцем
ГЛ_ИНФ(мыть), // мыть руки под струёй воды
ГЛ_ИНФ(закопать),
ГЛ_ИНФ(спрятать),
ГЛ_ИНФ(прятать),
ГЛ_ИНФ(перепрятать)
}
fact гл_предл
{
if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } }
then return true
}
// для глаголов вне списка - запрещаем.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return false,-10
}
fact гл_предл
{
if context { * предлог:под{} *:*{} }
then return false,-11
}
#endregion Предлог_ПОД
*/
#region Предлог_ОБ
// -------------- ПРЕДЛОГ 'ОБ' -----------------------
wordentry_set Гл_ОБ_предл=
{
rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ)
rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ)
rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ)
rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом?
rus_verbs:забывать{}, // Мы не можем забывать об их участи.
rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ)
rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ)
rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ)
rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ)
rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ)
rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ)
rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ)
rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ)
rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ)
rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ)
rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об)
rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об)
rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ)
rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ)
rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ)
rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе.
rus_verbs:кричать{}, // Все газеты кричат об этом событии.
rus_verbs:советоваться{}, // Она обо всём советуется с матерью.
rus_verbs:говориться{}, // об остальном говорилось легко.
rus_verbs:подумать{}, // нужно крепко обо всем подумать.
rus_verbs:напомнить{}, // черный дым напомнил об опасности.
rus_verbs:забыть{}, // забудь об этой роскоши.
rus_verbs:думать{}, // приходится обо всем думать самой.
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:информировать{}, // информировать об изменениях
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:заговорить{}, // заговорить об оплате
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:попросить{}, // попросить об услуге
rus_verbs:объявить{}, // объявить об отставке
rus_verbs:предупредить{}, // предупредить об аварии
rus_verbs:предупреждать{}, // предупреждать об опасности
rus_verbs:твердить{}, // твердить об обязанностях
rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:прочитать{}, // он читал об этом в учебнике
rus_verbs:узнать{}, // он узнал об этом из фильмов
rus_verbs:рассказать{}, // рассказать об экзаменах
rus_verbs:рассказывать{},
rus_verbs:договориться{}, // договориться об оплате
rus_verbs:договариваться{}, // договариваться об обмене
rus_verbs:болтать{}, // Не болтай об этом!
rus_verbs:проболтаться{}, // Не проболтайся об этом!
rus_verbs:заботиться{}, // кто заботится об урегулировании
rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне
rus_verbs:помнить{}, // всем советую об этом помнить
rus_verbs:мечтать{} // Мечтать об успехе
}
fact гл_предл
{
if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { * предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
// остальные глаголы не могут связываться
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:предл } }
then return false, -4
}
wordentry_set Гл_ОБ_вин=
{
rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ)
rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ)
rus_verbs:опереться{}, // Он опёрся об стену.
rus_verbs:опираться{},
rus_verbs:постучать{}, // постучал лбом об пол.
rus_verbs:удариться{}, // бутылка глухо ударилась об землю.
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:царапаться{} // Днище лодки царапалось обо что-то.
}
fact гл_предл
{
if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:об{} *:*{} }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_О
// ------------------- С ПРЕДЛОГОМ 'О' ----------------------
wordentry_set Гл_О_Вин={
rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену.
rus_verbs:болтать{}, // Болтали чаще всего о пустяках.
rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг.
rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол.
rus_verbs:бахнуться{}, // Бахнуться головой о стол.
rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ)
rus_verbs:ВЫТИРАТЬ{}, //
rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ)
rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ)
rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ)
rus_verbs:ЛЯЗГАТЬ{}, //
rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки
rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ)
rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ)
rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ)
rus_verbs:колотиться{}, // сердце его колотилось о ребра
rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей.
rus_verbs:биться{}, // биться головой о стену? (биться о)
rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о)
rus_verbs:разбиваться{}, // волны разбивались о скалу
rus_verbs:разбивать{}, // Разбивает голову о прутья клетки.
rus_verbs:облокотиться{}, // облокотиться о стену
rus_verbs:точить{}, // точить о точильный камень
rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень
rus_verbs:потереться{}, // потереться о дерево
rus_verbs:ушибиться{}, // ушибиться о дерево
rus_verbs:тереться{}, // тереться о ствол
rus_verbs:шмякнуться{}, // шмякнуться о землю
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:тереть{}, // тереть о камень
rus_verbs:потереть{}, // потереть о колено
rus_verbs:удариться{}, // удариться о край
rus_verbs:споткнуться{}, // споткнуться о камень
rus_verbs:запнуться{}, // запнуться о камень
rus_verbs:запинаться{}, // запинаться о камни
rus_verbs:ударяться{}, // ударяться о бортик
rus_verbs:стукнуться{}, // стукнуться о бортик
rus_verbs:стукаться{}, // стукаться о бортик
rus_verbs:опереться{}, // Он опёрся локтями о стол.
rus_verbs:плескаться{} // Вода плещется о берег.
}
fact гл_предл
{
if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
wordentry_set Гл_О_предл={
rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ)
rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ)
rus_verbs:РАССПРАШИВАТЬ{}, //
rus_verbs:слушать{}, // ты будешь слушать о них?
rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно
rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ)
rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ)
rus_verbs:сложить{}, // о вас сложены легенды
rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О)
rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О)
rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О)
rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О)
rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О)
rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О)
rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О)
rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О)
rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О)
rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О)
rus_verbs:осведомиться{}, // офицер осведомился о цели визита
rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о)
rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О)
rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о)
rus_verbs:зайти{}, // Разговор зашёл о политике.
rus_verbs:порассказать{}, // порассказать о своих путешествиях
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви
деепричастие:спев{}, прилагательное:спевший{ вид:соверш },
прилагательное:спетый{},
rus_verbs:напеть{},
rus_verbs:разговаривать{}, // разговаривать с другом о жизни
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
//rus_verbs:заботиться{}, // заботиться о престарелых родителях
rus_verbs:раздумывать{}, // раздумывать о новой работе
rus_verbs:договариваться{}, // договариваться о сумме компенсации
rus_verbs:молить{}, // молить о пощаде
rus_verbs:отзываться{}, // отзываться о книге
rus_verbs:подумывать{}, // подумывать о новом подходе
rus_verbs:поговаривать{}, // поговаривать о загадочном звере
rus_verbs:обмолвиться{}, // обмолвиться о проклятии
rus_verbs:условиться{}, // условиться о поддержке
rus_verbs:призадуматься{}, // призадуматься о последствиях
rus_verbs:известить{}, // известить о поступлении
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:напевать{}, // напевать о любви
rus_verbs:помышлять{}, // помышлять о новом деле
rus_verbs:переговорить{}, // переговорить о правилах
rus_verbs:повествовать{}, // повествовать о событиях
rus_verbs:слыхивать{}, // слыхивать о чудище
rus_verbs:потолковать{}, // потолковать о планах
rus_verbs:проговориться{}, // проговориться о планах
rus_verbs:умолчать{}, // умолчать о штрафах
rus_verbs:хлопотать{}, // хлопотать о премии
rus_verbs:уведомить{}, // уведомить о поступлении
rus_verbs:горевать{}, // горевать о потере
rus_verbs:запамятовать{}, // запамятовать о важном мероприятии
rus_verbs:заикнуться{}, // заикнуться о прибавке
rus_verbs:информировать{}, // информировать о событиях
rus_verbs:проболтаться{}, // проболтаться о кладе
rus_verbs:поразмыслить{}, // поразмыслить о судьбе
rus_verbs:заикаться{}, // заикаться о деньгах
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:печься{}, // печься о всеобщем благе
rus_verbs:разглагольствовать{}, // разглагольствовать о правах
rus_verbs:размечтаться{}, // размечтаться о будущем
rus_verbs:лепетать{}, // лепетать о невиновности
rus_verbs:грезить{}, // грезить о большой и чистой любви
rus_verbs:залепетать{}, // залепетать о сокровищах
rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде
rus_verbs:протрубить{}, // протрубить о победе
rus_verbs:извещать{}, // извещать о поступлении
rus_verbs:трубить{}, // трубить о поимке разбойников
rus_verbs:осведомляться{}, // осведомляться о судьбе
rus_verbs:поразмышлять{}, // поразмышлять о неизбежном
rus_verbs:слагать{}, // слагать о подвигах викингов
rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи
rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании
rus_verbs:закидывать{}, // закидывать сообщениями об ошибках
rus_verbs:базарить{}, // пацаны базарили о телках
rus_verbs:балагурить{}, // мужики балагурили о новом председателе
rus_verbs:балакать{}, // мужики балакали о новом председателе
rus_verbs:беспокоиться{}, // Она беспокоится о детях
rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве
rus_verbs:возмечтать{}, // возмечтать о счастливом мире
rus_verbs:вопить{}, // Кто-то вопил о несправедливости
rus_verbs:сказать{}, // сказать что-то новое о ком-то
rus_verbs:знать{}, // знать о ком-то что-то пикантное
rus_verbs:подумать{}, // подумать о чём-то
rus_verbs:думать{}, // думать о чём-то
rus_verbs:узнать{}, // узнать о происшествии
rus_verbs:помнить{}, // помнить о задании
rus_verbs:просить{}, // просить о коде доступа
rus_verbs:забыть{}, // забыть о своих обязанностях
rus_verbs:сообщить{}, // сообщить о заложенной мине
rus_verbs:заявить{}, // заявить о пропаже
rus_verbs:задуматься{}, // задуматься о смерти
rus_verbs:спрашивать{}, // спрашивать о поступлении товара
rus_verbs:догадаться{}, // догадаться о причинах
rus_verbs:договориться{}, // договориться о собеседовании
rus_verbs:мечтать{}, // мечтать о сцене
rus_verbs:поговорить{}, // поговорить о наболевшем
rus_verbs:размышлять{}, // размышлять о насущном
rus_verbs:напоминать{}, // напоминать о себе
rus_verbs:пожалеть{}, // пожалеть о содеянном
rus_verbs:ныть{}, // ныть о прибавке
rus_verbs:сообщать{}, // сообщать о победе
rus_verbs:догадываться{}, // догадываться о первопричине
rus_verbs:поведать{}, // поведать о тайнах
rus_verbs:умолять{}, // умолять о пощаде
rus_verbs:сожалеть{}, // сожалеть о случившемся
rus_verbs:жалеть{}, // жалеть о случившемся
rus_verbs:забывать{}, // забывать о случившемся
rus_verbs:упоминать{}, // упоминать о предках
rus_verbs:позабыть{}, // позабыть о своем обещании
rus_verbs:запеть{}, // запеть о любви
rus_verbs:скорбеть{}, // скорбеть о усопшем
rus_verbs:задумываться{}, // задумываться о смене работы
rus_verbs:позаботиться{}, // позаботиться о престарелых родителях
rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината
rus_verbs:попросить{}, // попросить о замене
rus_verbs:предупредить{}, // предупредить о замене
rus_verbs:предупреждать{}, // предупреждать о замене
rus_verbs:твердить{}, // твердить о замене
rus_verbs:заявлять{}, // заявлять о подлоге
rus_verbs:петь{}, // певица, поющая о лете
rus_verbs:проинформировать{}, // проинформировать о переговорах
rus_verbs:порассказывать{}, // порассказывать о событиях
rus_verbs:послушать{}, // послушать о новинках
rus_verbs:заговорить{}, // заговорить о плате
rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой.
rus_verbs:оставить{}, // Он оставил о себе печальную память.
rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях
rus_verbs:спорить{}, // они спорили о законе
глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия.
глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия.
rus_verbs:прочитать{}, // Я прочитал о тебе
rus_verbs:услышать{}, // Я услышал о нем
rus_verbs:помечтать{}, // Девочки помечтали о принце
rus_verbs:слышать{}, // Мальчик слышал о приведениях
rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке
rus_verbs:грустить{}, // Я грущу о тебе
rus_verbs:осведомить{}, // о последних достижениях науки
rus_verbs:рассказывать{}, // Антонио рассказывает о работе
rus_verbs:говорить{}, // говорим о трех больших псах
rus_verbs:идти{} // Вопрос идёт о войне.
}
fact гл_предл
{
if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } }
then return true
}
// Мы поделились впечатлениями о выставке.
// ^^^^^^^^^^ ^^^^^^^^^^
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:о{} *:*{} }
then return false,-5
}
#endregion Предлог_О
#region Предлог_ПО
// ------------------- С ПРЕДЛОГОМ 'ПО' ----------------------
// для этих глаголов - запрещаем связывание с ПО+дат.п.
wordentry_set Глаг_ПО_Дат_Запр=
{
rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:закончить{},
rus_verbs:мочь{},
rus_verbs:хотеть{}
}
fact гл_предл
{
if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } }
then return false,-10
}
// По умолчанию разрешаем связывание в паттернах типа
// Я иду по шоссе
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:дат } }
then return true
}
wordentry_set Глаг_ПО_Вин=
{
rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ)
rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО)
rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера
rus_verbs:засадить{}, // засадить по рукоятку
rus_verbs:увязнуть{} // увязнуть по колено
}
fact гл_предл
{
if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ПО
#region Предлог_К
// ------------------- С ПРЕДЛОГОМ 'К' ----------------------
wordentry_set Гл_К_Дат={
rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна.
rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску.
прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ)
rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ)
rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ)
rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ)
rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ)
rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ)
rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ)
rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ)
rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ)
rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, //
rus_verbs:ПРИНОРОВИТЬСЯ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ)
rus_verbs:СПИКИРОВАТЬ{}, //
rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С)
rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ)
rus_verbs:ПРОТЯНУТЬ{}, //
rus_verbs:ТЯНУТЬ{}, //
rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,,
rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, //
rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, //
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, //
rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ)
rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке.
rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ)
rus_verbs:хотеть{},
rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ)
rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ)
rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ)
rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ)
rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ)
rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ)
rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ)
rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ)
rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ)
rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г
rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ)
rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ)
rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К)
rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К)
rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К)
rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К)
rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К)
прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К)
безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К)
rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К)
rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К)
rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К)
rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К)
rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К)
rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К)
rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К)
rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К)
rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К)
rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К)
rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К)
rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К)
rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К)
rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К)
rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К)
rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К)
rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К)
rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К)
rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К)
rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К)
rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К)
rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К)
rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К)
глагол:быть{}, // к тебе есть вопросы.
прилагательное:равнодушный{}, // Он равнодушен к музыке.
rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К)
rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К)
инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К)
rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К)
rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к)
rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К)
rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К)
rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К)
rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К)
rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К)
rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К)
rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К)
rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к)
rus_verbs:просить{}, // Директор просит вас к себе. (просить к)
rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к)
rus_verbs:присесть{}, // старик присел к огню. (присесть к)
rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К)
rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к)
rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к)
rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К)
rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К)
rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К)
rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К)
rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к)
rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К)
rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К)
rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К)
rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К)
rus_verbs:подходить{}, // цвет подходил ей к лицу.
rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К)
rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К)
rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К)
rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К)
rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К)
rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К)
rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к)
rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К)
rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К)
rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к)
rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к)
rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К)
rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К)
rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К)
rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К)
rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к)
rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к)
rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к)
rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К)
rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к)
rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к)
rus_verbs:требовать{}, // вас требует к себе император. (требовать к)
rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к)
rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к)
rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К)
rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К)
rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к)
rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К)
rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К)
rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к)
rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к)
rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к)
rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К)
rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к)
rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к)
rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к)
rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К)
rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К)
rus_verbs:выехать{}, // почти сразу мы выехали к реке.
rus_verbs:пододвигаться{}, // пододвигайся к окну
rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам.
rus_verbs:представить{}, // Его представили к ордену.
rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу.
rus_verbs:выскочить{}, // тем временем они выскочили к реке.
rus_verbs:выйти{}, // тем временем они вышли к лестнице.
rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе.
rus_verbs:приложить{}, // приложить к детали повышенное усилие
rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку)
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю
rus_verbs:прыгать{}, // прыгать к хозяину на стол
rus_verbs:приглашать{}, // приглашать к доктору
rus_verbs:рваться{}, // Чужие люди рвутся к власти
rus_verbs:понестись{}, // понестись к обрыву
rus_verbs:питать{}, // питать привязанность к алкоголю
rus_verbs:заехать{}, // Коля заехал к Оле
rus_verbs:переехать{}, // переехать к родителям
rus_verbs:ползти{}, // ползти к дороге
rus_verbs:сводиться{}, // сводиться к элементарному действию
rus_verbs:добавлять{}, // добавлять к общей сумме
rus_verbs:подбросить{}, // подбросить к потолку
rus_verbs:призывать{}, // призывать к спокойствию
rus_verbs:пробираться{}, // пробираться к партизанам
rus_verbs:отвезти{}, // отвезти к родителям
rus_verbs:применяться{}, // применяться к уравнению
rus_verbs:сходиться{}, // сходиться к точному решению
rus_verbs:допускать{}, // допускать к сдаче зачета
rus_verbs:свести{}, // свести к нулю
rus_verbs:придвинуть{}, // придвинуть к мальчику
rus_verbs:подготовить{}, // подготовить к печати
rus_verbs:подобраться{}, // подобраться к оленю
rus_verbs:заторопиться{}, // заторопиться к выходу
rus_verbs:пристать{}, // пристать к берегу
rus_verbs:поманить{}, // поманить к себе
rus_verbs:припасть{}, // припасть к алтарю
rus_verbs:притащить{}, // притащить к себе домой
rus_verbs:прижимать{}, // прижимать к груди
rus_verbs:подсесть{}, // подсесть к симпатичной девочке
rus_verbs:придвинуться{}, // придвинуться к окну
rus_verbs:отпускать{}, // отпускать к другу
rus_verbs:пригнуться{}, // пригнуться к земле
rus_verbs:пристроиться{}, // пристроиться к колонне
rus_verbs:сгрести{}, // сгрести к себе
rus_verbs:удрать{}, // удрать к цыганам
rus_verbs:прибавиться{}, // прибавиться к общей сумме
rus_verbs:присмотреться{}, // присмотреться к покупке
rus_verbs:подкатить{}, // подкатить к трюму
rus_verbs:клонить{}, // клонить ко сну
rus_verbs:проследовать{}, // проследовать к выходу
rus_verbs:пододвинуть{}, // пододвинуть к себе
rus_verbs:применять{}, // применять к сотрудникам
rus_verbs:прильнуть{}, // прильнуть к экранам
rus_verbs:подвинуть{}, // подвинуть к себе
rus_verbs:примчаться{}, // примчаться к папе
rus_verbs:подкрасться{}, // подкрасться к жертве
rus_verbs:привязаться{}, // привязаться к собаке
rus_verbs:забирать{}, // забирать к себе
rus_verbs:прорваться{}, // прорваться к кассе
rus_verbs:прикасаться{}, // прикасаться к коже
rus_verbs:уносить{}, // уносить к себе
rus_verbs:подтянуться{}, // подтянуться к месту
rus_verbs:привозить{}, // привозить к ветеринару
rus_verbs:подползти{}, // подползти к зайцу
rus_verbs:приблизить{}, // приблизить к глазам
rus_verbs:применить{}, // применить к уравнению простое преобразование
rus_verbs:приглядеться{}, // приглядеться к изображению
rus_verbs:приложиться{}, // приложиться к ручке
rus_verbs:приставать{}, // приставать к девчонкам
rus_verbs:запрещаться{}, // запрещаться к показу
rus_verbs:прибегать{}, // прибегать к насилию
rus_verbs:побудить{}, // побудить к действиям
rus_verbs:притягивать{}, // притягивать к себе
rus_verbs:пристроить{}, // пристроить к полезному делу
rus_verbs:приговорить{}, // приговорить к смерти
rus_verbs:склоняться{}, // склоняться к прекращению разработки
rus_verbs:подъезжать{}, // подъезжать к вокзалу
rus_verbs:привалиться{}, // привалиться к забору
rus_verbs:наклоняться{}, // наклоняться к щенку
rus_verbs:подоспеть{}, // подоспеть к обеду
rus_verbs:прилипнуть{}, // прилипнуть к окну
rus_verbs:приволочь{}, // приволочь к себе
rus_verbs:устремляться{}, // устремляться к вершине
rus_verbs:откатиться{}, // откатиться к исходным позициям
rus_verbs:побуждать{}, // побуждать к действиям
rus_verbs:прискакать{}, // прискакать к кормежке
rus_verbs:присматриваться{}, // присматриваться к новичку
rus_verbs:прижиматься{}, // прижиматься к борту
rus_verbs:жаться{}, // жаться к огню
rus_verbs:передвинуть{}, // передвинуть к окну
rus_verbs:допускаться{}, // допускаться к экзаменам
rus_verbs:прикрепить{}, // прикрепить к корпусу
rus_verbs:отправлять{}, // отправлять к специалистам
rus_verbs:перебежать{}, // перебежать к врагам
rus_verbs:притронуться{}, // притронуться к реликвии
rus_verbs:заспешить{}, // заспешить к семье
rus_verbs:ревновать{}, // ревновать к сопернице
rus_verbs:подступить{}, // подступить к горлу
rus_verbs:уводить{}, // уводить к ветеринару
rus_verbs:побросать{}, // побросать к ногам
rus_verbs:подаваться{}, // подаваться к ужину
rus_verbs:приписывать{}, // приписывать к достижениям
rus_verbs:относить{}, // относить к растениям
rus_verbs:принюхаться{}, // принюхаться к ароматам
rus_verbs:подтащить{}, // подтащить к себе
rus_verbs:прислонить{}, // прислонить к стене
rus_verbs:подплыть{}, // подплыть к бую
rus_verbs:опаздывать{}, // опаздывать к стилисту
rus_verbs:примкнуть{}, // примкнуть к деомнстрантам
rus_verbs:стекаться{}, // стекаются к стенам тюрьмы
rus_verbs:подготовиться{}, // подготовиться к марафону
rus_verbs:приглядываться{}, // приглядываться к новичку
rus_verbs:присоединяться{}, // присоединяться к сообществу
rus_verbs:клониться{}, // клониться ко сну
rus_verbs:привыкать{}, // привыкать к хорошему
rus_verbs:принудить{}, // принудить к миру
rus_verbs:уплыть{}, // уплыть к далекому берегу
rus_verbs:утащить{}, // утащить к детенышам
rus_verbs:приплыть{}, // приплыть к финишу
rus_verbs:подбегать{}, // подбегать к хозяину
rus_verbs:лишаться{}, // лишаться средств к существованию
rus_verbs:приступать{}, // приступать к операции
rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике
rus_verbs:подключить{}, // подключить к трубе
rus_verbs:подключиться{}, // подключиться к сети
rus_verbs:прилить{}, // прилить к лицу
rus_verbs:стучаться{}, // стучаться к соседям
rus_verbs:пристегнуть{}, // пристегнуть к креслу
rus_verbs:присоединить{}, // присоединить к сети
rus_verbs:отбежать{}, // отбежать к противоположной стене
rus_verbs:подвезти{}, // подвезти к набережной
rus_verbs:прибегнуть{}, // прибегнуть к хитрости
rus_verbs:приучить{}, // приучить к туалету
rus_verbs:подталкивать{}, // подталкивать к выходу
rus_verbs:прорываться{}, // прорываться к выходу
rus_verbs:увозить{}, // увозить к ветеринару
rus_verbs:засеменить{}, // засеменить к выходу
rus_verbs:крепиться{}, // крепиться к потолку
rus_verbs:прибрать{}, // прибрать к рукам
rus_verbs:пристраститься{}, // пристраститься к наркотикам
rus_verbs:поспеть{}, // поспеть к обеду
rus_verbs:привязывать{}, // привязывать к дереву
rus_verbs:прилагать{}, // прилагать к документам
rus_verbs:переправить{}, // переправить к дедушке
rus_verbs:подогнать{}, // подогнать к воротам
rus_verbs:тяготеть{}, // тяготеть к социализму
rus_verbs:подбираться{}, // подбираться к оленю
rus_verbs:подступать{}, // подступать к горлу
rus_verbs:примыкать{}, // примыкать к первому элементу
rus_verbs:приладить{}, // приладить к велосипеду
rus_verbs:подбрасывать{}, // подбрасывать к потолку
rus_verbs:перевозить{}, // перевозить к новому месту дислокации
rus_verbs:усаживаться{}, // усаживаться к окну
rus_verbs:приближать{}, // приближать к глазам
rus_verbs:попроситься{}, // попроситься к бабушке
rus_verbs:прибить{}, // прибить к доске
rus_verbs:перетащить{}, // перетащить к себе
rus_verbs:прицепить{}, // прицепить к паровозу
rus_verbs:прикладывать{}, // прикладывать к ране
rus_verbs:устареть{}, // устареть к началу войны
rus_verbs:причалить{}, // причалить к пристани
rus_verbs:приспособиться{}, // приспособиться к опозданиям
rus_verbs:принуждать{}, // принуждать к миру
rus_verbs:соваться{}, // соваться к директору
rus_verbs:протолкаться{}, // протолкаться к прилавку
rus_verbs:приковать{}, // приковать к батарее
rus_verbs:подкрадываться{}, // подкрадываться к суслику
rus_verbs:подсадить{}, // подсадить к арестонту
rus_verbs:прикатить{}, // прикатить к финишу
rus_verbs:протащить{}, // протащить к владыке
rus_verbs:сужаться{}, // сужаться к основанию
rus_verbs:присовокупить{}, // присовокупить к пожеланиям
rus_verbs:пригвоздить{}, // пригвоздить к доске
rus_verbs:отсылать{}, // отсылать к первоисточнику
rus_verbs:изготовиться{}, // изготовиться к прыжку
rus_verbs:прилагаться{}, // прилагаться к покупке
rus_verbs:прицепиться{}, // прицепиться к вагону
rus_verbs:примешиваться{}, // примешиваться к вину
rus_verbs:переселить{}, // переселить к старшекурсникам
rus_verbs:затрусить{}, // затрусить к выходе
rus_verbs:приспособить{}, // приспособить к обогреву
rus_verbs:примериться{}, // примериться к аппарату
rus_verbs:прибавляться{}, // прибавляться к пенсии
rus_verbs:подкатиться{}, // подкатиться к воротам
rus_verbs:стягивать{}, // стягивать к границе
rus_verbs:дописать{}, // дописать к роману
rus_verbs:подпустить{}, // подпустить к корове
rus_verbs:склонять{}, // склонять к сотрудничеству
rus_verbs:припечатать{}, // припечатать к стене
rus_verbs:охладеть{}, // охладеть к музыке
rus_verbs:пришить{}, // пришить к шинели
rus_verbs:принюхиваться{}, // принюхиваться к ветру
rus_verbs:подрулить{}, // подрулить к барышне
rus_verbs:наведаться{}, // наведаться к оракулу
rus_verbs:клеиться{}, // клеиться к конверту
rus_verbs:перетянуть{}, // перетянуть к себе
rus_verbs:переметнуться{}, // переметнуться к конкурентам
rus_verbs:липнуть{}, // липнуть к сокурсницам
rus_verbs:поковырять{}, // поковырять к выходу
rus_verbs:подпускать{}, // подпускать к пульту управления
rus_verbs:присосаться{}, // присосаться к источнику
rus_verbs:приклеить{}, // приклеить к стеклу
rus_verbs:подтягивать{}, // подтягивать к себе
rus_verbs:подкатывать{}, // подкатывать к даме
rus_verbs:притрагиваться{}, // притрагиваться к опухоли
rus_verbs:слетаться{}, // слетаться к водопою
rus_verbs:хаживать{}, // хаживать к батюшке
rus_verbs:привлекаться{}, // привлекаться к административной ответственности
rus_verbs:подзывать{}, // подзывать к себе
rus_verbs:прикладываться{}, // прикладываться к иконе
rus_verbs:подтягиваться{}, // подтягиваться к парламенту
rus_verbs:прилепить{}, // прилепить к стенке холодильника
rus_verbs:пододвинуться{}, // пододвинуться к экрану
rus_verbs:приползти{}, // приползти к дереву
rus_verbs:запаздывать{}, // запаздывать к обеду
rus_verbs:припереть{}, // припереть к стене
rus_verbs:нагибаться{}, // нагибаться к цветку
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам
деепричастие:сгоняв{},
rus_verbs:поковылять{}, // поковылять к выходу
rus_verbs:привалить{}, // привалить к столбу
rus_verbs:отпроситься{}, // отпроситься к родителям
rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям
rus_verbs:прилипать{}, // прилипать к рукам
rus_verbs:подсоединить{}, // подсоединить к приборам
rus_verbs:приливать{}, // приливать к голове
rus_verbs:подселить{}, // подселить к другим новичкам
rus_verbs:прилепиться{}, // прилепиться к шкуре
rus_verbs:подлетать{}, // подлетать к пункту назначения
rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями
rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг
rus_verbs:льнуть{}, // льнуть к заботливому хозяину
rus_verbs:привязываться{}, // привязываться к любящему хозяину
rus_verbs:приклеиться{}, // приклеиться к спине
rus_verbs:стягиваться{}, // стягиваться к сенату
rus_verbs:подготавливать{}, // подготавливать к выходу на арену
rus_verbs:приглашаться{}, // приглашаться к доктору
rus_verbs:причислять{}, // причислять к отличникам
rus_verbs:приколоть{}, // приколоть к лацкану
rus_verbs:наклонять{}, // наклонять к горизонту
rus_verbs:припадать{}, // припадать к первоисточнику
rus_verbs:приобщиться{}, // приобщиться к культурному наследию
rus_verbs:придираться{}, // придираться к мелким ошибкам
rus_verbs:приучать{}, // приучать к лотку
rus_verbs:промотать{}, // промотать к началу
rus_verbs:прихлынуть{}, // прихлынуть к голове
rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу
rus_verbs:прикрутить{}, // прикрутить к велосипеду
rus_verbs:подплывать{}, // подплывать к лодке
rus_verbs:приравниваться{}, // приравниваться к побегу
rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами
rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы
rus_verbs:приткнуться{}, // приткнуться к первой группе туристов
rus_verbs:приручить{}, // приручить котика к лотку
rus_verbs:приковывать{}, // приковывать к себе все внимание прессы
rus_verbs:приготовляться{}, // приготовляться к первому экзамену
rus_verbs:остыть{}, // Вода остынет к утру.
rus_verbs:приехать{}, // Он приедет к концу будущей недели.
rus_verbs:подсаживаться{},
rus_verbs:успевать{}, // успевать к стилисту
rus_verbs:привлекать{}, // привлекать к себе внимание
прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму
rus_verbs:прийтись{}, // прийтись ко двору
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы
инфинитив:адаптироваться{вид:несоверш},
глагол:адаптироваться{вид:соверш},
глагол:адаптироваться{вид:несоверш},
деепричастие:адаптировавшись{},
деепричастие:адаптируясь{},
прилагательное:адаптировавшийся{вид:соверш},
//+прилагательное:адаптировавшийся{вид:несоверш},
прилагательное:адаптирующийся{},
rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей
rus_verbs:близиться{}, // Шторм близится к побережью
rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне
rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки
rus_verbs:причислить{}, // Мы причислили его к числу экспертов
rus_verbs:вести{}, // Наша партия ведет народ к процветанию
rus_verbs:взывать{}, // Учителя взывают к совести хулигана
rus_verbs:воззвать{}, // воззвать соплеменников к оружию
rus_verbs:возревновать{}, // возревновать к поклонникам
rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью
rus_verbs:восходить{}, // восходить к вершине
rus_verbs:восшествовать{}, // восшествовать к вершине
rus_verbs:успеть{}, // успеть к обеду
rus_verbs:повернуться{}, // повернуться к кому-то
rus_verbs:обратиться{}, // обратиться к охраннику
rus_verbs:звать{}, // звать к столу
rus_verbs:отправиться{}, // отправиться к парикмахеру
rus_verbs:обернуться{}, // обернуться к зовущему
rus_verbs:явиться{}, // явиться к следователю
rus_verbs:уехать{}, // уехать к родне
rus_verbs:прибыть{}, // прибыть к перекличке
rus_verbs:привыкнуть{}, // привыкнуть к голоду
rus_verbs:уходить{}, // уходить к цыганам
rus_verbs:привести{}, // привести к себе
rus_verbs:шагнуть{}, // шагнуть к славе
rus_verbs:относиться{}, // относиться к прежним периодам
rus_verbs:подослать{}, // подослать к врагам
rus_verbs:поспешить{}, // поспешить к обеду
rus_verbs:зайти{}, // зайти к подруге
rus_verbs:позвать{}, // позвать к себе
rus_verbs:потянуться{}, // потянуться к рычагам
rus_verbs:пускать{}, // пускать к себе
rus_verbs:отвести{}, // отвести к врачу
rus_verbs:приблизиться{}, // приблизиться к решению задачи
rus_verbs:прижать{}, // прижать к стене
rus_verbs:отправить{}, // отправить к доктору
rus_verbs:падать{}, // падать к многолетним минимумам
rus_verbs:полезть{}, // полезть к дерущимся
rus_verbs:лезть{}, // Ты сама ко мне лезла!
rus_verbs:направить{}, // направить к майору
rus_verbs:приводить{}, // приводить к дантисту
rus_verbs:кинуться{}, // кинуться к двери
rus_verbs:поднести{}, // поднести к глазам
rus_verbs:подниматься{}, // подниматься к себе
rus_verbs:прибавить{}, // прибавить к результату
rus_verbs:зашагать{}, // зашагать к выходу
rus_verbs:склониться{}, // склониться к земле
rus_verbs:стремиться{}, // стремиться к вершине
rus_verbs:лететь{}, // лететь к родственникам
rus_verbs:ездить{}, // ездить к любовнице
rus_verbs:приближаться{}, // приближаться к финише
rus_verbs:помчаться{}, // помчаться к стоматологу
rus_verbs:прислушаться{}, // прислушаться к происходящему
rus_verbs:изменить{}, // изменить к лучшему собственную жизнь
rus_verbs:проявить{}, // проявить к погибшим сострадание
rus_verbs:подбежать{}, // подбежать к упавшему
rus_verbs:терять{}, // терять к партнерам доверие
rus_verbs:пропустить{}, // пропустить к певцу
rus_verbs:подвести{}, // подвести к глазам
rus_verbs:меняться{}, // меняться к лучшему
rus_verbs:заходить{}, // заходить к другу
rus_verbs:рвануться{}, // рвануться к воде
rus_verbs:привлечь{}, // привлечь к себе внимание
rus_verbs:присоединиться{}, // присоединиться к сети
rus_verbs:приезжать{}, // приезжать к дедушке
rus_verbs:дернуться{}, // дернуться к борту
rus_verbs:подъехать{}, // подъехать к воротам
rus_verbs:готовиться{}, // готовиться к дождю
rus_verbs:убежать{}, // убежать к маме
rus_verbs:поднимать{}, // поднимать к источнику сигнала
rus_verbs:отослать{}, // отослать к руководителю
rus_verbs:приготовиться{}, // приготовиться к худшему
rus_verbs:приступить{}, // приступить к выполнению обязанностей
rus_verbs:метнуться{}, // метнуться к фонтану
rus_verbs:прислушиваться{}, // прислушиваться к голосу разума
rus_verbs:побрести{}, // побрести к выходу
rus_verbs:мчаться{}, // мчаться к успеху
rus_verbs:нестись{}, // нестись к обрыву
rus_verbs:попадать{}, // попадать к хорошему костоправу
rus_verbs:опоздать{}, // опоздать к психотерапевту
rus_verbs:посылать{}, // посылать к доктору
rus_verbs:поплыть{}, // поплыть к берегу
rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе
rus_verbs:отнести{}, // отнести животное к ветеринару
rus_verbs:прислониться{}, // прислониться к стволу
rus_verbs:наклонить{}, // наклонить к миске с молоком
rus_verbs:прикоснуться{}, // прикоснуться к поверхности
rus_verbs:увезти{}, // увезти к бабушке
rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия
rus_verbs:подозвать{}, // подозвать к себе
rus_verbs:улететь{}, // улететь к теплым берегам
rus_verbs:ложиться{}, // ложиться к мужу
rus_verbs:убираться{}, // убираться к чертовой бабушке
rus_verbs:класть{}, // класть к другим документам
rus_verbs:доставлять{}, // доставлять к подъезду
rus_verbs:поворачиваться{}, // поворачиваться к источнику шума
rus_verbs:заглядывать{}, // заглядывать к любовнице
rus_verbs:занести{}, // занести к заказчикам
rus_verbs:прибежать{}, // прибежать к папе
rus_verbs:притянуть{}, // притянуть к причалу
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:подать{}, // он подал лимузин к подъезду
rus_verbs:подавать{}, // она подавала соус к мясу
rus_verbs:приобщаться{}, // приобщаться к культуре
прилагательное:неспособный{}, // Наша дочка неспособна к учению.
прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару
прилагательное:предназначенный{}, // Старый дом предназначен к сносу.
прилагательное:внимательный{}, // Она всегда внимательна к гостям.
прилагательное:назначенный{}, // Дело назначено к докладу.
прилагательное:разрешенный{}, // Эта книга разрешена к печати.
прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам.
прилагательное:готовый{}, // Я готов к экзаменам.
прилагательное:требовательный{}, // Он очень требователен к себе.
прилагательное:жадный{}, // Он жаден к деньгам.
прилагательное:глухой{}, // Он глух к моей просьбе.
прилагательное:добрый{}, // Он добр к детям.
rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам.
rus_verbs:плыть{}, // Пароход плыл к берегу.
rus_verbs:пойти{}, // я пошел к доктору
rus_verbs:придти{}, // придти к выводу
rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом.
rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений.
rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам.
rus_verbs:спускаться{}, // Улица круто спускается к реке.
rus_verbs:спуститься{}, // Мы спустились к реке.
rus_verbs:пустить{}, // пускать ко дну
rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью!
rus_verbs:отойти{}, // Дом отошёл к племяннику.
rus_verbs:отходить{}, // Коля отходил ко сну.
rus_verbs:приходить{}, // местные жители к нему приходили лечиться
rus_verbs:кидаться{}, // не кидайся к столу
rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу.
rus_verbs:закончиться{}, // Собрание закончилось к вечеру.
rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему.
rus_verbs:направиться{}, // Мы сошли на берег и направились к городу.
rus_verbs:направляться{},
rus_verbs:свестись{}, // Всё свелось к нулю.
rus_verbs:прислать{}, // Пришлите кого-нибудь к ней.
rus_verbs:присылать{}, // Он присылал к должнику своих головорезов
rus_verbs:подлететь{}, // Самолёт подлетел к лесу.
rus_verbs:возвращаться{}, // он возвращается к старой работе
глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{},
прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая.
rus_verbs:возвращать{}, // возвращать к жизни
rus_verbs:располагать{}, // Атмосфера располагает к работе.
rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому.
rus_verbs:поступить{}, // К нам поступила жалоба.
rus_verbs:поступать{}, // К нам поступают жалобы.
rus_verbs:прыгнуть{}, // Белка прыгнула к дереву
rus_verbs:торопиться{}, // пассажиры торопятся к выходу
rus_verbs:поторопиться{}, // поторопитесь к выходу
rus_verbs:вернуть{}, // вернуть к активной жизни
rus_verbs:припирать{}, // припирать к стенке
rus_verbs:проваливать{}, // Проваливай ко всем чертям!
rus_verbs:вбежать{}, // Коля вбежал ко мне
rus_verbs:вбегать{}, // Коля вбегал ко мне
глагол:забегать{ вид:несоверш }, // Коля забегал ко мне
rus_verbs:постучаться{}, // Коля постучался ко мне.
rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому
rus_verbs:понести{}, // Мы понесли кота к ветеринару
rus_verbs:принести{}, // Я принес кота к ветеринару
rus_verbs:устремиться{}, // Мы устремились к ручью.
rus_verbs:подводить{}, // Учитель подводил детей к аквариуму
rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения.
rus_verbs:пригласить{}, // Я пригласил к себе товарищей.
rus_verbs:собираться{}, // Я собираюсь к тебе в гости.
rus_verbs:собраться{}, // Маша собралась к дантисту
rus_verbs:сходить{}, // Я схожу к врачу.
rus_verbs:идти{}, // Маша уверенно шла к Пете
rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию.
rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию.
rus_verbs:заканчивать{}, // Заканчивайте к обеду
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:окончить{}, //
rus_verbs:дозвониться{}, // Я не мог к вам дозвониться.
глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор
rus_verbs:уйти{}, // Антонио ушел к Элеонор
rus_verbs:бежать{}, // Антонио бежит к Элеонор
rus_verbs:спешить{}, // Антонио спешит к Элеонор
rus_verbs:скакать{}, // Антонио скачет к Элеонор
rus_verbs:красться{}, // Антонио крадётся к Элеонор
rus_verbs:поскакать{}, // беглецы поскакали к холмам
rus_verbs:перейти{} // Антонио перешел к Элеонор
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } }
then return true
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:к{} *:*{} }
then return false,-5
}
#endregion Предлог_К
#region Предлог_ДЛЯ
// ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ----------------------
wordentry_set Гл_ДЛЯ_Род={
частица:нет{}, // для меня нет других путей.
частица:нету{},
rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ)
rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ)
rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться)
rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ)
rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ)
rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ)
rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей
rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ)
rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ)
rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство
rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ)
rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ)
rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ)
rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ)
rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ)
rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ)
rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ)
rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ)
rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ)
rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ)
rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ)
rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ)
rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ)
rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ)
rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ)
rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ)
rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ)
rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ)
rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ)
rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ)
прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ)
rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ)
rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ)
rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ)
rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ)
rus_verbs:оставить{}, // или вообще решили оставить планету для себя
rus_verbs:оставлять{},
rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ)
rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ)
rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ)
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ)
rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ)
rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ)
rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ)
rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ)
rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для)
rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ)
rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ)
rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ)
rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ)
rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ)
прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ)
прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ)
прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ)
rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ)
rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ)
rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ)
rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ)
rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ)
rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ)
rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ)
rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ)
rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ)
rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ)
rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ)
прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ)
rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ)
rus_verbs:вывести{}, // мы специально вывели этих животных для мяса.
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для)
rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ)
rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ)
rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ)
rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ)
rus_verbs:найтись{}, // у вас найдется для него работа?
rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для)
rus_verbs:заехать{}, // Коля заехал для обсуждения проекта
rus_verbs:созреть{}, // созреть для побега
rus_verbs:наметить{}, // наметить для проверки
rus_verbs:уяснить{}, // уяснить для себя
rus_verbs:нанимать{}, // нанимать для разовой работы
rus_verbs:приспособить{}, // приспособить для удовольствия
rus_verbs:облюбовать{}, // облюбовать для посиделок
rus_verbs:прояснить{}, // прояснить для себя
rus_verbs:задействовать{}, // задействовать для патрулирования
rus_verbs:приготовлять{}, // приготовлять для проверки
инфинитив:использовать{ вид:соверш }, // использовать для достижения цели
инфинитив:использовать{ вид:несоверш },
глагол:использовать{ вид:соверш },
глагол:использовать{ вид:несоверш },
прилагательное:использованный{},
деепричастие:используя{},
деепричастие:использовав{},
rus_verbs:напрячься{}, // напрячься для решительного рывка
rus_verbs:одобрить{}, // одобрить для использования
rus_verbs:одобрять{}, // одобрять для использования
rus_verbs:пригодиться{}, // пригодиться для тестирования
rus_verbs:готовить{}, // готовить для выхода в свет
rus_verbs:отобрать{}, // отобрать для участия в конкурсе
rus_verbs:потребоваться{}, // потребоваться для подтверждения
rus_verbs:пояснить{}, // пояснить для слушателей
rus_verbs:пояснять{}, // пояснить для экзаменаторов
rus_verbs:понадобиться{}, // понадобиться для обоснования
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
rus_verbs:найти{}, // Папа нашел для детей няню
прилагательное:вредный{}, // Это вредно для здоровья.
прилагательное:полезный{}, // Прогулки полезны для здоровья.
прилагательное:обязательный{}, // Этот пункт обязателен для исполнения
прилагательное:бесполезный{}, // Это лекарство бесполезно для него
прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления
rus_verbs:создать{}, // Он не создан для этого дела.
прилагательное:сложный{}, // задача сложна для младших школьников
прилагательное:несложный{},
прилагательное:лёгкий{},
прилагательное:сложноватый{},
rus_verbs:становиться{},
rus_verbs:представлять{}, // Это не представляет для меня интереса.
rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка
rus_verbs:пройти{}, // День прошёл спокойно для него.
rus_verbs:проходить{},
rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
rus_verbs:высаживаться{},
rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца.
rus_verbs:прибавить{},
rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов.
rus_verbs:составлять{},
rus_verbs:стараться{}, // Я старался для вас
rus_verbs:постараться{}, // Я постарался для вас
rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста.
rus_verbs:собраться{}, // собраться для обсуждения
rus_verbs:собираться{}, // собираться для обсуждения
rus_verbs:уполномочивать{},
rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров
rus_verbs:принести{}, // Я принёс эту книгу для вас.
rus_verbs:делать{}, // Я это делаю для удовольствия.
rus_verbs:сделать{}, // Я сделаю это для удовольствия.
rus_verbs:подготовить{}, // я подготовил для друзей сюрприз
rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз
rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села
rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села
rus_verbs:прибыть{} // они прибыли для участия
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } }
then return true
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:для{} *:*{} }
then return false,-4
}
#endregion Предлог_ДЛЯ
#region Предлог_ОТ
// попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_ОТ_Род_Запр=
{
rus_verbs:наслаждаться{}, // свободой от обязательств
rus_verbs:насладиться{},
rus_verbs:мочь{}, // Он не мог удержаться от смеха.
// rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:чувствовать{}, // все время от времени чувствуют его.
rus_verbs:планировать{},
rus_verbs:приняться{} // мы принялись обниматься от радости.
}
fact гл_предл
{
if context { Глаг_ОТ_Род_Запр предлог:от{} * }
then return false
}
#endregion Предлог_ОТ
#region Предлог_БЕЗ
/*
// запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_БЕЗ_Род_Запр=
{
rus_verbs:мочь{}, // Он мог читать часами без отдыха.
rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:планировать{},
rus_verbs:приняться{}
}
fact гл_предл
{
if context { Глаг_БЕЗ_Род_Запр предлог:без{} * }
then return false
}
*/
#endregion Предлог_БЕЗ
#region Предлог_КРОМЕ
fact гл_предл
{
if context { * ПредлогДляВсе * }
then return false,-5
}
#endregion Предлог_КРОМЕ
// ------------------------------------
// По умолчанию разрешаем все остальные сочетания.
fact гл_предл
{
if context { * * * }
then return true
}
| Характер писателя лучше всего выражается в его произведениях.
| rus_verbs:выражаться{}, | 5,482,599 | [
1,
145,
103,
145,
113,
146,
227,
145,
113,
145,
123,
146,
229,
145,
118,
146,
227,
225,
145,
128,
145,
121,
146,
228,
145,
113,
146,
229,
145,
118,
145,
124,
146,
242,
225,
145,
124,
146,
230,
146,
234,
146,
235,
145,
118,
225,
145,
115,
146,
228,
145,
118,
145,
116,
145,
127,
225,
145,
115,
146,
238,
146,
227,
145,
113,
145,
119,
145,
113,
145,
118,
146,
229,
146,
228,
146,
242,
225,
145,
115,
225,
145,
118,
145,
116,
145,
127,
225,
145,
128,
146,
227,
145,
127,
145,
121,
145,
120,
145,
115,
145,
118,
145,
117,
145,
118,
145,
126,
145,
121,
146,
242,
146,
232,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
436,
407,
67,
502,
2038,
30,
145,
115,
146,
238,
146,
227,
145,
113,
145,
119,
145,
113,
146,
229,
146,
239,
146,
228,
146,
242,
2916,
16,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title Glofile
* @author Jonathan Brown <[email protected]>
*/
contract Glofile {
enum GlofileType { Anon, Person, Project, Organization, Proxy, Parody, Bot }
enum SafetyLevel { Safe, NSFW, NSFL }
struct Glofile {
bool dontIndex;
GlofileType glofileType;
SafetyLevel safetyLevel;
string fullName;
string location;
bytes3[] foregroundColors;
bytes3[] backgroundColors;
bytes3[] languages;
bytes3[] bioLanguages;
bytes[] avatars;
bytes[] coverImages;
bytes[] backgroundImages;
string[] topics;
string[] parents;
string[] children;
string[] uris;
mapping (bytes3 => bytes) bioTranslations;
}
mapping (address => Glofile) glofiles;
event Update(address indexed account);
event Delete(address indexed account);
/**
* @notice Set your Glofile don't index flag to `dontIndex`
* @dev Sets the "don't index" flag. Glofiles with this flag set should only be accessible directly and not be discoverable via search.
* @param dontIndex flag to indicate that this Glofile should not be indexed
*/
function setDontIndex(bool dontIndex) {
glofiles[msg.sender].dontIndex = dontIndex;
Update(msg.sender);
}
/**
* @notice Set your Glofile type to `glofileType`
* @dev Sets the Glofile type.
* @param glofileType Glofile type
*/
function setGlofileType(GlofileType glofileType) {
glofiles[msg.sender].glofileType = glofileType;
Update(msg.sender);
}
/**
* @notice Set your Glofile safety level to `safetyLevel`
* @dev Sets the safety level. The account may publish content that is less safe than this, so long as it is flagged as such.
* @param safetyLevel safety level
*/
function setSafetyLevel(SafetyLevel safetyLevel) {
glofiles[msg.sender].safetyLevel = safetyLevel;
Update(msg.sender);
}
/**
* @notice Set your Glofile full name to `fullName`
* @dev Sets the full name.
* @param fullName UTF-8 string of full name - max length 128 chars
*/
function setFullName(string fullName) {
glofiles[msg.sender].fullName = fullName;
Update(msg.sender);
}
/**
* @notice Set your Glofile location
* @dev Sets the location. A dedicated contract could be used for more sophisticated location functionality.
* @param location UTF-8 string of location - max string length 128 chars
*/
function setLocation(string location) {
glofiles[msg.sender].location = location;
Update(msg.sender);
}
/**
* @notice Set your Glofile foreground colors
* @dev Sets all the foreground colors.
* @param colors array of RGB triplets
*/
function setForegroundColors(bytes3[] colors) {
glofiles[msg.sender].foregroundColors = colors;
Update(msg.sender);
}
/**
* @notice Set your Glofile background colors
* @dev Sets all the background colors.
* @param colors array of RGB triplets
*/
function setBackgroundColors(bytes3[] colors) {
glofiles[msg.sender].backgroundColors = colors;
Update(msg.sender);
}
/**
* @notice Sets the Glofile langauges your account may publish in
* @dev Sets all the languages the account may publish in.
* @param languages array of 3 letter ISO 639-3 language codes
*/
function setLanguages(bytes3[] languages) {
glofiles[msg.sender].languages = languages;
Update(msg.sender);
}
/**
* @notice Get Glofile basic info
* @dev Gets all the info that can be retreived in a single call.
* @param account Glofile to access
* @return dontIndex flag to indicate that this Glofile should not be indexed
* @return glofileType Glofile type
* @return safetyLevel safety level
* @return fullName UTF-8 string of full name
* @return location UTF-8 string of location
* @return foregroundColors array of RGB triplets of foreground colors
* @return backgroundColors array of RGB triplets of background colors
* @return languages array of 3 letter ISO 639-3 language codes
*/
function getBasicInfo(address account) constant returns (bool dontIndex, GlofileType glofileType, SafetyLevel safetyLevel, string fullName, string location, bytes3[] foregroundColors, bytes3[] backgroundColors, bytes3[] languages) {
Glofile glofile = glofiles[account];
dontIndex = glofile.dontIndex;
glofileType = glofile.glofileType;
safetyLevel = glofile.safetyLevel;
fullName = glofile.fullName;
location = glofile.location;
foregroundColors = glofile.foregroundColors;
backgroundColors = glofile.backgroundColors;
languages = glofile.languages;
}
/**
* @notice Set your Glofile bio with langauge code `language`
* @dev Sets the bio in a specific language.
* @param language 3 letter ISO 639-3 language code
* @param translation UTF-8 Markdown of bio compressed with DEFLATE - max Markdown length 256 chars
*/
function setBio(bytes3 language, bytes translation) {
Glofile glofile = glofiles[msg.sender];
// Check if we already have the language code.
for (uint i = 0; i < glofile.bioLanguages.length; i++) {
if (glofile.bioLanguages[i] == language) {
break;
}
}
if (i == glofile.bioLanguages.length) {
// We didn't find it. Try to find a free slot.
for (i = 0; i < glofile.bioLanguages.length; i++) {
if (glofile.bioLanguages[i] == 0) {
break;
}
}
if (i == glofile.bioLanguages.length) {
// We didn't find a free slot. Make the array bigger.
glofile.bioLanguages.length++;
}
glofile.bioLanguages[i] = language;
}
// Set translation.
glofile.bioTranslations[language] = translation;
Update(msg.sender);
}
/**
* @notice Delete your Glofile bio with language code `language`
* @dev Deletes a bio translation.
* @param language 3 letter ISO 639-3 language code
*/
function deleteBio(bytes3 language) {
Glofile glofile = glofiles[msg.sender];
for (uint i = 0; i < glofile.bioLanguages.length; i++) {
if (glofile.bioLanguages[i] == language) {
delete glofile.bioLanguages[i];
break;
}
}
// Delete the actual mapping in case a client accesses without checking
// language key.
delete glofile.bioTranslations[language];
Update(msg.sender);
}
/**
* @notice Delete all of your Glofile bio translations
* @dev Deletes all of the bio translations.
*/
function deleteAllBioTranslations() {
Glofile glofile = glofiles[msg.sender];
// Delete the actual mappings in case a client accesses without checking
// language key.
for (uint i = 0; i < glofile.bioLanguages.length; i++) {
delete glofile.bioTranslations[glofile.bioLanguages[i]];
}
delete glofile.bioLanguages;
Update(msg.sender);
}
/**
* @notice Get the list of language code a Glofile bio is available in
* @dev Gets the list of language codes the bio is available in.
* @param account Glofile to access
* @return array of 3 letter ISO 639-3 language codes
*/
function getBioLanguages(address account) constant returns (bytes3[]) {
return glofiles[account].bioLanguages;
}
/**
* @notice Get the Glofile bio with language code `language`
* @dev Gets the bio in a specific language.
* @param account Glofile to access
* @param language 3 letter ISO 639-3 language code
* @return UTF-8 Markdown of bio compressed with DEFLATE
*/
function getBio(address account, bytes3 language) constant returns (bytes) {
return glofiles[account].bioTranslations[language];
}
/**
* @notice Set your Glofile avatar with index `i` to `ipfsHash`
* @dev Sets the avatar with a specific index to an IPFS hash.
* @param i index of avatar to set
* @param ipfsHash binary IPFS hash of image
*/
function setAvatar(uint i, bytes ipfsHash) {
bytes[] avatars = glofiles[msg.sender].avatars;
// Make sure the array is long enough.
if (avatars.length <= i) {
avatars.length = i + 1;
}
avatars[i] = ipfsHash;
Update(msg.sender);
}
/**
* @notice Delete your Glofile avatar with index `i`
* @dev Deletes an avatar with a specific index.
* @param i index of avatar to delete
*/
function deleteAvatar(uint i) {
delete glofiles[msg.sender].avatars[i];
Update(msg.sender);
}
/**
* @notice Delete all your Glofile avatars
* @dev Deletes all avatars from the Glofile.
*/
function deleteAllAvatars() {
delete glofiles[msg.sender].avatars;
Update(msg.sender);
}
/**
* @notice Get the number of Glofile avatars
* @dev Gets the number of avatars.
* @param account Glofile to access
* @return number of avatars
*/
function getAvatarCount(address account) constant returns (uint) {
return glofiles[account].avatars.length;
}
/**
* @notice Get the Glofile avatar with index `i`
* @dev Gets the avatar with a specific index.
* @param account Glofile to access
* @param i index of avatar to get
* @return binary IPFS hash of image
*/
function getAvatar(address account, uint i) constant returns (bytes) {
return glofiles[account].avatars[i];
}
/**
* @notice Set your Glofile cover image with index `i` to `ipfsHash`
* @dev Sets the cover image with a specific index to an IPFS hash.
* @param i index of cover image to set
* @param ipfsHash binary IPFS hash of image
*/
function setCoverImage(uint i, bytes ipfsHash) {
bytes[] coverImages = glofiles[msg.sender].coverImages;
// Make sure the array is long enough.
if (coverImages.length <= i) {
coverImages.length = i + 1;
}
coverImages[i] = ipfsHash;
Update(msg.sender);
}
/**
* @notice Delete your Glofile cover image with index `i`
* @dev Deletes the cover image with a specific index.
* @param i index of cover image to delete
*/
function deleteCoverImage(uint i) {
delete glofiles[msg.sender].coverImages[i];
Update(msg.sender);
}
/**
* @notice Delete all your Glofile cover images
* @dev Deletes all cover images from the Glofile.
*/
function deleteAllCoverImages() {
delete glofiles[msg.sender].coverImages;
Update(msg.sender);
}
/**
* @notice Get the number of Glofile cover images
* @dev Gets the number of cover images.
* @param account Glofile to access
* @return number of cover images
*/
function getCoverImageCount(address account) constant returns (uint) {
return glofiles[account].coverImages.length;
}
/**
* @notice Get the Glofile cover image with index `i`
* @dev Gets the cover image with a specific index.
* @param account Glofile to access
* @param i index of cover image to get
* @return binary IPFS hash of image
*/
function getCoverImage(address account, uint i) constant returns (bytes) {
return glofiles[account].coverImages[i];
}
/**
* @notice Set your Glofile background image with index `i` to `ipfsHash`
* @dev Sets the background image with a specific index to an IPFS hash.
* @param i index of background image to set
* @param ipfsHash binary IPFS hash of image
*/
function setBackgroundImage(uint i, bytes ipfsHash) {
bytes[] backgroundImages = glofiles[msg.sender].backgroundImages;
// Make sure the array is long enough.
if (backgroundImages.length <= i) {
backgroundImages.length = i + 1;
}
backgroundImages[i] = ipfsHash;
Update(msg.sender);
}
/**
* @notice Delete your Glofile background image with index `i`
* @dev Deletes the background image with a specific index.
* @param i index of background image to delete
*/
function deleteBackgroundImage(uint i) {
delete glofiles[msg.sender].backgroundImages[i];
Update(msg.sender);
}
/**
* @notice Delete all your Glofile background images
* @dev Deletes all the background images.
*/
function deleteAllBackgroundImages() {
delete glofiles[msg.sender].backgroundImages;
Update(msg.sender);
}
/**
* @notice Get the number of Glofile background images
* @dev Gets the number of background images.
* @param account Glofile to access
* @return number of background images
*/
function getBackgroundImageCount(address account) constant returns (uint) {
return glofiles[account].backgroundImages.length;
}
/**
* @notice Get the Glofile background image with index `i`
* @dev Gets the background image with a specific index.
* @param i index of cover image to get
* @param account Glofile to access
* @return binary IPFS hash of image
*/
function getBackgroundImage(address account, uint i) constant returns (bytes) {
return glofiles[account].backgroundImages[i];
}
/**
* @notice Set your Glofile topic with index `i` to `topic`
* @dev Sets the topic with a specific index.
* @param i index of topic to set
* @param topic UTF-8 string of topic (no whitespace)
*/
function setTopic(uint i, string topic) {
string[] topics = glofiles[msg.sender].topics;
// Make sure the array is long enough.
if (topics.length <= i) {
topics.length = i + 1;
}
topics[i] = topic;
Update(msg.sender);
}
/**
* @notice Delete your Glofile topic with index `i`
* @dev Deletes an topic with a specific index.
* @param i index of topic to delete
*/
function deleteTopic(uint i) {
delete glofiles[msg.sender].topics[i];
Update(msg.sender);
}
/**
* @notice Delete all your Glofile topics
* @dev Deletes all topics from the Glofile.
*/
function deleteAllTopics() {
delete glofiles[msg.sender].topics;
Update(msg.sender);
}
/**
* @notice Get the number of Glofile topics
* @dev Gets the number of topics.
* @param account Glofile to access
* @return number of topics
*/
function getTopicCount(address account) constant returns (uint) {
return glofiles[account].topics.length;
}
/**
* @notice Get the Glofile topic with index `i`
* @dev Gets the topic with a specific index.
* @param account Glofile to access
* @param i index of topic to get
* @return UTF-8 string of topic
*/
function getTopic(address account, uint i) constant returns (string) {
return glofiles[account].topics[i];
}
/**
* @notice Set your Glofile parent with index `i` to `parent`
* @dev Sets the parent with a specific index.
* @param i index of parent to set
* @param parent UTF-8 string of parent
*/
function setParent(uint i, string parent) {
string[] parents = glofiles[msg.sender].parents;
// Make sure the array is long enough.
if (parents.length <= i) {
parents.length = i + 1;
}
parents[i] = parent;
Update(msg.sender);
}
/**
* @notice Delete your Glofile parent with index `i`
* @dev Deletes an parent with a specific index.
* @param i index of parent to delete
*/
function deleteParent(uint i) {
delete glofiles[msg.sender].parents[i];
Update(msg.sender);
}
/**
* @notice Delete all your Glofile parents
* @dev Deletes all parents from the Glofile.
*/
function deleteAllParents() {
delete glofiles[msg.sender].parents;
Update(msg.sender);
}
/**
* @notice Get the number of Glofile parents
* @dev Gets the number of parents.
* @param account Glofile to access
* @return number of parents
*/
function getParentCount(address account) constant returns (uint) {
return glofiles[account].parents.length;
}
/**
* @notice Get the Glofile parent with index `i`
* @dev Gets the parent with a specific index.
* @param account Glofile to access
* @param i index of parent to get
* @return UTF-8 string of parent
*/
function getParent(address account, uint i) constant returns (string) {
return glofiles[account].parents[i];
}
/**
* @notice Set your Glofile child with index `i` to `child`
* @dev Sets the child with a specific index.
* @param i index of child to set
* @param child UTF-8 string of child
*/
function setChild(uint i, string child) {
string[] children = glofiles[msg.sender].children;
// Make sure the array is long enough.
if (children.length <= i) {
children.length = i + 1;
}
children[i] = child;
Update(msg.sender);
}
/**
* @notice Delete your Glofile child with index `i`
* @dev Deletes an child with a specific index.
* @param i index of child to delete
*/
function deleteChild(uint i) {
delete glofiles[msg.sender].children[i];
Update(msg.sender);
}
/**
* @notice Delete all your Glofile children
* @dev Deletes all children from the Glofile.
*/
function deleteAllChildren() {
delete glofiles[msg.sender].children;
Update(msg.sender);
}
/**
* @notice Get the number of Glofile children
* @dev Gets the number of children.
* @param account Glofile to access
* @return number of children
*/
function getChildCount(address account) constant returns (uint) {
return glofiles[account].children.length;
}
/**
* @notice Get the Glofile child with index `i`
* @dev Gets the child with a specific index.
* @param account Glofile to access
* @param i index of child to get
* @return UTF-8 string of child
*/
function getChild(address account, uint i) constant returns (string) {
return glofiles[account].children[i];
}
/**
* @notice Set your Glofile uri with index `i` to `uri`
* @dev Sets the uri with a specific index.
* @param i index of uri to set
* @param uri UTF-8 string of uri
*/
function setUri(uint i, string uri) {
string[] uris = glofiles[msg.sender].uris;
// Make sure the array is long enough.
if (uris.length <= i) {
uris.length = i + 1;
}
uris[i] = uri;
Update(msg.sender);
}
/**
* @notice Delete your Glofile uri with index `i`
* @dev Deletes an uri with a specific index.
* @param i index of uri to delete
*/
function deleteUri(uint i) {
delete glofiles[msg.sender].uris[i];
Update(msg.sender);
}
/**
* @notice Delete all your Glofile uris
* @dev Deletes all uris from the Glofile.
*/
function deleteAllUris() {
delete glofiles[msg.sender].uris;
Update(msg.sender);
}
/**
* @notice Get the number of Glofile uris
* @dev Gets the number of uris.
* @param account Glofile to access
* @return number of uris
*/
function getUriCount(address account) constant returns (uint) {
return glofiles[account].uris.length;
}
/**
* @notice Get the Glofile uri with index `i`
* @dev Gets the uri with a specific index.
* @param account Glofile to access
* @param i index of uri to get
* @return UTF-8 string of uri
*/
function getUri(address account, uint i) constant returns (string) {
return glofiles[account].uris[i];
}
/**
* @notice Copy entire Glofile from `source`
* @dev Copies the Glofile from another account to this one.
* @param source account of Glofile to copy from
* TODO: check this works
*/
function copyEntireGlofile(address source) {
glofiles[msg.sender] = glofiles[source];
Update(msg.sender);
}
/**
* @notice Delete your entire Glofile
* @dev Deletes the Glofile completely.
* TODO: make sure this deletes everything
*/
function deleteEntireGlofile() {
delete glofiles[msg.sender];
Delete(msg.sender);
}
}
| * @notice Delete all of your Glofile bio translations @dev Deletes all of the bio translations./ Delete the actual mappings in case a client accesses without checking language key. | function deleteAllBioTranslations() {
Glofile glofile = glofiles[msg.sender];
for (uint i = 0; i < glofile.bioLanguages.length; i++) {
delete glofile.bioTranslations[glofile.bioLanguages[i]];
}
delete glofile.bioLanguages;
Update(msg.sender);
}
| 12,551,871 | [
1,
2613,
777,
434,
3433,
611,
383,
768,
25091,
7863,
225,
17973,
777,
434,
326,
25091,
7863,
18,
19,
2504,
326,
3214,
7990,
316,
648,
279,
1004,
2006,
281,
2887,
6728,
2653,
498,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
27283,
38,
1594,
12297,
1435,
288,
203,
565,
611,
383,
768,
314,
383,
768,
273,
314,
383,
2354,
63,
3576,
18,
15330,
15533,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
314,
383,
768,
18,
21010,
12912,
18,
2469,
31,
277,
27245,
288,
203,
1377,
1430,
314,
383,
768,
18,
21010,
12297,
63,
75,
383,
768,
18,
21010,
12912,
63,
77,
13563,
31,
203,
565,
289,
203,
565,
1430,
314,
383,
768,
18,
21010,
12912,
31,
203,
565,
2315,
12,
3576,
18,
15330,
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
] |
./full_match/3/0x044e0465CAdCF1260F7965558356f4f1bbdb317d/sources/contracts/MyAuction.sol | 최고 입찰가는 경매 판매자에게 전송 feeBeneficiary는 highestBid (최고 입찰가) 에서 fee (1%) 를 받는다 highestBid(최고 입찰가)는 fee 가격을 제외한 가격 (99%) 으로 전송 된다. 수수료 1% 설정 feeBeneficiary = 0x0d8c1Beae062BDc263B23D4BC8c4BBeeA4a556B5; 계약을 승인하고 낙찰자에게 token 소유권 이전 | if(bidsLen == 0){
cancelAuction(_auctionId);
Bid memory lastBid = auctionBids[_auctionId][bidsLen - 1];
fee = lastBid.amount / 100;
finalBid = lastBid.amount - fee;
myAuction.owner.transfer(finalBid);
address(uint160(feeBeneficiary)).transfer(fee);
if(approveAndTransfer(lastBid.bider, myAuction.tokenId)){
auctions[_auctionId].ended = true;
emit AuctionFinalized(msg.sender, _auctionId);
}
}
| 8,121,413 | [
1,
173,
118,
255,
171,
116,
259,
225,
173,
257,
232,
173,
113,
113,
171,
113,
227,
172,
237,
247,
225,
171,
115,
126,
172,
105,
102,
225,
174,
239,
243,
172,
105,
102,
173,
257,
243,
173,
250,
243,
171,
115,
239,
225,
173,
259,
231,
173,
233,
99,
14036,
38,
4009,
74,
14463,
814,
172,
237,
247,
9742,
17763,
261,
173,
118,
255,
171,
116,
259,
225,
173,
257,
232,
173,
113,
113,
171,
113,
227,
13,
225,
173,
250,
243,
173,
231,
255,
14036,
261,
21,
9,
13,
225,
172,
103,
125,
225,
172,
113,
254,
172,
237,
247,
172,
238,
102,
9742,
17763,
12,
173,
118,
255,
171,
116,
259,
225,
173,
257,
232,
173,
113,
113,
171,
113,
227,
13,
172,
237,
247,
14036,
225,
171,
113,
227,
171,
115,
107,
173,
256,
231,
225,
173,
259,
255,
173,
252,
121,
174,
248,
255,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
3639,
309,
12,
70,
2232,
2891,
422,
374,
15329,
203,
5411,
3755,
37,
4062,
24899,
69,
4062,
548,
1769,
203,
5411,
605,
350,
3778,
1142,
17763,
273,
279,
4062,
38,
2232,
63,
67,
69,
4062,
548,
6362,
70,
2232,
2891,
300,
404,
15533,
203,
203,
5411,
14036,
273,
1142,
17763,
18,
8949,
342,
2130,
31,
203,
5411,
727,
17763,
273,
1142,
17763,
18,
8949,
300,
14036,
31,
203,
2398,
203,
5411,
3399,
37,
4062,
18,
8443,
18,
13866,
12,
6385,
17763,
1769,
203,
5411,
1758,
12,
11890,
16874,
12,
21386,
38,
4009,
74,
14463,
814,
13,
2934,
13866,
12,
21386,
1769,
203,
2398,
203,
5411,
309,
12,
12908,
537,
1876,
5912,
12,
2722,
17763,
18,
70,
3585,
16,
3399,
37,
4062,
18,
2316,
548,
3719,
95,
203,
7734,
279,
4062,
87,
63,
67,
69,
4062,
548,
8009,
3934,
273,
638,
31,
203,
7734,
3626,
432,
4062,
7951,
1235,
12,
3576,
18,
15330,
16,
389,
69,
4062,
548,
1769,
203,
5411,
289,
203,
3639,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.