file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./partial_match/1/0xea0E551A5e4A7bdC839b7a153a9406532bC99487/sources/DELUTIONARY.sol | MARK: DividendTracker | contract DividendTracker is DividendPayingToken {
using SafeMath for uint256;
using SafeMathInt for int256;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(address key) private view returns (uint) {
return tokenHoldersMap.values[key];
}
function getIndexOfKey(address key) private view returns (int) {
if(!tokenHoldersMap.inserted[key]) {
return -1;
}
return int(tokenHoldersMap.indexOf[key]);
}
function getIndexOfKey(address key) private view returns (int) {
if(!tokenHoldersMap.inserted[key]) {
return -1;
}
return int(tokenHoldersMap.indexOf[key]);
}
function getKeyAtIndex(uint index) private view returns (address) {
return tokenHoldersMap.keys[index];
}
function size() private view returns (uint) {
return tokenHoldersMap.keys.length;
}
function set(address key, uint val) private {
if (tokenHoldersMap.inserted[key]) {
tokenHoldersMap.values[key] = val;
tokenHoldersMap.inserted[key] = true;
tokenHoldersMap.values[key] = val;
tokenHoldersMap.indexOf[key] = tokenHoldersMap.keys.length;
tokenHoldersMap.keys.push(key);
}
}
function set(address key, uint val) private {
if (tokenHoldersMap.inserted[key]) {
tokenHoldersMap.values[key] = val;
tokenHoldersMap.inserted[key] = true;
tokenHoldersMap.values[key] = val;
tokenHoldersMap.indexOf[key] = tokenHoldersMap.keys.length;
tokenHoldersMap.keys.push(key);
}
}
} else {
function remove(address key) private {
if (!tokenHoldersMap.inserted[key]) {
return;
}
delete tokenHoldersMap.inserted[key];
delete tokenHoldersMap.values[key];
uint index = tokenHoldersMap.indexOf[key];
uint lastIndex = tokenHoldersMap.keys.length - 1;
address lastKey = tokenHoldersMap.keys[lastIndex];
tokenHoldersMap.indexOf[lastKey] = index;
delete tokenHoldersMap.indexOf[key];
tokenHoldersMap.keys[index] = lastKey;
tokenHoldersMap.keys.pop();
}
Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event IncludeInDividends(address indexed account);
event ClaimWaitUpdated(uint256 indexed _newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
function remove(address key) private {
if (!tokenHoldersMap.inserted[key]) {
return;
}
delete tokenHoldersMap.inserted[key];
delete tokenHoldersMap.values[key];
uint index = tokenHoldersMap.indexOf[key];
uint lastIndex = tokenHoldersMap.keys.length - 1;
address lastKey = tokenHoldersMap.keys[lastIndex];
tokenHoldersMap.indexOf[lastKey] = index;
delete tokenHoldersMap.indexOf[key];
tokenHoldersMap.keys[index] = lastKey;
tokenHoldersMap.keys.pop();
}
Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event IncludeInDividends(address indexed account);
event ClaimWaitUpdated(uint256 indexed _newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() {
claimWait = 1200;
minimumTokenBalanceForDividends = 10000 * (10**18);
}
function excludeFromDividends(address account) external onlyOwner {
excludedFromDividends[account] = true;
_setBalance(account, 0);
remove(account);
emit ExcludeFromDividends(account);
}
function includeInDividends(address account) external onlyOwner {
require(excludedFromDividends[account]);
excludedFromDividends[account] = false;
emit IncludeInDividends(account);
}
function _updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 1200 && newClaimWait <= 86400, "Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account, address _rewardToken)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account, _rewardToken);
totalDividends = accumulativeDividendOf(account, _rewardToken);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccount(address _account, address _rewardToken)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account, _rewardToken);
totalDividends = accumulativeDividendOf(account, _rewardToken);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccount(address _account, address _rewardToken)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account, _rewardToken);
totalDividends = accumulativeDividendOf(account, _rewardToken);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccount(address _account, address _rewardToken)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account, _rewardToken);
totalDividends = accumulativeDividendOf(account, _rewardToken);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index, address _rewardToken)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = getKeyAtIndex(index);
return getAccount(account, _rewardToken);
}
function getAccountAtIndex(uint256 index, address _rewardToken)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = getKeyAtIndex(index);
return getAccount(account, _rewardToken);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
set(account, newBalance);
}
else {
_setBalance(account, 0);
remove(account);
}
processAccount(account, true);
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
set(account, newBalance);
}
else {
_setBalance(account, 0);
remove(account);
}
processAccount(account, true);
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
set(account, newBalance);
}
else {
_setBalance(account, 0);
remove(account);
}
processAccount(account, true);
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
set(account, newBalance);
}
else {
_setBalance(account, 0);
remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount;
bool paid;
for (uint256 i; i < rewardTokens.length; i++){
amount = _withdrawDividendOfUser(account, rewardTokens[i]);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
paid = true;
}
}
return paid;
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount;
bool paid;
for (uint256 i; i < rewardTokens.length; i++){
amount = _withdrawDividendOfUser(account, rewardTokens[i]);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
paid = true;
}
}
return paid;
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount;
bool paid;
for (uint256 i; i < rewardTokens.length; i++){
amount = _withdrawDividendOfUser(account, rewardTokens[i]);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
paid = true;
}
}
return paid;
}
}
| 15,777,753 | [
1,
12693,
30,
21411,
26746,
8135,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
21411,
26746,
8135,
353,
21411,
26746,
9148,
310,
1345,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
10477,
1702,
364,
509,
5034,
31,
203,
203,
565,
1958,
1635,
288,
203,
3639,
1758,
8526,
1311,
31,
203,
3639,
2874,
12,
2867,
516,
2254,
13,
924,
31,
203,
3639,
2874,
12,
2867,
516,
2254,
13,
3133,
31,
203,
3639,
2874,
12,
2867,
516,
1426,
13,
9564,
31,
203,
565,
289,
203,
203,
565,
445,
336,
12,
2867,
498,
13,
3238,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
1147,
27003,
863,
18,
2372,
63,
856,
15533,
203,
565,
289,
203,
203,
565,
445,
8088,
951,
653,
12,
2867,
498,
13,
3238,
1476,
1135,
261,
474,
13,
288,
203,
3639,
309,
12,
5,
2316,
27003,
863,
18,
6387,
329,
63,
856,
5717,
288,
203,
5411,
327,
300,
21,
31,
203,
3639,
289,
203,
3639,
327,
509,
12,
2316,
27003,
863,
18,
31806,
63,
856,
19226,
203,
565,
289,
203,
203,
565,
445,
8088,
951,
653,
12,
2867,
498,
13,
3238,
1476,
1135,
261,
474,
13,
288,
203,
3639,
309,
12,
5,
2316,
27003,
863,
18,
6387,
329,
63,
856,
5717,
288,
203,
5411,
327,
300,
21,
31,
203,
3639,
289,
203,
3639,
327,
509,
12,
2316,
27003,
863,
18,
31806,
63,
856,
19226,
203,
565,
289,
203,
203,
565,
445,
3579,
24499,
12,
11890,
770,
13,
3238,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1147,
27003,
863,
18,
2452,
63,
1615,
15533,
203,
565,
289,
203,
203,
2
]
|
pragma solidity >= 0.5.0;
import "./GSNRecipient.sol";
import "../math/SafeMath.sol";
import "../ownership/Secondary.sol";
import "../token/ERC20/SafeERC20.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Detailed.sol";
/**
* @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that charges transaction fees in a special purpose ERC20
* token, which we refer to as the gas payment token. The amount charged is exactly the amount of Ether charged to the
* recipient. This means that the token is essentially pegged to the value of Ether.
*
* The distribution strategy of the gas payment token to users is not defined by this contract. It's a mintable token
* whose only minter is the recipient, so the strategy must be implemented in a derived contract, making use of the
* internal {_mint} function.
*/
contract GSNRecipientERC20Fee is GSNRecipient {
using SafeERC20 for __unstable__ERC20PrimaryAdmin;
using SafeMath for uint256;
enum GSNRecipientERC20FeeErrorCodes {
INSUFFICIENT_BALANCE
}
__unstable__ERC20PrimaryAdmin private _token;
/**
* @dev The arguments to the constructor are the details that the gas payment token will have: `name` and `symbol`. `decimals` is hard-coded to 18.
*/
constructor(string memory name, string memory symbol) public {
_token = new __unstable__ERC20PrimaryAdmin(name, symbol, 18);
}
/**
* @dev Returns the gas payment token.
*/
function token() public view returns (IERC20) {
return IERC20(_token);
}
/**
* @dev Internal function that mints the gas payment token. Derived contracts should expose this function in their public API, with proper access control mechanisms.
*/
function _mint(address account, uint256 amount) internal {
_token.mint(account, amount);
}
/**
* @dev Ensures that only users with enough gas payment token balance can have transactions relayed through the GSN.
*/
function acceptRelayedCall(
address,
address from,
bytes calldata,
uint256 transactionFee,
uint256 gasPrice,
uint256,
uint256,
bytes calldata,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory)
{
if (_token.balanceOf(from) < maxPossibleCharge) {
return _rejectRelayedCall(uint256(GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE));
}
return _approveRelayedCall(abi.encode(from, maxPossibleCharge, transactionFee, gasPrice));
}
/**
* @dev Implements the precharge to the user. The maximum possible charge (depending on gas limit, gas price, and
* fee) will be deducted from the user balance of gas payment token. Note that this is an overestimation of the
* actual charge, necessary because we cannot predict how much gas the execution will actually need. The remainder
* is returned to the user in {_postRelayedCall}.
*/
function _preRelayedCall(bytes memory context) internal returns (bytes32) {
(address from, uint256 maxPossibleCharge) = abi.decode(context, (address, uint256));
// The maximum token charge is pre-charged from the user
_token.safeTransferFrom(from, address(this), maxPossibleCharge);
}
/**
* @dev Returns to the user the extra amount that was previously charged, once the actual execution cost is known.
*/
function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) internal {
(address from, uint256 maxPossibleCharge, uint256 transactionFee, uint256 gasPrice) =
abi.decode(context, (address, uint256, uint256, uint256));
// actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas.
// This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an
// ERC20 transfer.
uint256 overestimation = _computeCharge(POST_RELAYED_CALL_MAX_GAS.sub(10000), gasPrice, transactionFee);
actualCharge = actualCharge.sub(overestimation);
// After the relayed call has been executed and the actual charge estimated, the excess pre-charge is returned
_token.safeTransfer(from, maxPossibleCharge.sub(actualCharge));
}
}
/**
* @title __unstable__ERC20PrimaryAdmin
* @dev An ERC20 token owned by another contract, which has minting permissions and can use transferFrom to receive
* anyone's tokens. This contract is an internal helper for GSNRecipientERC20Fee, and should not be used
* outside of this context.
*/
// solhint-disable-next-line contract-name-camelcase
contract __unstable__ERC20PrimaryAdmin is ERC20, ERC20Detailed, Secondary {
uint256 private constant UINT256_MAX = 2**256 - 1;
constructor(string memory name, string memory symbol, uint8 decimals) public ERC20Detailed(name, symbol, decimals) {
// solhint-disable-previous-line no-empty-blocks
}
// The primary account (GSNRecipientERC20Fee) can mint tokens
function mint(address account, uint256 amount) public onlyPrimary {
_mint(account, amount);
}
// The primary account has 'infinite' allowance for all token holders
function allowance(address owner, address spender) public view returns (uint256) {
if (spender == primary()) {
return UINT256_MAX;
} else {
return super.allowance(owner, spender);
}
}
// Allowance for the primary account cannot be changed (it is always 'infinite')
function _approve(address owner, address spender, uint256 value) internal {
if (spender == primary()) {
return;
} else {
super._approve(owner, spender, value);
}
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
if (recipient == primary()) {
_transfer(sender, recipient, amount);
return true;
} else {
return super.transferFrom(sender, recipient, amount);
}
}
}
| * @dev The arguments to the constructor are the details that the gas payment token will have: `name` and `symbol`. `decimals` is hard-coded to 18./ | constructor(string memory name, string memory symbol) public {
_token = new __unstable__ERC20PrimaryAdmin(name, symbol, 18);
}
| 15,798,422 | [
1,
1986,
1775,
358,
326,
3885,
854,
326,
3189,
716,
326,
16189,
5184,
1147,
903,
1240,
30,
1375,
529,
68,
471,
1375,
7175,
8338,
1375,
31734,
68,
353,
7877,
17,
24808,
358,
6549,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
2316,
273,
394,
1001,
318,
15021,
972,
654,
39,
3462,
6793,
4446,
12,
529,
16,
3273,
16,
6549,
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
]
|
pragma solidity 0.6.6;
import "./FluxAggregator.sol";
import "./SimpleReadAccessController.sol";
/**
* @title AccessControlled FluxAggregator contract
* @notice This contract requires addresses to be added to a controller
* in order to read the answers stored in the FluxAggregator contract
*/
contract AccessControlledAggregator is FluxAggregator, SimpleReadAccessController {
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public FluxAggregator(
_link,
_paymentAmount,
_timeout,
_validator,
_minSubmissionValue,
_maxSubmissionValue,
_decimals,
_description
){}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answerInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev overridden funcion to add the checkAccess() modifier
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
override
checkAccess()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return super.getRoundData(_roundId);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestAnswer
* functions. Consumers are encouraged to check that they're receiving fresh
* data by inspecting the updatedAt and answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answerInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev overridden funcion to add the checkAccess() modifier
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
override
checkAccess()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return super.latestRoundData();
}
/**
* @notice get the most recently reported answer
* @dev overridden funcion to add the checkAccess() modifier
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
override
checkAccess()
returns (int256)
{
return super.latestAnswer();
}
/**
* @notice get the most recently reported round ID
* @dev overridden funcion to add the checkAccess() modifier
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
override
checkAccess()
returns (uint256)
{
return super.latestRound();
}
/**
* @notice get the most recent updated at timestamp
* @dev overridden funcion to add the checkAccess() modifier
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
override
checkAccess()
returns (uint256)
{
return super.latestTimestamp();
}
/**
* @notice get past rounds answers
* @dev overridden funcion to add the checkAccess() modifier
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
override
checkAccess()
returns (int256)
{
return super.getAnswer(_roundId);
}
/**
* @notice get timestamp when an answer was last updated
* @dev overridden funcion to add the checkAccess() modifier
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
override
checkAccess()
returns (uint256)
{
return super.getTimestamp(_roundId);
}
}
pragma solidity 0.6.6;
import "./Median.sol";
import "./Owned.sol";
import "./SafeMath128.sol";
import "./SafeMath32.sol";
import "./SafeMath64.sol";
import "./interfaces/AggregatorV2V3Interface.sol";
import "./interfaces/AggregatorValidatorInterface.sol";
import "./interfaces/LinkTokenInterface.sol";
import "./vendor/SafeMath.sol";
/**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/
contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
}
pragma solidity ^0.6.0;
import "./vendor/SafeMath.sol";
import "./SignedSafeMath.sol";
library Median {
using SignedSafeMath for int256;
int256 constant INT_MAX = 2**255-1;
/**
* @notice Returns the sorted middle, or the average of the two middle indexed items if the
* array has an even number of elements.
* @dev The list passed as an argument isn't modified.
* @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs
* the runtime is O(n^2).
* @param list The list of elements to compare
*/
function calculate(int256[] memory list)
internal
pure
returns (int256)
{
return calculateInplace(copy(list));
}
/**
* @notice See documentation for function calculate.
* @dev The list passed as an argument may be permuted.
*/
function calculateInplace(int256[] memory list)
internal
pure
returns (int256)
{
require(0 < list.length, "list must not be empty");
uint256 len = list.length;
uint256 middleIndex = len / 2;
if (len % 2 == 0) {
int256 median1;
int256 median2;
(median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex);
return SignedSafeMath.avg(median1, median2);
} else {
return quickselect(list, 0, len - 1, middleIndex);
}
}
/**
* @notice Maximum length of list that shortSelectTwo can handle
*/
uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7;
/**
* @notice Select the k1-th and k2-th element from list of length at most 7
* @dev Uses an optimal sorting network
*/
function shortSelectTwo(
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
private
pure
returns (int256 k1th, int256 k2th)
{
// Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network)
// for lists of length 7. Network layout is taken from
// http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg
uint256 len = hi + 1 - lo;
int256 x0 = list[lo + 0];
int256 x1 = 1 < len ? list[lo + 1] : INT_MAX;
int256 x2 = 2 < len ? list[lo + 2] : INT_MAX;
int256 x3 = 3 < len ? list[lo + 3] : INT_MAX;
int256 x4 = 4 < len ? list[lo + 4] : INT_MAX;
int256 x5 = 5 < len ? list[lo + 5] : INT_MAX;
int256 x6 = 6 < len ? list[lo + 6] : INT_MAX;
if (x0 > x1) {(x0, x1) = (x1, x0);}
if (x2 > x3) {(x2, x3) = (x3, x2);}
if (x4 > x5) {(x4, x5) = (x5, x4);}
if (x0 > x2) {(x0, x2) = (x2, x0);}
if (x1 > x3) {(x1, x3) = (x3, x1);}
if (x4 > x6) {(x4, x6) = (x6, x4);}
if (x1 > x2) {(x1, x2) = (x2, x1);}
if (x5 > x6) {(x5, x6) = (x6, x5);}
if (x0 > x4) {(x0, x4) = (x4, x0);}
if (x1 > x5) {(x1, x5) = (x5, x1);}
if (x2 > x6) {(x2, x6) = (x6, x2);}
if (x1 > x4) {(x1, x4) = (x4, x1);}
if (x3 > x6) {(x3, x6) = (x6, x3);}
if (x2 > x4) {(x2, x4) = (x4, x2);}
if (x3 > x5) {(x3, x5) = (x5, x3);}
if (x3 > x4) {(x3, x4) = (x4, x3);}
uint256 index1 = k1 - lo;
if (index1 == 0) {k1th = x0;}
else if (index1 == 1) {k1th = x1;}
else if (index1 == 2) {k1th = x2;}
else if (index1 == 3) {k1th = x3;}
else if (index1 == 4) {k1th = x4;}
else if (index1 == 5) {k1th = x5;}
else if (index1 == 6) {k1th = x6;}
else {revert("k1 out of bounds");}
uint256 index2 = k2 - lo;
if (k1 == k2) {return (k1th, k1th);}
else if (index2 == 0) {return (k1th, x0);}
else if (index2 == 1) {return (k1th, x1);}
else if (index2 == 2) {return (k1th, x2);}
else if (index2 == 3) {return (k1th, x3);}
else if (index2 == 4) {return (k1th, x4);}
else if (index2 == 5) {return (k1th, x5);}
else if (index2 == 6) {return (k1th, x6);}
else {revert("k2 out of bounds");}
}
/**
* @notice Selects the k-th ranked element from list, looking only at indices between lo and hi
* (inclusive). Modifies list in-place.
*/
function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k)
private
pure
returns (int256 kth)
{
require(lo <= k);
require(k <= hi);
while (lo < hi) {
if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {
int256 ignore;
(kth, ignore) = shortSelectTwo(list, lo, hi, k, k);
return kth;
}
uint256 pivotIndex = partition(list, lo, hi);
if (k <= pivotIndex) {
// since pivotIndex < (original hi passed to partition),
// termination is guaranteed in this case
hi = pivotIndex;
} else {
// since (original lo passed to partition) <= pivotIndex,
// termination is guaranteed in this case
lo = pivotIndex + 1;
}
}
return list[lo];
}
/**
* @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between
* lo and hi (inclusive). Modifies list in-place.
*/
function quickselectTwo(
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
internal // for testing
pure
returns (int256 k1th, int256 k2th)
{
require(k1 < k2);
require(lo <= k1 && k1 <= hi);
require(lo <= k2 && k2 <= hi);
while (true) {
if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {
return shortSelectTwo(list, lo, hi, k1, k2);
}
uint256 pivotIdx = partition(list, lo, hi);
if (k2 <= pivotIdx) {
hi = pivotIdx;
} else if (pivotIdx < k1) {
lo = pivotIdx + 1;
} else {
assert(k1 <= pivotIdx && pivotIdx < k2);
k1th = quickselect(list, lo, pivotIdx, k1);
k2th = quickselect(list, pivotIdx + 1, hi, k2);
return (k1th, k2th);
}
}
}
/**
* @notice Partitions list in-place using Hoare's partitioning scheme.
* Only elements of list between indices lo and hi (inclusive) will be modified.
* Returns an index i, such that:
* - lo <= i < hi
* - forall j in [lo, i]. list[j] <= list[i]
* - forall j in [i, hi]. list[i] <= list[j]
*/
function partition(int256[] memory list, uint256 lo, uint256 hi)
private
pure
returns (uint256)
{
// We don't care about overflow of the addition, because it would require a list
// larger than any feasible computer's memory.
int256 pivot = list[(lo + hi) / 2];
lo -= 1; // this can underflow. that's intentional.
hi += 1;
while (true) {
do {
lo += 1;
} while (list[lo] < pivot);
do {
hi -= 1;
} while (list[hi] > pivot);
if (lo < hi) {
(list[lo], list[hi]) = (list[hi], list[lo]);
} else {
// Let orig_lo and orig_hi be the original values of lo and hi passed to partition.
// Then, hi < orig_hi, because hi decreases *strictly* monotonically
// in each loop iteration and
// - either list[orig_hi] > pivot, in which case the first loop iteration
// will achieve hi < orig_hi;
// - or list[orig_hi] <= pivot, in which case at least two loop iterations are
// needed:
// - lo will have to stop at least once in the interval
// [orig_lo, (orig_lo + orig_hi)/2]
// - (orig_lo + orig_hi)/2 < orig_hi
return hi;
}
}
}
/**
* @notice Makes an in-memory copy of the array passed in
* @param list Reference to the array to be copied
*/
function copy(int256[] memory list)
private
pure
returns(int256[] memory)
{
int256[] memory list2 = new int256[](list.length);
for (uint256 i = 0; i < list.length; i++) {
list2[i] = list[i];
}
return list2;
}
}
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) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.6.0;
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
/**
* @notice Computes average of two signed integers, ensuring that the computation
* doesn't overflow.
* @dev If the result is not an integer, it is rounded towards zero. For example,
* avg(-3, -4) = -3
*/
function avg(int256 _a, int256 _b)
internal
pure
returns (int256)
{
if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) {
return add(_a, _b) / 2;
}
int256 remainder = (_a % 2 + _b % 2) / 2;
return add(add(_a / 2, _b / 2), remainder);
}
}
pragma solidity ^0.6.0;
/**
* @title The Owned contract
* @notice A contract with helpers for basic contract ownership.
*/
contract Owned {
address payable public owner;
address private pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address _to)
external
onlyOwner()
{
pendingOwner = _to;
emit OwnershipTransferRequested(owner, _to);
}
/**
* @dev Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @dev Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only callable by owner");
_;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 128 bit integers.
*/
library SafeMath128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "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(uint128 a, uint128 b) internal pure returns (uint128) {
require(b <= a, "SafeMath: subtraction overflow");
uint128 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint128 a, uint128 b) internal pure returns (uint128) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint128 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint128 a, uint128 b) internal pure returns (uint128) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 32 bit integers.
*/
library SafeMath32 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
require(b <= a, "SafeMath: subtraction overflow");
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
// 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;
}
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 64 bit integers.
*/
library SafeMath64 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint64 a, uint64 b) internal pure returns (uint64) {
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
require(b <= a, "SafeMath: subtraction overflow");
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
// 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;
}
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
pragma solidity ^0.6.0;
interface AggregatorValidatorInterface {
function validate(
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
) external returns (bool);
}
pragma solidity ^0.6.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
pragma solidity ^0.6.0;
import "./SimpleWriteAccessController.sol";
/**
* @title SimpleReadAccessController
* @notice Gives access to:
* - any externally owned account (note that offchain actors can always read
* any contract storage regardless of onchain access control measures, so this
* does not weaken the access control while improving usability)
* - accounts explicitly added to an access list
* @dev SimpleReadAccessController is not suitable for access controlling writes
* since it grants any externally owned account access! See
* SimpleWriteAccessController for that.
*/
contract SimpleReadAccessController is SimpleWriteAccessController {
/**
* @notice Returns the access of an address
* @param _user The address to query
*/
function hasAccess(
address _user,
bytes memory _calldata
)
public
view
virtual
override
returns (bool)
{
return super.hasAccess(_user, _calldata) || _user == tx.origin;
}
}
pragma solidity ^0.6.0;
import "./Owned.sol";
import "./interfaces/AccessControllerInterface.sol";
/**
* @title SimpleWriteAccessController
* @notice Gives access to accounts explicitly added to an access list by the
* controller's owner.
* @dev does not make any special permissions for externally, see
* SimpleReadAccessController for that.
*/
contract SimpleWriteAccessController is AccessControllerInterface, Owned {
bool public checkEnabled;
mapping(address => bool) internal accessList;
event AddedAccess(address user);
event RemovedAccess(address user);
event CheckAccessEnabled();
event CheckAccessDisabled();
constructor()
public
{
checkEnabled = true;
}
/**
* @notice Returns the access of an address
* @param _user The address to query
*/
function hasAccess(
address _user,
bytes memory
)
public
view
virtual
override
returns (bool)
{
return accessList[_user] || !checkEnabled;
}
/**
* @notice Adds an address to the access list
* @param _user The address to add
*/
function addAccess(address _user)
external
onlyOwner()
{
if (!accessList[_user]) {
accessList[_user] = true;
emit AddedAccess(_user);
}
}
/**
* @notice Removes an address from the access list
* @param _user The address to remove
*/
function removeAccess(address _user)
external
onlyOwner()
{
if (accessList[_user]) {
accessList[_user] = false;
emit RemovedAccess(_user);
}
}
/**
* @notice makes the access check enforced
*/
function enableAccessCheck()
external
onlyOwner()
{
if (!checkEnabled) {
checkEnabled = true;
emit CheckAccessEnabled();
}
}
/**
* @notice makes the access check unenforced
*/
function disableAccessCheck()
external
onlyOwner()
{
if (checkEnabled) {
checkEnabled = false;
emit CheckAccessDisabled();
}
}
/**
* @dev reverts if the caller does not have access
*/
modifier checkAccess() {
require(hasAccess(msg.sender, msg.data), "No access");
_;
}
}
pragma solidity ^0.6.0;
interface AccessControllerInterface {
function hasAccess(address user, bytes calldata data) external view returns (bool);
} | * @notice get data about the latest round. Consumers are encouraged to check that they're receiving fresh data by inspecting the updatedAt and answeredInRound return values. Consumers are encouraged to use this more fully featured method over the "legacy" latestAnswer functions. Consumers are encouraged to check that they're receiving fresh data by inspecting the updatedAt and answeredInRound return values. @return roundId is the round ID for which data was retrieved @return answer is the answer for the given round @return startedAt is the timestamp when the round was started. This is 0 if the round hasn't been started yet. @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) @return answeredInRound is the round ID of the round in which the answer was computed. answeredInRound may be smaller than roundId when the round timed out. answerInRound is equal to roundId when the round didn't time out and was completed regularly. @dev overridden funcion to add the checkAccess() modifier @dev Note that for in-progress rounds (i.e. rounds that haven't yet received maxSubmissions) answer and updatedAt may change between queries./ | function latestRoundData()
public
view
override
checkAccess()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return super.latestRoundData();
}
| 565,195 | [
1,
588,
501,
2973,
326,
4891,
3643,
18,
22210,
414,
854,
2446,
477,
11349,
358,
866,
716,
2898,
4565,
15847,
12186,
501,
635,
5334,
310,
326,
31944,
471,
5803,
329,
382,
11066,
327,
924,
18,
22210,
414,
854,
2446,
477,
11349,
358,
999,
333,
1898,
7418,
2572,
72,
707,
1879,
326,
315,
17386,
6,
4891,
13203,
4186,
18,
22210,
414,
854,
2446,
477,
11349,
358,
866,
716,
2898,
4565,
15847,
12186,
501,
635,
5334,
310,
326,
31944,
471,
5803,
329,
382,
11066,
327,
924,
18,
327,
3643,
548,
353,
326,
3643,
1599,
364,
1492,
501,
1703,
10295,
327,
5803,
353,
326,
5803,
364,
326,
864,
3643,
327,
5746,
861,
353,
326,
2858,
1347,
326,
3643,
1703,
5746,
18,
1220,
353,
374,
309,
326,
3643,
13342,
1404,
2118,
5746,
4671,
18,
327,
31944,
353,
326,
2858,
1347,
326,
3643,
1142,
1703,
3526,
261,
77,
18,
73,
18,
5803,
1703,
1142,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
225,
445,
4891,
11066,
751,
1435,
203,
565,
1071,
203,
565,
1476,
203,
565,
3849,
203,
565,
28484,
1435,
203,
565,
1135,
261,
203,
1377,
2254,
3672,
3643,
548,
16,
203,
1377,
509,
5034,
5803,
16,
203,
1377,
2254,
5034,
5746,
861,
16,
203,
1377,
2254,
5034,
31944,
16,
203,
1377,
2254,
3672,
5803,
329,
382,
11066,
203,
565,
262,
203,
225,
288,
203,
565,
327,
2240,
18,
13550,
11066,
751,
5621,
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
]
|
./full_match/4/0xC89d6Cb70ec9a171E31904C274d3Fe911012eecC/sources/pep.sol | Return addresses which have Giveaways
| address[] memory result= new address[](gWallets.length); | 13,367,222 | [
1,
990,
6138,
1492,
1240,
22374,
69,
3052,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
8526,
3778,
563,
33,
394,
1758,
8526,
12,
75,
26558,
2413,
18,
2469,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xDE2b84fcAE56A0BebC94B1dAcEd90c3b9043161b/sources/src/DssVest.sol | new duration as time between bgn and revocationTime
| _tau = sub(revocationTime, _bgn); | 17,097,971 | [
1,
2704,
3734,
487,
813,
3086,
324,
1600,
471,
24158,
950,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
389,
29908,
273,
720,
12,
9083,
4431,
950,
16,
389,
70,
1600,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x7E9f2FC2162C20dfFE87c61AF57408f8c21855AA/sources/CometoDubai.sol | Buy FeeSell FeeOriginal Fee | contract CometoDubai is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Come to Dubai";
string private constant _symbol = "DUBAI";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 10000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 0;
uint256 private _taxFeeOnBuy = 0;
uint256 private _redisFeeOnSell = 0;
uint256 private _taxFeeOnSell = 0;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xc00278FA7ECC0342726F7a00d9B7903f2f1B1adD);
address payable private _marketingAddress = payable(0xc00278FA7ECC0342726F7a00d9B7903f2f1B1adD);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true;
bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true;
bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true;
bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true;
bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true;
bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
} | 15,512,241 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1286,
11453,
40,
373,
10658,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
799,
73,
358,
463,
373,
10658,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
31429,
18194,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
2130,
11706,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
38,
9835,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
374,
31,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
55,
1165,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
55,
1165,
273,
374,
31,
203,
203,
565,
2254,
5034,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2022-01-24
*/
/**
*Submitted for verification at BscScan.com on 2022-01-06
*/
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
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;
}
}
}
/**
* @dev Interface of the ETH165 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 ({ETH165Checker}).
*
* For an implementation, see {ETH165}.
*/
interface IETH165Upgradeable {
/**
* @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);
}
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @dev Required interface of an ETH721 compliant contract.
*/
interface IETH721Upgradeable is IETH165Upgradeable {
/**
* @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 ETH721 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 {IETH721Receiver-onETH721Received}, 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 {IETH721Receiver-onETH721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ETH721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ETH721 asset contracts.
*/
interface IETH721ReceiverUpgradeable {
/**
* @dev Whenever an {IETH721} `tokenId` token is transferred to this contract via {IETH721-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 `IETH721.onETH721Received.selector`.
*/
function onETH721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ETH-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IETH721MetadataUpgradeable is IETH721Upgradeable {
/**
* @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);
}
/**
* @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);
}
}
}
}
/*
* @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;
}
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdeg";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Implementation of the {IETH165} interface.
*
* Contracts that want to implement ETH165 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, {ETH165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ETH165Upgradeable is Initializable, IETH165Upgradeable {
function __ETH165_init() internal initializer {
__ETH165_init_unchained();
}
function __ETH165_init_unchained() internal initializer {
}
/**
* @dev See {IETH165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IETH165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ETH721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ETH721Enumerable}.
*/
contract ETH721Upgradeable is Initializable, ContextUpgradeable, ETH165Upgradeable, IETH721Upgradeable, IETH721MetadataUpgradeable {
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(uint256 => mapping(address => uint256)) public 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 __ETH721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ETH165_init_unchained();
__ETH721_init_unchained(name_, symbol_);
}
function __ETH721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IETH165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ETH165Upgradeable, IETH165Upgradeable) returns (bool) {
return
interfaceId == type(IETH721Upgradeable).interfaceId ||
interfaceId == type(IETH721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IETH721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ETH721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IETH721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ETH721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IETH721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IETH721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IETH721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ETH721Metadata: 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 {IETH721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ETH721Upgradeable.ownerOf(tokenId);
require(to != owner, "ETH721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ETH721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IETH721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ETH721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IETH721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ETH721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IETH721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IETH721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ETH721: transfer caller is not owner nor approved");
balances[tokenId][to] +=1;
balances[tokenId][from] -=1;
_transfer(from, to, tokenId);
}
/**
* @dev See {IETH721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
balances[tokenId][to] +=1;
balances[tokenId][from] -=1;
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IETH721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ETH721: 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 ETH721 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 {IETH721Receiver-onETH721Received}, 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(_checkOnETH721Received(from, to, tokenId, _data), "ETH721: transfer to non ETH721Receiver 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), "ETH721: operator query for nonexistent token");
address owner = ETH721Upgradeable.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 {IETH721Receiver-onETH721Received}, 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-ETH721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IETH721Receiver-onETH721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnETH721Received(address(0), to, tokenId, _data),
"ETH721: transfer to non ETH721Receiver 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), "ETH721: mint to the zero address");
require(!_exists(tokenId), "ETH721: 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 = ETH721Upgradeable.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(ETH721Upgradeable.ownerOf(tokenId) == from, "ETH721: transfer of token that is not own");
require(to != address(0), "ETH721: 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(ETH721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IETH721Receiver-onETH721Received} 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 _checkOnETH721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IETH721ReceiverUpgradeable(to).onETH721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IETH721ReceiverUpgradeable.onETH721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ETH721: transfer to non ETH721Receiver 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;
}
/**
* @title ETH-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IETH721EnumerableUpgradeable is IETH721Upgradeable {
/**
* @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);
}
/**
* @dev This implements an optional extension of {ETH721} 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 ETH721EnumerableUpgradeable is Initializable, ETH721Upgradeable, IETH721EnumerableUpgradeable {
function __ETH721Enumerable_init() internal initializer {
__Context_init_unchained();
__ETH165_init_unchained();
__ETH721Enumerable_init_unchained();
}
function __ETH721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IETH165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IETH165Upgradeable, ETH721Upgradeable) returns (bool) {
return interfaceId == type(IETH721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IETH721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ETH721Upgradeable.balanceOf(owner), "ETH721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IETH721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IETH721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ETH721EnumerableUpgradeable.totalSupply(), "ETH721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ETH721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ETH721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
/**
* @dev ETH721 token with storage based token URI management.
*/
abstract contract ETH721URIStorageUpgradeable is Initializable, ETH721Upgradeable {
function __ETH721URIStorage_init() internal initializer {
__Context_init_unchained();
__ETH165_init_unchained();
__ETH721URIStorage_init_unchained();
}
function __ETH721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IETH721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ETH721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = super._baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ETH721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
/**
* @title ETH721 Burnable Token
* @dev ETH721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ETH721BurnableUpgradeable is Initializable, ContextUpgradeable, ETH721Upgradeable, OwnableUpgradeable {
function __ETH721Burnable_init() internal initializer {
__Context_init_unchained();
__ETH165_init_unchained();
__ETH721Burnable_init_unchained();
__Ownable_init();
}
using SafeMathUpgradeable for uint256;
function __ETH721Burnable_init_unchained() internal initializer {
}
/**
* @dev Burns `tokenId`. See {ETH721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
if( msg.sender == owner()){
address owner = ETH721Upgradeable.ownerOf(tokenId);
balances[tokenId][owner].sub(1);
_burn(tokenId);
}
else{
require(balances[tokenId][msg.sender] == 1,"Not a Owner");
balances[tokenId][msg.sender].sub(1);
_burn(tokenId);
}
}
uint256[50] private __gap;
}
interface IETH20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @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);
}
contract Milage721 is
ETH721Upgradeable,
ETH721EnumerableUpgradeable,
ETH721URIStorageUpgradeable,
ETH721BurnableUpgradeable
{
event Approve(
address indexed owner,
uint256 indexed token_id,
bool approved
);
event OrderPlace(
address indexed from,
uint256 indexed tokenId,
uint256 indexed value
);
event FeeTransfer(
uint256 admin,
uint256 creator,
uint256 owner
);
event CancelOrder(address indexed from, uint256 indexed tokenId);
event ChangePrice(address indexed from, uint256 indexed tokenId, uint256 indexed value);
event TokenId(address indexed from, uint256 indexed id);
using SafeMathUpgradeable for uint256;
struct Order {
uint256 tokenId;
uint256 price;
}
mapping(address => mapping(uint256 => Order)) public order_place;
mapping(uint256 => mapping(address => bool)) public checkOrder;
mapping (uint256 => uint256) public totalQuantity;
mapping(uint256 => address) public _creator;
mapping(uint256 => uint256) public _royal;
mapping(string => address) private tokentype;
uint256 private serviceValue;
uint256 private sellervalue;
string private _currentBaseURI;
uint256 public _tid;
uint256 deci;
function initialize() public initializer {
__Ownable_init();
ETH721Upgradeable.__ETH721_init("Milage trade center", "MILAGETECHLLC");
_tid = 1;
serviceValue = 2500000000000000000;
sellervalue = 0;
deci = 18;
}
function getServiceFee() public view returns(uint256, uint256){
return (serviceValue, sellervalue);
}
function setServiceValue(uint256 _serviceValue, uint256 sellerfee) public onlyOwner{
serviceValue = _serviceValue;
sellervalue = sellerfee;
}
function getTokenAddress(string memory _type) public view returns(address){
return tokentype[_type];
}
function addTokenType(string[] memory _type,address[] memory tokenAddress) public onlyOwner{
require(_type.length == tokenAddress.length,"Not equal for type and tokenAddress");
for(uint i = 0; i < _type.length; i++) {
tokentype[_type[i]] = tokenAddress[i];
}
}
function safeMint(address to, uint256 tokenId) public onlyOwner {
_safeMint(to, tokenId);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_currentBaseURI = baseURI;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ETH721Upgradeable, ETH721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId)
internal
override(ETH721Upgradeable, ETH721URIStorageUpgradeable)
{
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ETH721Upgradeable, ETH721URIStorageUpgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ETH721Upgradeable, ETH721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function mint(
string memory ipfsmetadata,
uint256 value,
uint256 supply,
uint256 royal
) public{
_tid = _tid.add(1);
uint256 id_ = _tid.add(block.timestamp);
_setTokenURI(id_, ipfsmetadata);
_creator[id_]=msg.sender;
_safeMint(msg.sender, id_);
_royal[id_]=royal*1e18;
balances[id_][msg.sender] =supply ;
if (value != 0) {
_orderPlace(msg.sender, id_, value);
}
totalQuantity[id_] = supply;
emit TokenId(msg.sender, id_);
}
function orderPlace(uint256 tokenId, uint256 _price) public{
require(_price > 0, "Price must greater than Zero");
_orderPlace(msg.sender, tokenId, _price);
}
function _orderPlace(
address from,
uint256 tokenId,
uint256 _price
) internal {
require(balances[tokenId][from] > 0, "Is Not a Owner");
Order memory order;
order.tokenId = tokenId;
order.price = _price;
order_place[from][tokenId] = order;
checkOrder[tokenId][from] = true;
emit OrderPlace(from, tokenId, _price);
}
function calc(uint256 amount, uint256 royal, uint256 _serviceValue, uint256 _sellervalue) internal pure returns(uint256, uint256, uint256){
uint256 fee = pETHent(amount, _serviceValue);
uint256 roy = pETHent(amount, royal);
uint256 netamount = 0;
if(_sellervalue != 0){
uint256 fee1 = pETHent(amount, _sellervalue);
fee = fee.add(fee1);
netamount = amount.sub(fee1.add(roy));
}
else{
netamount = amount.sub(roy);
}
return (fee, roy, netamount);
}
function pETHent(uint256 value1, uint256 value2)
internal
pure
returns (uint256)
{
uint256 result = value1.mul(value2).div(1e20);
return (result);
}
function saleWithToken(string memory tokenAss,address from , uint256 tokenId, uint256 amount) public{
newtokenasbid(tokenAss,from,amount,tokenId);
if(checkOrder[tokenId][from]==true){
delete order_place[from][tokenId];
checkOrder[tokenId][from] = false;
}
tokenTrans(tokenId, from, msg.sender);
}
function newtokenasbid(string memory tokenAss,address from, uint256 amount, uint256 tokenId) internal {
require(
amount == order_place[from][tokenId].price && order_place[from][tokenId].price > 0,
"Insufficent fund"
);
uint256 val = pETHent(amount, serviceValue).add(amount);
IETH20Upgradeable t = IETH20Upgradeable(tokentype[tokenAss]);
uint256 Tokendecimals = deci.sub(t.decimals());
uint256 approveValue = t.allowance(msg.sender, address(this));
require( approveValue >= val.div(10**Tokendecimals), "Insufficient approve");
require(balances[tokenId][from] > 0, "Is Not a Owner");
(uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue);
require( approveValue >= (_adminfee.add(roy.add(netamount))).div(10**Tokendecimals), "Insufficient approve balance");
if(_adminfee != 0){
t.transferFrom(msg.sender,owner(),_adminfee.div(10**Tokendecimals));
}
if(roy != 0){
t.transferFrom(msg.sender,_creator[tokenId],roy.div(10**Tokendecimals));
}
if(netamount != 0){
t.transferFrom(msg.sender,from,netamount.div(10**Tokendecimals));
}
emit FeeTransfer(_adminfee,roy,netamount);
}
function _acceptBId(string memory tokenAss,address from, uint256 amount, uint256 tokenId) internal{
uint256 val = pETHent(amount, serviceValue).add(amount);
IETH20Upgradeable t = IETH20Upgradeable(tokentype[tokenAss]);
uint256 Tokendecimals = deci.sub(t.decimals());
uint256 approveValue = t.allowance(from, address(this));
require( approveValue >= val.div(10**Tokendecimals) && val > 0, "Insufficient approve");
require(balances[tokenId][msg.sender] > 0, "Is Not a Owner");
(uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue);
require( approveValue >= (_adminfee.add(roy.add(netamount))).div(10**Tokendecimals), "Insufficient approve balance");
if(_adminfee != 0){
t.transferFrom(from,owner(),_adminfee.div(10**Tokendecimals));
}
if(roy != 0){
t.transferFrom(from,_creator[tokenId],roy.div(10**Tokendecimals));
}
if(netamount != 0){
t.transferFrom(from,msg.sender,netamount.div(10**Tokendecimals));
}
emit FeeTransfer(_adminfee,roy,netamount);
}
function saleToken(
address payable from,
uint256 tokenId,
uint256 amount
) public payable {
_saleToken(from, tokenId, amount);
saleTokenTransfer(from, tokenId);
}
function _saleToken(
address payable from,
uint256 tokenId,
uint256 amount
) internal {
uint256 val = pETHent(amount, serviceValue).add(amount);
require( msg.value == val, "msg.value Not equal to current amount");
require(
amount == order_place[from][tokenId].price && order_place[from][tokenId].price > 0,
"Insufficent fund"
);
address payable create = payable(_creator[tokenId]);
address payable admin = payable(owner());
(uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue);
require( msg.value == _adminfee.add(roy.add(netamount)), "msg.value Not equal to Calculation amount");
if(_adminfee != 0){
admin.transfer(_adminfee);
}
if(roy != 0){
create.transfer(roy);
}
if(netamount != 0){
from.transfer(netamount);
}
emit FeeTransfer(_adminfee,roy,netamount);
}
function saleTokenTransfer(address payable from, uint256 tokenId) internal {
if (checkOrder[tokenId][from] == true) {
delete order_place[from][tokenId];
checkOrder[tokenId][from] = false;
}
tokenTrans(tokenId, from, msg.sender);
}
function tokenTrans(
uint256 tokenId,
address from,
address to
) internal {
_approve(msg.sender,tokenId);
safeTransferFrom(from, to, tokenId);
}
function acceptBId(string memory bidtoken,address bidaddr, uint256 amount, uint256 tokenId) public{
_acceptBId(bidtoken, bidaddr, amount, tokenId);
if(checkOrder[tokenId][msg.sender]==true){
delete order_place[msg.sender][tokenId];
checkOrder[tokenId][msg.sender] = false;
}
tokenTrans(tokenId,msg.sender, bidaddr);
}
function cancelOrder(uint256 tokenId) public{
require(balances[tokenId][msg.sender] > 0, "Is Not a Owner");
delete order_place[msg.sender][tokenId];
checkOrder[tokenId][msg.sender] = false;
emit CancelOrder(msg.sender, tokenId);
}
function changePrice(uint256 value, uint256 tokenId) public{
require( balances[tokenId][msg.sender] > 0, "Is Not a Owner");
require( value < order_place[msg.sender][tokenId].price);
order_place[msg.sender][tokenId].price = value;
emit ChangePrice(msg.sender, tokenId, value);
}
function burnToken(uint256 id,address from) public{
require( balances[id][from] == 1, "You are Not a Token Owner or insufficient Token Balance");
burn(id);
if(balances[id][from] == 1){
if(checkOrder[id][from]==true){
delete order_place[from][id];
checkOrder[id][from] = false;
}
}
}
} | * @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), "ETH721: operator query for nonexistent token");
address owner = ETH721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
| 5,998,939 | [
1,
1356,
2856,
1375,
87,
1302,
264,
68,
353,
2935,
358,
10680,
1375,
2316,
548,
8338,
29076,
30,
300,
1375,
2316,
548,
68,
1297,
1005,
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,
565,
445,
389,
291,
31639,
1162,
5541,
12,
2867,
17571,
264,
16,
2254,
5034,
1147,
548,
13,
2713,
1476,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
1584,
44,
27,
5340,
30,
3726,
843,
364,
1661,
19041,
1147,
8863,
203,
3639,
1758,
3410,
273,
512,
2455,
27,
5340,
10784,
429,
18,
8443,
951,
12,
2316,
548,
1769,
203,
3639,
327,
261,
87,
1302,
264,
422,
3410,
747,
336,
31639,
12,
2316,
548,
13,
422,
17571,
264,
747,
353,
31639,
1290,
1595,
12,
8443,
16,
17571,
264,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// import "hardhat/console.sol";
import "./facades/LimboDAOLike.sol";
import "./facades/Burnable.sol";
import "./facades/BehodlerLike.sol";
import "./facades/FlanLike.sol";
import "./facades/UniPairLike.sol";
import "./facades/MigratorLike.sol";
import "./facades/AMMHelper.sol";
import "./facades/AngbandLike.sol";
import "./facades/LimboAddTokenToBehodlerPowerLike.sol";
import "./DAO/Governable.sol";
import "./facades/FlashGovernanceArbiterLike.sol";
/*
Contract: LIMBO is the main staking contract. It corresponds conceptually to Sushi's Masterchef and takes design inspiration from Masterchef.
Context: Limbo is a part of the Behodler ecosystem. All dapps within the Behodler ecosystem either support or are supported by the Behodler AMM.
Purpose: As a single contract store of liquidity, Behodler AMM requires new tokens be initiated with the a TVL equal to the average TVL of existing tokens.
In Behodler nomenclature, the total value of all tokens in the AMM is the total value bonded (TVB) and the value of individual tokens is the average value bonded (AVB).
The primary goal of Limbo is to raise capital for prospective AMM tokens in order to meet the AVB threshold.
Secondary goals: since Limbo possesses staking mechanics, a secondary goal is to encourage lockup of protocol tokens.
Types of staking: Staked tokens are either for migration to Behodler or for lockup. The former pools are threshold and the latter are perpetual.
Primary incentive: users staking on Limbo receive the perpetually minted Flan token.
Economics: When the staked value of a threshold token is migrated to Behodler, SCX is generated. The SCX is used via an external AMM such as Uniswap to prop up the liquidity and value of Flan.
Rather than being used to purchase Flan on the open market, the generated SCX is paired with newly minted Flan in a ratio that steers the price of Flan toward parity with Dai.
This mechanism of pairing and steering the price through minting is known in Behodler as price tilting and effectively doubles the liquidity raised. For instance, suppose we list
$10000 of a new token on Behodler. We then take $10000 worth of SCX and pair it with $10000 of newly minted Flan, adding $20000 of token liquidity to an external AMM. The extra
$10000 will form the price support for newly minted Flan which can be used to encourage future migrations.
In addition to migration driven liquidity growth, Flan will be rewarded for token lockup. For lockup of Flan, the price support pressure of reduced circulating supply will provide additional
runway from which to mint more Flan. For external AMM pair contracts involving SCX or Pyrotokens, the lockup will raise liquidity for those pairs which will promote arbitrage trading of the pairs which will
lead to additional burning of those tokens. For direct lockup of SCX, additional minting of SCX corresponds algorithmically to increased liquidity on Behodler and an increased SCX price. This raises the AVB of Behodler which creates
additional liquidity for Flan during the next migration. Flan therefore has 4 supporting vectors: SCX from migration, price support for SCX via lockup, price support via PyroFlan and indirect price support of Flan and SCX via trading on external pairs (automining).
Nomenclature: Since words like token are incredibly generic, we need to provide context through naming. Sticking to an overall metaphor, to paraphrase MakerDao documentation, reduces code smells.
1. A token listed on Limbo is a Soul
2. When a token lists on Behodler, we say the soul is crossing over. The event is a crossing.
3. A token crosses over when the TVL on Limbo exceeds a threshold.
4. Tokens which do not cross over such as existing tokens listed on Behodler or the protocol tokens are perpetual souls.
Security note: Since the migration steps generate value transfers between protocols, forced delays should be instituted to close any flash loan or dominant miner ttack vectors.
Basic staking incentives:
For both perpatual and threshold souls, a flan per second statistic is divided proportionately amongst the existing stakers.
Late stakers considerations:
Suppose you're the last person to stake on a threshold soul. That is, your stake takes the soul over the crossing threshold and the soul is locked.
In this instance, you would have earned no Flan, creating a declining incentive for stakers to arrive and in the extreme leading
to a situation of never crossing the threshold for any soul. This is a tragedy of the commons situation that leads to an overly
inflated and essentially worthless Flan. We need a strategy to ameliorate this. The strategy needs to:
1. provide sufficient incentive for later arrivals.
2. Not punish early stakers and ideally reward them for being early.
3. Not disproportionately inflate the supply of flan.
Crossing incentives:
After a crossing, stakers are no longer able to withdraw their tokens as they'll now be sent to Behodler. They'll therefore need to be compensated for loss of tokens.
Governance can calibrate two variables on a soul to encourage prospective stakers in threshold souls to breach the threshold:
1. Initial crossing bonus (ICB) is the Flan per token paid to all stakers and is a positive integer.
2. Crossing bonus delta (CBD) is the Flan per token for every second the soul is live. For instance suppose the CBD is 2. From the very first token staked to
the point at which the threshold was crossed, the soul records 10000 seconds passing. This amounts to 2*10000 = 20000 Flan per token.
The ICB and CBD are combined to forma Total Flan Per Token (TF) and the individual user balance is multiplied by TF. For instance, using the example above, suppose the ICB is 10 Flan per token.
This means the total Flan per token paid out is 10 + 20000 = 20010 Flan per token. If a user has 3 T staked, they receive 3*20010 = 60030 Flan as reward for having their T migrated to Behodler.
This is in addition to any Flan their received during the staking phase.
Note: CBD can be negative. This creates a situation where the initial bonus per token is at its highest when the staking round begins.
For negative CBD, the intent is to create a sense of urgency amongst prospective stakers to push the pool over the threshold. For positive CBD, the intent is to draw marginal stakers into the soul in a desire to receive the crossing bonus while the opportunity still exists.
A negative CBD benefits from strong communal coordination. For instance, if the token listed has a large, active and well heeled community, a negative CBD might act as a rallying cry to ape in. A positive CBD benefits from individually uncoordinated motivations (classical market setting)
States of migration:
1. calibration
No staking/unstaking.
2. Staking
Staking/unstaking. If type is threshold, take threshold into account
3. WaitingToCross
Can claim rewards. Can't unstake.
4. CrossedOver
Injected into Behodler
Flash governance:
Since there might be many souls staking, we don't want to have to go through long-to-confirm proposals.
Instead, we want to have the opportunity to flash a governance action quickly. Flash governance happens in the span of 1 transaction.
To protect the community and the integrity of the DAO, all flash governance decisions must be accompanied by a large EYE deposit that presumably is more costly to give up
than the most profitable attack vector. The deposit is locked for a duration long enough for a long form burn proposal to be voted on.
The community can then decide if their governance action was in accord with the wellbeing of Limbo.
If it isn't, they can slash the deposit by betwen 1 and 100%. Flash gov can only move a variable some percentage per day.
Eg. suppose we vote on snapshot to raise the threshold for Sushi to 1200 Sushi from 1180, 1.69%. Some chosen community member flash sets the threshold to the new value.
A malicious flash staker then sets the threshold down to 1150. The community believes that the latter user was acting against the will of the community and a formal proposal is deployed onchain which slashes the user's staked EYE.
The community votes on the proposal and the EYE is slashed. After a fixed timeout, the EYE belonging to the original flash staker.
Rectangle of Fairness:
When new lquidity is added to Behodler, SCX is generated. The fully undiluted price of the new quantity of SCX far exceeds the value of the tokens migrated. Because of the dynamics of Behodler's bonding curve, the
current value of the AVB is always equal to about 25 SCX. If the AVB increases, the increase shows up as in increase in the SCX price so that the 25 SCX metric still holds. For this reason, only 25 SCX is used to prop up
the liquidity of Flan. The surplus SCX generated is burnt. Because multiplying 25 SCX by the current market price gives us a value equal to the AVB and because we wish to strike a balance between boosting Flan and not over diluting the
market with too much SCX, this value is known as the Rectangle of Fairness. While 25 SCX is the value of AVB, it's usually desirable to hold back a bit more than 25 for 2 reasons:
1. SCX burns on transfer so that after all open market operations are complete, we'd have less than 25 remaining.
2. CPMMs such as Uniswap impose hyperbolic price slippage so that trying to withdraw the full balance of SCX results in paying an assymptotically high Flan price. As such we can deploy a bit more than 25 SCX per migrations without worrying about added dilution
*/
enum SoulState {
calibration,
staking,
waitingToCross,
crossedOver
}
enum SoulType {
uninitialized,
threshold, //the default soul type is staked and when reaching a threshold, migrates to Behodler
perpetual //the type of staking pool most people are familiar with.
}
/*
Error string legend:
token not recognized as valid soul. E1
invalid state E2
unstaking locked E3
balance exceeded E4
bonus already claimed. E5
crossing bonus arithmetic invariant. E6
token accounted for. E7
burning excess SCX failed. E8
Invocation reward failed. E9
only threshold souls can be migrated EB
not enough time between crossing and migration EC
bonus must be positive ED
Unauthorized call EE
Protocol disabled EF
Reserve divergence tolerance exceeded EG
not enough time between reserve stamps EH
Minimum APY only applicable to threshold souls EI
Governance action failed. EJ
Access Denied EK
ERC20 Transfer Failed EL
Incorrect SCX transfer to AMMHelper EM
*/
struct Soul {
uint256 lastRewardTimestamp;
uint256 accumulatedFlanPerShare;
uint256 crossingThreshold; //the value at which this soul is elligible to cross over to Behodler
SoulType soulType;
SoulState state;
uint256 flanPerSecond; // fps: we use a helper function to convert min APY into fps
}
struct CrossingParameters {
uint256 stakingBeginsTimestamp; //to calculate bonus
uint256 stakingEndsTimestamp;
int256 crossingBonusDelta; //change in teraFlanPerToken per second
uint256 initialCrossingBonus; //measured in teraFlanPerToken
bool burnable;
}
struct CrossingConfig {
address behodler;
uint256 SCX_fee;
uint256 migrationInvocationReward; //calling migrate is expensive. The caller should be rewarded in Flan.
uint256 crossingMigrationDelay; // this ensures that if Flan is successfully attacked, governance will have time to lock Limbo and prevent bogus migrations
address morgothPower;
address angband;
address ammHelper;
uint16 rectangleOfFairnessInflationFactor; //0-100: if the community finds the requirement to be too strict, they can inflate how much SCX to hold back
}
library SoulLib {
function set(
Soul storage soul,
uint256 crossingThreshold,
uint256 soulType,
uint256 state,
uint256 fps
) external {
soul.crossingThreshold = crossingThreshold;
soul.flanPerSecond = fps;
soul.state = SoulState(state);
soul.soulType = SoulType(soulType);
}
}
library CrossingLib {
function set(
CrossingParameters storage params,
FlashGovernanceArbiterLike flashGoverner,
Soul storage soul,
uint256 initialCrossingBonus,
int256 crossingBonusDelta,
bool burnable,
uint256 crossingThreshold
) external {
flashGoverner.enforceTolerance(initialCrossingBonus, params.initialCrossingBonus);
flashGoverner.enforceToleranceInt(crossingBonusDelta, params.crossingBonusDelta);
params.initialCrossingBonus = initialCrossingBonus;
params.crossingBonusDelta = crossingBonusDelta;
params.burnable = burnable;
flashGoverner.enforceTolerance(crossingThreshold, soul.crossingThreshold);
soul.crossingThreshold = crossingThreshold;
}
}
library MigrationLib {
function migrate(
address token,
LimboAddTokenToBehodlerPowerLike power,
CrossingParameters memory crossingParams,
CrossingConfig memory crossingConfig,
FlanLike flan,
uint256 RectangleOfFairness,
Soul storage soul
) external returns (uint256, uint256) {
power.parameterize(token, crossingParams.burnable);
//invoke Angband execute on power that migrates token type to Behodler
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(address(crossingConfig.morgothPower), tokenBalance);
AngbandLike(crossingConfig.angband).executePower(address(crossingConfig.morgothPower));
uint256 scxMinted = IERC20(address(crossingConfig.behodler)).balanceOf(address(this));
uint256 adjustedRectangle = ((crossingConfig.rectangleOfFairnessInflationFactor) * RectangleOfFairness) / 100;
//for top up or exotic high value migrations.
if (scxMinted <= adjustedRectangle) {
adjustedRectangle = scxMinted / 2;
}
//burn SCX - rectangle
uint256 excessSCX = scxMinted - adjustedRectangle;
require(BehodlerLike(crossingConfig.behodler).burn(excessSCX), "E8");
//use remaining scx to buy flan and pool it on an external AMM
IERC20(crossingConfig.behodler).transfer(crossingConfig.ammHelper, adjustedRectangle);
uint256 lpMinted = AMMHelper(crossingConfig.ammHelper).stabilizeFlan(adjustedRectangle);
//reward caller and update soul state
require(flan.mint(msg.sender, crossingConfig.migrationInvocationReward), "E9");
soul.state = SoulState.crossedOver;
return (tokenBalance, lpMinted);
}
}
/// @title Limbo
/// @author Justin Goro
/// @notice Tokens are either staked for locking (perpetual) or for migration to the Behodler AMM (threshold).
/// @dev The governance functions are initially unguarded to allow the deploying dev to rapidly set up without having to endure governance imposed time limits on proposals. Ending the config period is a irreversible action.
contract Limbo is Governable {
using SafeERC20 for IERC20;
using SoulLib for Soul;
using MigrationLib for address;
using CrossingLib for CrossingParameters;
event SoulUpdated(address soul, uint256 fps);
event Staked(address staker, address soul, uint256 amount);
event Unstaked(address staker, address soul, uint256 amount);
event TokenListed(address token, uint256 amount, uint256 scxfln_LP_minted);
event ClaimedReward(address staker, address soul, uint256 index, uint256 amount);
event BonusPaid(address token, uint256 index, address recipient, uint256 bonus);
struct User {
uint256 stakedAmount;
uint256 rewardDebt;
bool bonusPaid;
}
uint256 constant TERA = 1E12;
uint256 constant RectangleOfFairness = 30 ether; //MP = 1/t. Rect = tMP = t(1/t) = 1. 25 is the result of scaling factors on Behodler.
bool protocolEnabled = true;
///@notice protocol settings for migrating threshold tokens to Behodler
CrossingConfig public crossingConfig;
///@notice Since a token can be listed more than once on Behodler, we index each listing to separate the rewards from each staking event.
///@dev tokenAddress->index->stakingInfo
mapping(address => mapping(uint256 => Soul)) public souls;
///@notice Each token maintains its own index to allow Limbo to keep rewards for each staking event separate
mapping(address => uint256) public latestIndex;
///@dev tokenAddress->userAddress->soulIndex->Userinfo
mapping(address => mapping(address => mapping(uint256 => User))) public userInfo;
///@dev token->index->data
mapping(address => mapping(uint256 => CrossingParameters)) public tokenCrossingParameters;
///@dev soul->owner->unstaker->amount
mapping(address => mapping(address => mapping(address => uint256))) unstakeApproval;
FlanLike Flan;
modifier enabled() {
require(protocolEnabled, "EF");
_;
}
///@notice helper function for approximating a total dollar value APY for a threshold soul.
///@param token threshold soul
///@param desiredAPY because values may be out of sync with the market, this function can only ever approximate an APY
///@param daiThreshold user can select a Behodler AVB in Dai. 0 indicates the migration oracle value for AVB should be used.
function attemptToTargetAPY(
address token,
uint256 desiredAPY,
uint256 daiThreshold
) public governanceApproved(false) {
Soul storage soul = currentSoul(token);
require(soul.soulType == SoulType.threshold, "EI");
uint256 fps = AMMHelper(crossingConfig.ammHelper).minAPY_to_FPS(desiredAPY, daiThreshold);
flashGoverner.enforceTolerance(soul.flanPerSecond, fps);
soul.flanPerSecond = fps;
}
///@notice refreshes current state of soul.
function updateSoul(address token) public {
Soul storage s = currentSoul(token);
updateSoul(token, s);
}
function updateSoul(address token, Soul storage soul) internal {
require(soul.soulType != SoulType.uninitialized, "E1");
uint256 finalTimeStamp = block.timestamp;
if (soul.state != SoulState.staking) {
finalTimeStamp = tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp;
}
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
uint256 flanReward = (finalTimeStamp - soul.lastRewardTimestamp) * soul.flanPerSecond;
soul.accumulatedFlanPerShare = soul.accumulatedFlanPerShare + ((flanReward * TERA) / balance);
}
soul.lastRewardTimestamp = finalTimeStamp;
}
constructor(address flan, address limboDAO) Governable(limboDAO) {
Flan = FlanLike(flan);
}
///@notice configure global migration settings such as the address of Behodler and the minumum delay between end of staking and migration
function configureCrossingConfig(
address behodler,
address angband,
address ammHelper,
address morgothPower,
uint256 migrationInvocationReward,
uint256 crossingMigrationDelay,
uint16 rectInflationFactor //0 to 100
) public onlySuccessfulProposal {
crossingConfig.migrationInvocationReward = migrationInvocationReward * (1 ether);
crossingConfig.behodler = behodler;
crossingConfig.crossingMigrationDelay = crossingMigrationDelay;
crossingConfig.angband = angband;
crossingConfig.ammHelper = ammHelper;
crossingConfig.morgothPower = morgothPower;
require(rectInflationFactor <= 10000, "E6");
crossingConfig.rectangleOfFairnessInflationFactor = rectInflationFactor;
}
///@notice if an exploit in any part of Limbo or its souls is detected, anyone with sufficient EYE balance can disable the protocol instantly
function disableProtocol() public governanceApproved(true) {
protocolEnabled = false;
}
///@notice Once disabled, the only way to reenable is via a formal proposal. This forces the community to deliberate on the legitimacy of the disabling that lead to this state. A malicious call to disable can have its EYE slashed.
function enableProtocol() public onlySuccessfulProposal {
protocolEnabled = true;
}
///@notice Governance function for rapidly calibrating a soul. Useful for responding to large price movements quickly
///@param token Soul to calibrate
///@param initialCrossingBonus Of the crossing bonus flan payout, this represents the fixed Flan per token component
///@param crossingBonusDelta Of the crossing bonus flan payout, this represents the payout per flan per second that the soul is in staking state
///@param fps Flan Per Second staked.
function adjustSoul(
address token,
uint256 initialCrossingBonus,
int256 crossingBonusDelta,
uint256 fps
) public governanceApproved(false) {
Soul storage soul = currentSoul(token);
flashGoverner.enforceTolerance(soul.flanPerSecond, fps);
soul.flanPerSecond = fps;
CrossingParameters storage params = tokenCrossingParameters[token][latestIndex[token]];
flashGoverner.enforceTolerance(params.initialCrossingBonus, initialCrossingBonus);
flashGoverner.enforceTolerance(
uint256(params.crossingBonusDelta < 0 ? params.crossingBonusDelta * -1 : params.crossingBonusDelta),
uint256(crossingBonusDelta < 0 ? crossingBonusDelta * -1 : crossingBonusDelta)
);
params.initialCrossingBonus = initialCrossingBonus;
params.crossingBonusDelta = crossingBonusDelta;
}
///@notice Configuration of soul through formal proposal. Should only be called infrequently.
///@dev Unlike with flash governance, variable movements are unguarded
///@param crossingThreshold The token balance on Behodler that triggers the soul to enter into waitingToCross state
///@param soulType Indicates whether the soul is perpetual or threshold
///@param state a threshold soul can be either staking, waitingToCross, or CrossedOver. Both soul types can be in calibration state.
///@param index a token could be initially liste as a threshold soul and then later added as perpetual. An index helps distinguish these two events so that user late to claim rewards have no artificial time constraints imposed on their behaviour
function configureSoul(
address token,
uint256 crossingThreshold,
uint256 soulType,
uint256 state,
uint256 index,
uint256 fps
) public onlySoulUpdateProposal {
{
latestIndex[token] = index > latestIndex[token] ? latestIndex[token] + 1 : latestIndex[token];
Soul storage soul = currentSoul(token);
bool fallingBack = soul.state != SoulState.calibration && SoulState(state) == SoulState.calibration;
soul.set(crossingThreshold, soulType, state, fps);
if (SoulState(state) == SoulState.staking) {
tokenCrossingParameters[token][latestIndex[token]].stakingBeginsTimestamp = block.timestamp;
}
if(fallingBack){
tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp = block.timestamp;
}
}
emit SoulUpdated(token, fps);
}
///@notice We need to know how to handle threshold souls at the point of crossing
///@param token The soul to configure
///@param initialCrossingBonus Of the crossing bonus flan payout, this represents the fixed Flan per token component
///@param crossingBonusDelta Of the crossing bonus flan payout, this represents the payout per flan per second that the soul is in staking state
///@param burnable For listing on Behodler, is this token going to burn on trade or does it get its own Pyrotoken
///@param crossingThreshold The token balance on Behodler that triggers the soul to enter into waitingToCross state
function configureCrossingParameters(
address token,
uint256 initialCrossingBonus,
int256 crossingBonusDelta,
bool burnable,
uint256 crossingThreshold
) public governanceApproved(false) {
CrossingParameters storage params = tokenCrossingParameters[token][latestIndex[token]];
Soul storage soul = currentSoul(token);
params.set(flashGoverner, soul, initialCrossingBonus, crossingBonusDelta, burnable, crossingThreshold);
}
///@notice User facing stake function for handling both types of souls
///@param token The soul to stake
///@param amount The amount of tokens to stake
/**@dev Can handle fee on transfer tokens but for more exotic tokens such as rebase tokens, use a proxy wrapper. See the TokenProxyRegistry for logistics.
*The purpose of balance checking before and after transfer of tokens is to account for fee-on-transfer discrepencies so that tokens like SCX can be listed without inducing
*broken states. The community is encouraged to use proxy wrappers for tokens which may open up Limbo or Beholer exploit vulnerabilities.
*Security enforcement of tokens listed on Limbo is offloaded to governance so that Limbo isn't required to anticipate every attack vector.
*/
function stake(address token, uint256 amount) public enabled {
Soul storage soul = currentSoul(token);
require(soul.state == SoulState.staking, "E2");
updateSoul(token, soul);
uint256 currentIndex = latestIndex[token];
User storage user = userInfo[token][msg.sender][currentIndex];
if (amount > 0) {
//dish out accumulated rewards.
uint256 pending = getPending(user, soul);
if (pending > 0) {
Flan.mint(msg.sender, pending);
}
//Balance checking accounts for FOT discrepencies
uint256 oldBalance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 newBalance = IERC20(token).balanceOf(address(this));
user.stakedAmount = user.stakedAmount + newBalance - oldBalance; //adding true difference accounts for FOT tokens
if (soul.soulType == SoulType.threshold && newBalance > soul.crossingThreshold) {
soul.state = SoulState.waitingToCross;
tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp = block.timestamp;
}
}
user.rewardDebt = (user.stakedAmount * soul.accumulatedFlanPerShare) / TERA;
emit Staked(msg.sender, token, user.stakedAmount);
}
///@notice User facing unstake function for handling both types of souls. For threshold souls, can only be called during staking phase.
///@param token The soul to unstake
///@param amount The amount of tokens to unstake
function unstake(address token, uint256 amount) public enabled {
_unstake(token, amount, msg.sender, msg.sender);
}
///@notice Allows for Limbo to be upgraded 1 user at a time without introducing a system wide security risk. Anticipates moving tokens to Limbo2 (wen Limbo2??)
///@dev similar to ERC20.transferFrom, this function allows a user to approve an upgrade contract migrate their staked tokens safely.
function unstakeFor(
address token,
uint256 amount,
address holder
) public {
_unstake(token, amount, msg.sender, holder);
}
function _unstake(
address token,
uint256 amount,
address unstaker,
address holder
) internal {
if (unstaker != holder) {
unstakeApproval[token][holder][unstaker] -= amount;
}
Soul storage soul = currentSoul(token);
require(soul.state == SoulState.calibration || soul.state == SoulState.staking, "E2");
updateSoul(token, soul);
User storage user = userInfo[token][holder][latestIndex[token]];
require(user.stakedAmount >= amount, "E4");
uint256 pending = getPending(user, soul);
if (pending > 0 && amount > 0) {
user.stakedAmount = user.stakedAmount - amount;
IERC20(token).safeTransfer(address(unstaker), amount);
rewardAdjustDebt(unstaker, pending, soul.accumulatedFlanPerShare, user);
emit Unstaked(unstaker, token, amount);
}
}
///@notice accumulated flan rewards from staking can be claimed
///@param token The soul for which to claim rewards
///@param index souls no longer listed may still have unclaimed rewards.
function claimReward(address token, uint256 index) public enabled {
Soul storage soul = souls[token][index];
updateSoul(token, soul);
User storage user = userInfo[token][msg.sender][index];
uint256 pending = getPending(user, soul);
if (pending > 0) {
rewardAdjustDebt(msg.sender, pending, soul.accumulatedFlanPerShare, user);
emit ClaimedReward(msg.sender, token, index, pending);
}
}
///@notice for threshold souls only, claiming the compensation for migration tokens known as the Crossing Bonus
///@param token The soul for which to claim rewards
///@param index souls no longer listed may still have an unclaimed bonus.
///@dev The tera factor is to handle fixed point calculations without significant loss of precision.
function claimBonus(address token, uint256 index) public enabled {
Soul storage soul = souls[token][index];
CrossingParameters storage crossing = tokenCrossingParameters[token][index];
require(soul.state == SoulState.crossedOver || soul.state == SoulState.waitingToCross, "E2");
User storage user = userInfo[token][msg.sender][index];
require(!user.bonusPaid, "E5");
user.bonusPaid = true;
int256 accumulatedFlanPerTeraToken = crossing.crossingBonusDelta *
int256(crossing.stakingEndsTimestamp - crossing.stakingBeginsTimestamp);
//assert signs are the same
require(accumulatedFlanPerTeraToken * crossing.crossingBonusDelta >= 0, "E6");
int256 finalFlanPerTeraToken = int256(crossing.initialCrossingBonus) + accumulatedFlanPerTeraToken;
uint256 flanBonus = 0;
require(finalFlanPerTeraToken > 0, "ED");
flanBonus = uint256((int256(user.stakedAmount) * finalFlanPerTeraToken)) / TERA;
Flan.mint(msg.sender, flanBonus);
emit BonusPaid(token, index, msg.sender, flanBonus);
}
/**@notice some tokens may be sent to Limbo by mistake or unhandled in some manner. For instance, if a Pooltogether token is listed and Limbo wins,
the reward token may not have relevance on Limbo. If the token exists as a pair with Flan on the external AMM
this function buys Flan from the AMM and burns it. A small percentage of the purchased Flan is sent to the caller to incentivize
flushing Limbo of stuck tokens. A secondary incentive exists to create new pairs for Flan.
*/
function claimSecondaryRewards(address token) public {
SoulState state = currentSoul(token).state;
require(state == SoulState.calibration || state == SoulState.crossedOver, "E7");
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(crossingConfig.ammHelper, balance);
AMMHelper(crossingConfig.ammHelper).buyFlanAndBurn(token, balance, msg.sender);
}
///@notice migrates threshold token from Limbo to Behodler and orchestrates Flan boosting mechanics. Callers of this function are rewared to compensate for gas expenditure
/**@dev this function depends on a Morgoth Power. For those unfamiliar, a power is similar to a spell on other DAOs. Morgoth owns Behodler and so the only way to list
* a token on Behodler is via a Morgoth Power. Permission mapping is handled on Morgoth side. Calling this function assumes that the power has been calibrated and than Limbo has been granted
* permission on Morgoth to execute migrations to Behodler. The other big depenency is the AMM helper which contains the bulk of the migration logic.
*/
function migrate(address token) public enabled {
Soul storage soul = currentSoul(token);
require(soul.soulType == SoulType.threshold, "EB");
require(soul.state == SoulState.waitingToCross, "E2");
require(
block.timestamp - tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp >
crossingConfig.crossingMigrationDelay,
"EC"
);
(uint256 tokenBalance, uint256 lpMinted) = token.migrate(
LimboAddTokenToBehodlerPowerLike(crossingConfig.morgothPower),
tokenCrossingParameters[token][latestIndex[token]],
crossingConfig,
Flan,
RectangleOfFairness,
soul
);
emit TokenListed(token, tokenBalance, lpMinted);
}
///@notice analogous to ERC20 approve, this function gives third party contracts permission to migrate token balances on Limbo. Useful for both upgrades and third party integrations into Limbo
function approveUnstake(
address soul,
address unstaker,
uint256 amount
) external {
unstakeApproval[soul][msg.sender][unstaker] = amount; //soul->owner->unstaker->amount
}
function rewardAdjustDebt(
address recipient,
uint256 pending,
uint256 accumulatedFlanPerShare,
User storage user
) internal {
Flan.mint(recipient, pending);
user.rewardDebt = (user.stakedAmount * accumulatedFlanPerShare) / TERA;
}
function currentSoul(address token) internal view returns (Soul storage) {
return souls[token][latestIndex[token]];
}
function getPending(User memory user, Soul memory soul) internal pure returns (uint256) {
return ((user.stakedAmount * soul.accumulatedFlanPerShare) / TERA) - user.rewardDebt;
}
}
| @notice configure global migration settings such as the address of Behodler and the minumum delay between end of staking and migration | function configureCrossingConfig(
address behodler,
address angband,
address ammHelper,
address morgothPower,
uint256 migrationInvocationReward,
uint256 crossingMigrationDelay,
) public onlySuccessfulProposal {
crossingConfig.migrationInvocationReward = migrationInvocationReward * (1 ether);
crossingConfig.behodler = behodler;
crossingConfig.crossingMigrationDelay = crossingMigrationDelay;
crossingConfig.angband = angband;
crossingConfig.ammHelper = ammHelper;
crossingConfig.morgothPower = morgothPower;
require(rectInflationFactor <= 10000, "E6");
crossingConfig.rectangleOfFairnessInflationFactor = rectInflationFactor;
}
| 5,521,282 | [
1,
14895,
2552,
6333,
1947,
4123,
487,
326,
1758,
434,
4823,
76,
369,
749,
471,
326,
1131,
379,
379,
4624,
3086,
679,
434,
384,
6159,
471,
6333,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
5068,
13941,
310,
809,
12,
203,
565,
1758,
12433,
369,
749,
16,
203,
565,
1758,
392,
4490,
464,
16,
203,
565,
1758,
2125,
81,
2276,
16,
203,
565,
1758,
312,
3341,
10370,
13788,
16,
203,
565,
2254,
5034,
6333,
9267,
17631,
1060,
16,
203,
565,
2254,
5034,
6828,
310,
10224,
6763,
16,
203,
225,
262,
1071,
1338,
14277,
14592,
288,
203,
565,
6828,
310,
809,
18,
15746,
9267,
17631,
1060,
273,
6333,
9267,
17631,
1060,
380,
261,
21,
225,
2437,
1769,
203,
565,
6828,
310,
809,
18,
2196,
76,
369,
749,
273,
12433,
369,
749,
31,
203,
565,
6828,
310,
809,
18,
14653,
310,
10224,
6763,
273,
6828,
310,
10224,
6763,
31,
203,
565,
6828,
310,
809,
18,
539,
12752,
273,
392,
4490,
464,
31,
203,
565,
6828,
310,
809,
18,
301,
81,
2276,
273,
2125,
81,
2276,
31,
203,
565,
6828,
310,
809,
18,
81,
3341,
10370,
13788,
273,
312,
3341,
10370,
13788,
31,
203,
565,
2583,
12,
2607,
27040,
367,
6837,
1648,
12619,
16,
315,
41,
26,
8863,
203,
565,
6828,
310,
809,
18,
2607,
4341,
951,
42,
1826,
4496,
27040,
367,
6837,
273,
4917,
27040,
367,
6837,
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
]
|
./full_match/1/0xDf7D56E526eD37834be0e4D2C8aecE552f54cFea/sources/contracts/BaseSmartVaultDeployer.sol | Create and setup action Set holder token out Set holder max slippage Transfer admin permissions to admin Authorize action to wrap and swap from Smart Vault | function _setupHolderAction(SmartVault smartVault, HolderActionParams memory params) internal {
Holder holder = Holder(params.impl);
Deployer.setupBaseAction(holder, params.admin, address(smartVault));
address[] memory executors = Arrays.from(params.admin, params.managers, new address[](0));
Deployer.setupActionExecutors(holder, executors, holder.call.selector);
Deployer.setupTokenThresholdAction(holder, params.admin, params.tokenThresholdActionParams);
holder.authorize(params.admin, holder.setTokenOut.selector);
holder.authorize(address(this), holder.setTokenOut.selector);
holder.setTokenOut(params.tokenOut);
holder.unauthorize(address(this), holder.setTokenOut.selector);
holder.authorize(params.admin, holder.setMaxSlippage.selector);
holder.authorize(address(this), holder.setMaxSlippage.selector);
holder.setMaxSlippage(params.maxSlippage);
holder.unauthorize(address(this), holder.setMaxSlippage.selector);
Deployer.transferAdminPermissions(holder, params.admin);
smartVault.authorize(address(holder), smartVault.wrap.selector);
smartVault.authorize(address(holder), smartVault.swap.selector);
}
| 17,182,576 | [
1,
1684,
471,
3875,
1301,
1000,
10438,
1147,
596,
1000,
10438,
943,
272,
3169,
2433,
12279,
3981,
4371,
358,
3981,
23859,
1301,
358,
2193,
471,
7720,
628,
19656,
17329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
8401,
6064,
1803,
12,
23824,
12003,
13706,
12003,
16,
670,
1498,
1803,
1370,
3778,
859,
13,
2713,
288,
203,
3639,
670,
1498,
10438,
273,
670,
1498,
12,
2010,
18,
11299,
1769,
203,
3639,
7406,
264,
18,
8401,
2171,
1803,
12,
4505,
16,
859,
18,
3666,
16,
1758,
12,
26416,
12003,
10019,
203,
3639,
1758,
8526,
3778,
1196,
13595,
273,
5647,
18,
2080,
12,
2010,
18,
3666,
16,
859,
18,
29757,
16,
394,
1758,
8526,
12,
20,
10019,
203,
3639,
7406,
264,
18,
8401,
1803,
1905,
13595,
12,
4505,
16,
1196,
13595,
16,
10438,
18,
1991,
18,
9663,
1769,
203,
3639,
7406,
264,
18,
8401,
1345,
7614,
1803,
12,
4505,
16,
859,
18,
3666,
16,
859,
18,
2316,
7614,
1803,
1370,
1769,
203,
203,
3639,
10438,
18,
22488,
12,
2010,
18,
3666,
16,
10438,
18,
542,
1345,
1182,
18,
9663,
1769,
203,
3639,
10438,
18,
22488,
12,
2867,
12,
2211,
3631,
10438,
18,
542,
1345,
1182,
18,
9663,
1769,
203,
3639,
10438,
18,
542,
1345,
1182,
12,
2010,
18,
2316,
1182,
1769,
203,
3639,
10438,
18,
318,
22488,
12,
2867,
12,
2211,
3631,
10438,
18,
542,
1345,
1182,
18,
9663,
1769,
203,
203,
3639,
10438,
18,
22488,
12,
2010,
18,
3666,
16,
10438,
18,
542,
2747,
55,
3169,
2433,
18,
9663,
1769,
203,
3639,
10438,
18,
22488,
12,
2867,
12,
2211,
3631,
10438,
18,
542,
2747,
55,
3169,
2433,
18,
9663,
1769,
203,
3639,
10438,
18,
542,
2747,
55,
3169,
2433,
12,
2010,
18,
1896,
55,
3169,
2433,
1769,
203,
3639,
10438,
2
]
|
./full_match/4/0x68E227C57253D9f375a85163181732364aa6b8fE/sources/browser/Untitled2.sol | * @dev Internal function to mint a new token Reverts if the given token ID already exists @param to The address that will own the minted token @param tokenId uint256 ID of the token to be minted/assigning lucky no and power to tokenId | function _mint(address to, uint256 tokenId, uint256 _userSeed) internal {
require(to != address(0));
require(!_exists(tokenId));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
if(_userSeed > 0 )
{
uint256 _luck = uint256(keccak256(abi.encodePacked(blockhash( block.number -1), _userSeed))) % 99;
uint256 _power = uint256(keccak256(abi.encodePacked(blockhash( block.number -10), _userSeed))) % 99;
powerNLucks[tokenId].luck = _luck;
powerNLucks[tokenId].power = _power;
}
emit Transfer(address(0), to, tokenId);
}
| 12,369,379 | [
1,
3061,
445,
358,
312,
474,
279,
394,
1147,
868,
31537,
309,
326,
864,
1147,
1599,
1818,
1704,
225,
358,
1021,
1758,
716,
903,
4953,
326,
312,
474,
329,
1147,
225,
1147,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
312,
474,
329,
19,
6145,
310,
328,
9031,
93,
1158,
471,
7212,
358,
1147,
548,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
81,
474,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
16,
2254,
5034,
389,
1355,
12702,
13,
2713,
288,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
5,
67,
1808,
12,
2316,
548,
10019,
203,
203,
3639,
389,
2316,
5541,
63,
2316,
548,
65,
273,
358,
31,
203,
3639,
389,
995,
329,
5157,
1380,
63,
869,
8009,
15016,
5621,
203,
203,
540,
203,
3639,
309,
24899,
1355,
12702,
405,
374,
262,
203,
3639,
288,
203,
5411,
2254,
5034,
389,
80,
9031,
273,
2254,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2629,
2816,
12,
1203,
18,
2696,
300,
21,
3631,
389,
1355,
12702,
20349,
738,
14605,
31,
203,
5411,
2254,
5034,
389,
12238,
273,
2254,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2629,
2816,
12,
1203,
18,
2696,
300,
2163,
3631,
389,
1355,
12702,
20349,
738,
14605,
31,
203,
5411,
7212,
24924,
9031,
87,
63,
2316,
548,
8009,
80,
9031,
273,
389,
80,
9031,
31,
203,
5411,
7212,
24924,
9031,
87,
63,
2316,
548,
8009,
12238,
273,
389,
12238,
31,
2398,
203,
3639,
289,
203,
540,
203,
203,
203,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.3;
import { VerifyVDF } from "./VerifyVDF.sol";
contract Test is VerifyVDF {
function testValidateGroupElement(bytes memory e) external pure returns (bool) {
return validateGroupElement(e);
}
function testIsZeroGroupElement(bytes memory e) external pure returns (bool) {
return isZeroGroupElement(e);
}
function testEqualNumber(bytes memory a, bytes memory b) external pure returns (bool) {
return equalNumber(a, b);
}
function testHashToPrime(
bytes memory g,
bytes memory y,
uint256 nonce,
bytes memory dst
) external pure returns (uint256) {
return hashToPrime(g, y, nonce, dst);
}
// solhint-disable-next-line
function gasCostVerify(
bytes memory g,
bytes memory pi,
bytes memory y,
bytes memory q,
bytes memory dst,
uint256 nonce,
uint256 delay
) external returns (uint256) {
uint256 operationGasCost = gasleft();
verify(g, pi, y, q, dst, nonce, delay);
return operationGasCost - gasleft();
}
function gasCostMillerRabinPrimalityTest(uint256 n) external view returns (uint256) {
uint256 operationGasCost = gasleft();
require(millerRabinPrimalityTest(n), "run it with a prime");
return operationGasCost - gasleft();
}
// solhint-disable-next-line
function gasCostEqualNumber(bytes memory a, bytes memory b) external returns (uint256) {
uint256 operationGasCost = gasleft();
equalNumber(a, b);
return operationGasCost - gasleft();
}
function testMulModEqual(
bytes memory a,
bytes memory b,
bytes memory y,
bytes memory q
) external view returns (bool) {
return mulModEqual(a, b, y, q);
}
// solhint-disable-next-line
function gasCostMulModEqual(
bytes memory a,
bytes memory b,
bytes memory y,
bytes memory q
) external returns (uint256) {
uint256 operationGasCost = gasleft();
mulModEqual(a, b, y, q);
return operationGasCost - gasleft();
}
function testAdd2048to4096(bytes memory a, bytes memory b) external pure returns (bytes memory) {
add2048to4096(a, b);
return a;
}
// solhint-disable-next-line
function gasCostAdd2048to4096(bytes memory a, bytes memory b) external returns (uint256) {
uint256 operationGasCost = gasleft();
add2048to4096(a, b);
return operationGasCost - gasleft();
}
function testMul2048(bytes memory a, bytes memory b) external pure returns (bytes memory) {
return mul2048(a, b);
}
// solhint-disable-next-line
function gasCostMul2048(bytes memory a, bytes memory b) external returns (uint256) {
uint256 operationGasCost = gasleft();
mul2048(a, b);
return operationGasCost - gasleft();
}
function testModExp(bytes memory base, uint256 exponent) external view returns (bytes memory) {
return modexp(base, exponent);
}
// solhint-disable-next-line
function gasCostModExp(bytes memory base, uint256 exponent) external returns (uint256) {
uint256 operationGasCost = gasleft();
modexp(base, exponent);
return operationGasCost - gasleft();
}
function testModExp256(
uint256 base,
uint256 exponent,
uint256 modulus
) external view returns (uint256) {
return modexp(base, exponent, modulus);
}
// solhint-disable-next-line
function gasCostModExp256(
uint256 base,
uint256 exponent,
uint256 modulus
) external returns (uint256) {
uint256 operationGasCost = gasleft();
modexp(base, exponent, modulus);
return operationGasCost - gasleft();
}
}
| solhint-disable-next-line | function gasCostModExp(bytes memory base, uint256 exponent) external returns (uint256) {
uint256 operationGasCost = gasleft();
modexp(base, exponent);
return operationGasCost - gasleft();
}
| 5,366,706 | [
1,
18281,
11317,
17,
8394,
17,
4285,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16189,
8018,
1739,
2966,
12,
3890,
3778,
1026,
16,
2254,
5034,
9100,
13,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
1674,
27998,
8018,
273,
16189,
4482,
5621,
203,
565,
1965,
23829,
12,
1969,
16,
9100,
1769,
203,
565,
327,
1674,
27998,
8018,
300,
16189,
4482,
5621,
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
]
|
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./interfaces/IHNDGame.sol";
import "./interfaces/IHND.sol";
import "./interfaces/IEXP.sol";
import "./interfaces/IKingdom.sol";
contract Kingdom is IKingdom, Ownable, ReentrancyGuard, IERC721Receiver, Pausable {
// maximum rank for a Hero/Demon
uint8 public constant MAX_RANK = 8;
// struct to store a stake's token, owner, and earning values
struct Stake {
uint16 tokenId;
uint80 value;
address owner;
}
uint256 private totalRankStaked;
uint256 private numHeroesStaked;
event TokenStaked(address indexed owner, uint256 indexed tokenId, bool indexed isHero, uint256 value);
event HeroClaimed(uint256 indexed tokenId, bool indexed unstaked, uint256 earned);
event DemonClaimed(uint256 indexed tokenId, bool indexed unstaked, uint256 earned);
// reference to the HND NFT contract
IHND public HNDNFT;
// reference to the HND NFT contract
IHNDGame public HNDGame;
// reference to the $EXP contract for minting $EXP earnings
IEXP public expToken;
// maps tokenId to stake
mapping(uint256 => Stake) private kingdom;
// maps rank to all Demon staked with that rank
mapping(uint256 => Stake[]) private army;
// tracks location of each Demon in Army
mapping(uint256 => uint256) private armyIndices;
// any rewards distributed when no demons are staked
mapping(address => uint256[]) public stakedTokenOwners;
//holds mapping of their position in stakedTokenOwners
mapping(uint256 => uint256) private stakedTokenIndex;
uint256 private unaccountedRewards = 0;
// amount of $EXP due for each rank point staked
uint256 private expPerRank = 0;
// heroes earn 10000 $EXP per day
uint256 public constant DAILY_EXP_RATE = 10000 ether;
// heroes must have 2 days worth of $EXP to unstake or else they're still guarding the Kingdom
uint256 public constant MINIMUM_TO_EXIT = 2 days;
// demons take a 20% tax on all $EXP claimed
uint256 public constant EXP_CLAIM_TAX_PERCENTAGE = 20;
// when heroes are leaving demons have 50% chance to take 50% of their earned $EXP instead of 20%
uint256 public constant EXP_STOLEN_DENOMINATOR = 2;
// 10,000,000,000 $EXP used and cycled through during combat
uint256 public constant MAXIMUM_GLOBAL_EXP = 10000000000 ether;
// $EXP that has been dispensed from the faucet during combat
uint256 public expFromFaucet;
// the last time $EXP was claimed
uint256 private lastClaimTimestamp;
// emergency rescue to allow unstaking without any checks but without $EXP
bool public rescueEnabled = false;
mapping(address => bool) private admins;
/**
*/
constructor() {
_pause();
}
/** CRITICAL TO SETUP */
modifier requireContractsSet() {
require(address(HNDNFT) != address(0) && address(expToken) != address(0)
&& address(HNDGame) != address(0), "Contracts not set");
_;
}
function setContracts(address _HNDNFT, address _exp, address _HNDGame) external onlyOwner {
HNDNFT = IHND(_HNDNFT);
expToken = IEXP(_exp);
HNDGame = IHNDGame(_HNDGame);
}
/** STAKING */
/**
* adds Heros and Demons to the Kingdom and Army
* @param account the address of the staker
* @param tokenIds the IDs of the Heros and Demons to stake
*/
function addManyToKingdom(address account, uint16[] calldata tokenIds) external override nonReentrant {
require(tx.origin == _msgSender() || _msgSender() == address(HNDGame), "Only EOA");
require(account == tx.origin, "account to sender mismatch");
for (uint i = 0; i < tokenIds.length; i++) {
if (_msgSender() != address(HNDGame)) { // dont do this step if its a mint + stake
require(HNDNFT.ownerOf(tokenIds[i]) == _msgSender(), "You don't own this token");
HNDNFT.transferFrom(_msgSender(), address(this), tokenIds[i]);
} else if (tokenIds[i] == 0) {
continue; // there may be gaps in the array for stolen tokens
}
if (HNDNFT.isHero(tokenIds[i]))
_addHeroToKingdom(account, tokenIds[i]);
else
_addDemonToArmy(account, tokenIds[i]);
}
}
/**
* adds a single Hero to the Kingdom
* @param account the address of the staker
* @param tokenId the ID of the Hero to add to the Kingdom
*/
function _addHeroToKingdom(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {
kingdom[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
stakedTokenIndex[tokenId] = stakedTokenOwners[account].length;
stakedTokenOwners[account].push(tokenId);
numHeroesStaked += 1;
emit TokenStaked(account, tokenId, true, block.timestamp);
}
/**
* adds a single Demon to the Army
* @param account the address of the staker
* @param tokenId the ID of the Demon to add to the Army
*/
function _addDemonToArmy(address account, uint256 tokenId) internal {
uint8 rank = _rankForDemon(tokenId);
totalRankStaked += rank; // Portion of earnings ranges from 8 to 5
armyIndices[tokenId] = army[rank].length; // Store the location of the demon in the Army
army[rank].push(Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(expPerRank)
})); // Add the demon to the Army
stakedTokenIndex[tokenId] = stakedTokenOwners[account].length;
stakedTokenOwners[account].push(tokenId);
emit TokenStaked(account, tokenId, false, expPerRank);
}
/** CLAIMING / UNSTAKING */
/**
* realize $EXP earnings and optionally unstake tokens from the Kingdom
* to unstake a Hero it will require it has 2 days worth of $EXP unclaimed
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
*/
function claimManyFromKingdom(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings nonReentrant {
require(tx.origin == _msgSender() || _msgSender() == address(HNDGame), "Only EOA");
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (HNDNFT.isHero(tokenIds[i])) {
owed += _claimHeroFromKingdom(tokenIds[i], unstake);
}
else {
owed += _claimDemonFromArmy(tokenIds[i], unstake);
}
}
expToken.updateOriginAccess();
if (owed == 0) {
return;
}
expToken.mint(_msgSender(), owed);
}
function calculateRewards(uint256 tokenId) external view returns (uint256 owed) {
uint64 lastTokenWrite = HNDNFT.getTokenWriteBlock(tokenId);
// Must check this, as getTokenTraits will be allowed since this contract is an admin
require(lastTokenWrite < block.number, "hmmmm what doing?");
Stake memory stake = kingdom[tokenId];
if(HNDNFT.isHero(tokenId)) {
if (expFromFaucet < MAXIMUM_GLOBAL_EXP) {
owed = (block.timestamp - stake.value) * DAILY_EXP_RATE / 1 days;
} else if (stake.value > lastClaimTimestamp) {
owed = 0; // $EXP production stopped already
} else {
owed = (lastClaimTimestamp - stake.value) * DAILY_EXP_RATE / 1 days; // stop earning additional $EXP if it's all been earned
}
}
else {
uint8 rank = _rankForDemon(tokenId);
owed = (rank) * (expPerRank - stake.value); // Calculate portion of tokens based on Rank
}
}
/**
* realize $EXP earnings for a single Hero and optionally unstake it
* if not unstaking, pay a 20% tax to the staked Demons
* if unstaking, there is a 50% chance all $EXP is stolen
* @param tokenId the ID of the Heros to claim earnings from
* @param unstake whether or not to unstake the Heros
* @return owed - the amount of $EXP earned
*/
function _claimHeroFromKingdom(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(HNDNFT.ownerOf(tokenId) == address(this), "Kingdom: Claiming unstaked hero!");
Stake memory stake = kingdom[tokenId];
require(stake.owner == _msgSender(), "Kingdom: Claiming unowned hero!");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "Kingdom: Hero is still guarding!");
if (expFromFaucet < MAXIMUM_GLOBAL_EXP) {
owed = (block.timestamp - stake.value) * DAILY_EXP_RATE / 1 days;
} else if (stake.value > lastClaimTimestamp) {
owed = 0; // $EXP production stopped already
} else {
owed = (lastClaimTimestamp - stake.value) * DAILY_EXP_RATE / 1 days; // stop earning additional $EXP if it's all been earned
}
if (unstake) {
// 50% chance of half $EXP being stolen
if (uint256(keccak256(abi.encode(blockhash(block.number-1), _msgSender(), tokenId))) % 2 == 1) {
//steal half of $EXP accumulated
_payDemonTax(owed/EXP_STOLEN_DENOMINATOR);
// keep half the $EXP
owed = (owed/EXP_STOLEN_DENOMINATOR);
}
delete kingdom[tokenId];
delete stakedTokenOwners[_msgSender()][stakedTokenIndex[tokenId]];
stakedTokenIndex[tokenId] = 0;
numHeroesStaked -= 1;
HNDNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Hero
} else {
_payDemonTax(owed * EXP_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked demons
// send leftover
owed = owed * (100 - EXP_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Hero owner
// reset their stake
kingdom[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
}
emit HeroClaimed(tokenId, unstake, owed);
}
/**
* realize $EXP earnings for a single Demon and optionally unstake it
* Demons earn $EXP proportional to their rank
* @param tokenId the ID of the Demon to claim earnings from
* @param unstake whether or not to unstake the Demon
* @return owed the amount of $EXP earned
*/
function _claimDemonFromArmy(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(HNDNFT.ownerOf(tokenId) == address(this), "Kingdom: Claiming unstaked demon!");
uint8 rank = _rankForDemon(tokenId);
Stake memory stake = army[rank][armyIndices[tokenId]];
require(stake.owner == _msgSender(), "Kingdom: Claiming unowned demon!");
owed = (rank) * (expPerRank - stake.value); // Calculate portion of tokens based on Rank
if (unstake) {
totalRankStaked -= rank; // Remove rank from total staked
Stake memory lastStake = army[rank][army[rank].length - 1];
army[rank][armyIndices[tokenId]] = lastStake; // Shuffle last Demon to current position
armyIndices[lastStake.tokenId] = armyIndices[tokenId];
army[rank].pop(); // Remove duplicate
delete armyIndices[tokenId]; // Delete old mapping
delete stakedTokenOwners[_msgSender()][stakedTokenIndex[tokenId]];
stakedTokenIndex[tokenId] = 0;
// Always remove last to guard against reentrance
HNDNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Demon
} else {
// we reset their stake
army[rank][armyIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(expPerRank)
});
}
emit DemonClaimed(tokenId, unstake, owed);
}
/**
* emergency unstake tokens
* @param tokenIds the IDs of the tokens to claim earnings from
*/
function rescue(uint256[] calldata tokenIds) external nonReentrant {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint8 rank;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (HNDNFT.isHero(tokenId)) {
stake = kingdom[tokenId];
require(stake.owner == _msgSender(), "must own token");
delete kingdom[tokenId];
numHeroesStaked -= 1;
HNDNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Heros
emit HeroClaimed(tokenId, true, 0);
} else {
rank = _rankForDemon(tokenId);
stake = army[rank][armyIndices[tokenId]];
require(stake.owner == _msgSender(), "must own token");
totalRankStaked -= rank; // Remove Rank from total staked
lastStake = army[rank][army[rank].length - 1];
army[rank][armyIndices[tokenId]] = lastStake; // Shuffle last Demon to current position
armyIndices[lastStake.tokenId] = armyIndices[tokenId];
army[rank].pop(); // Remove duplicate
delete armyIndices[tokenId]; // Delete old mapping
HNDNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Demon
emit DemonClaimed(tokenId, true, 0);
}
}
}
/** ACCOUNTING */
/**
* add $EXP to claimable pot for the Army
* @param amount $EXP to add to the pot
*/
function _payDemonTax(uint256 amount) internal {
if (totalRankStaked == 0) { // if there's no staked demons
unaccountedRewards += amount; // keep track of $EXP due to demons
return;
}
// makes sure to include any unaccounted $EXP
expPerRank += (amount + unaccountedRewards) / totalRankStaked;
unaccountedRewards = 0;
}
/**
* add $EXP to claimable pot for the Army
* @param amount $EXP to add to the pot
*/
function recycleExp(uint256 amount) override external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
expFromFaucet -= amount;
}
/**
* tracks $EXP earnings to ensure it stops once 10 billion is eclipsed
*/
modifier _updateEarnings() {
if (expFromFaucet < MAXIMUM_GLOBAL_EXP) {
expFromFaucet +=
(block.timestamp - lastClaimTimestamp)
* numHeroesStaked
* DAILY_EXP_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
/** ADMIN */
/**
* allows owner to enable "rescue mode"
* simplifies accounting, prioritizes tokens out in emergency
*/
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
/**
* enables owner to pause / unpause contract
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** READ ONLY */
/**
* gets the rank score for a Demon
* @param tokenId the ID of the Demon to get the rank score for
* @return the rank score of the Demon (5-8)
*/
function _rankForDemon(uint256 tokenId) internal view returns (uint8) {
IHND.HeroDemon memory s = HNDNFT.getTokenTraits(tokenId);
return MAX_RANK - s.rankIndex; // rank index is 0-3
}
/**
* chooses a random Demon thief when a newly minted token is stolen
* @param seed a random value to choose a Demon from
* @return the owner of the randomly selected Demon thief
*/
function randomDemonOwner(uint256 seed) external view override returns (address) {
if (totalRankStaked == 0) {
return address(0x0);
}
uint256 bucket = (seed & 0xFFFFFFFF) % totalRankStaked; // choose a value from 0 to total rank staked
uint256 cumulative;
seed >>= 32;
// loop through each bucket of Demons with the same rank score
for (uint i = MAX_RANK - 3; i <= MAX_RANK; i++) {
cumulative += army[i].length * i;
// if the value is not inside of that bucket, keep going
if (bucket >= cumulative) continue;
// get the address of a random Demon with that rank score
return army[i][seed % army[i].length].owner;
}
return address(0x0);
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send to Kingdom directly");
return IERC721Receiver.onERC721Received.selector;
}
/**
* enables an address to mint / burn
* @param addr the address to enable
*/
function addAdmin(address addr) external onlyOwner {
admins[addr] = true;
}
/**
* disables an address from minting / burning
* @param addr the address to disbale
*/
function removeAdmin(address addr) external onlyOwner {
admins[addr] = false;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IKingdom {
function addManyToKingdom(address account, uint16[] calldata tokenIds) external;
function randomDemonOwner(uint256 seed) external view returns (address);
function recycleExp(uint256 amount) external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IEXP {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function updateOriginAccess() external;
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IHND is IERC721Enumerable {
// game data storage
struct HeroDemon {
bool isHero;
bool isFemale;
uint8 body;
uint8 face;
uint8 eyes;
uint8 headpiecehorns;
uint8 gloves;
uint8 armor;
uint8 weapon;
uint8 shield;
uint8 shoes;
uint8 tailflame;
uint8 rankIndex;
}
function minted() external returns (uint16);
function updateOriginAccess(uint16[] memory tokenIds) external;
function mint(address recipient, uint256 seed) external;
function burn(uint256 tokenId) external;
function getMaxTokens() external view returns (uint256);
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (HeroDemon memory);
function getTokenWriteBlock(uint256 tokenId) external view returns(uint64);
function isHero(uint256 tokenId) external view returns(bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IHNDGame {
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 (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/extensions/IERC721Enumerable.sol)
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
// 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 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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);
} | Shuffle last Demon to current position
| army[rank][armyIndices[tokenId]] = lastStake; | 1,476,061 | [
1,
1555,
10148,
1142,
463,
4758,
358,
783,
1754,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1377,
419,
4811,
63,
11500,
6362,
4610,
93,
8776,
63,
2316,
548,
13563,
273,
1142,
510,
911,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "./libraries/math/WadRayMath.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "hardhat/console.sol";
contract UsdPlusToken is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, AccessControlUpgradeable, UUPSUpgradeable {
using WadRayMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
// --- ERC20 fields
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// --- fields
bytes32 public constant EXCHANGER = keccak256("EXCHANGER");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
uint256 private _totalMint;
uint256 private _totalBurn;
uint256 public liquidityIndexChangeTime;
uint256 public liquidityIndex;
uint256 public liquidityIndexDenominator;
EnumerableSet.AddressSet _owners;
// --- events
event ExchangerUpdated(address exchanger);
event LiquidityIndexUpdated(uint256 changeTime, uint256 liquidityIndex);
// --- modifiers
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Restricted to admins");
_;
}
modifier onlyExchanger() {
require(hasRole(EXCHANGER, msg.sender), "Caller is not the EXCHANGER");
_;
}
// --- setters
function setExchanger(address _exchanger) external onlyAdmin {
grantRole(EXCHANGER, _exchanger);
emit ExchangerUpdated(_exchanger);
}
function setLiquidityIndex(uint256 _liquidityIndex) external onlyExchanger {
require(_liquidityIndex > 0, "Zero liquidity index not allowed");
liquidityIndex = _liquidityIndex;
liquidityIndexChangeTime = block.timestamp;
emit LiquidityIndexUpdated(liquidityIndexChangeTime, liquidityIndex);
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__Context_init_unchained();
_name = "USD+";
_symbol = "USD+";
__AccessControl_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(UPGRADER_ROLE, msg.sender);
liquidityIndex = 10 ** 27; // as Ray
liquidityIndexDenominator = 10 ** 27; // Ray
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
// --- logic
function mint(address _sender, uint256 _amount) external onlyExchanger {
// up to ray
uint256 mintAmount = _amount.wadToRay();
mintAmount = mintAmount.rayDiv(liquidityIndex);
_mint(_sender, mintAmount);
_totalMint += mintAmount;
emit Transfer(address(0), _sender, _amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
_afterTokenTransfer(address(0), account, amount);
}
function burn(address _sender, uint256 _amount) external onlyExchanger {
// up to ray
uint256 burnAmount = _amount.wadToRay();
burnAmount = burnAmount.rayDiv(liquidityIndex);
_burn(_sender, burnAmount);
_totalBurn += burnAmount;
emit Transfer(_sender, address(0), _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 {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
_afterTokenTransfer(sender, recipient, amount);
}
/**
* @dev See {IERC20-transfer}.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
// up to ray
uint256 transferAmount = amount.wadToRay();
transferAmount = transferAmount.rayDiv(liquidityIndex);
_transfer(_msgSender(), recipient, transferAmount);
emit Transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view override returns (uint256) {
uint256 allowanceRay = _allowance(owner, spender).rayMul(liquidityIndex);
// ray -> wad
return allowanceRay.rayToWad();
}
/**
* @dev See {IERC20-allowance}.
*/
function _allowance(address owner, address spender) internal view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*/
function approve(address spender, uint256 amount) external override returns (bool){
// up to ray
uint256 scaledAmount = amount.wadToRay();
scaledAmount = scaledAmount.rayDiv(liquidityIndex);
_approve(_msgSender(), spender, scaledAmount);
return true;
}
/**
* @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);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
// up to ray
uint256 scaledAmount = amount.wadToRay();
scaledAmount = scaledAmount.rayDiv(liquidityIndex);
_transfer(sender, recipient, scaledAmount);
uint256 currentAllowance = _allowance(sender, _msgSender());
require(currentAllowance >= scaledAmount, "UsdPlusToken: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - scaledAmount);
}
emit Transfer(sender, recipient, amount);
return true;
}
/**
* @dev Calculates the balance of the user: principal balance + interest generated by the principal
* @param user The user whose balance is calculated
* @return The balance of the user
**/
function balanceOf(address user)
public
view
override
returns (uint256)
{
// stored balance is ray (27)
uint256 balanceInMapping = _balanceOf(user);
// ray -> ray
uint256 balanceRay = balanceInMapping.rayMul(liquidityIndex);
// ray -> wad
return balanceRay.rayToWad();
}
/**
* @dev See {IERC20-balanceOf}.
*/
function _balanceOf(address account) internal view returns (uint256) {
return _balances[account];
}
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256) {
return _balanceOf(user);
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view override returns (uint256) {
// stored totalSupply is ray (27)
uint256 currentSupply = _totalSupply;
// ray -> ray
uint256 currentSupplyRay = currentSupply.rayMul(liquidityIndex);
// ray -> wad
return currentSupplyRay.rayToWad();
}
function totalMint() external view returns (uint256) {
uint256 totalMintRay = _totalMint.rayMul(liquidityIndex);
return totalMintRay.rayToWad();
}
function totalBurn() external view returns (uint256) {
uint256 totalBurnRay = _totalBurn.rayMul(liquidityIndex);
return totalBurnRay.rayToWad();
}
/**
* @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(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Returns the scaled total supply of the variable debt token
* @return the scaled total supply
**/
function scaledTotalSupply() public view returns (uint256) {
return _totalSupply;
}
function ownerLength() external view returns (uint256) {
return _owners.length();
}
function ownerAt(uint256 index) external view returns (address) {
return _owners.at(index);
}
function ownerBalanceAt(uint256 index) external view returns (uint256) {
return balanceOf(_owners.at(index));
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public pure override returns (uint8) {
return 6;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal {
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal {
if (from == address(0)) {
// mint
_owners.add(to);
} else if (to == address(0)) {
// burn
if (balanceOf(from) == 0) {
_owners.remove(from);
}
} else {
// transfer
if (balanceOf(from) == 0) {
_owners.remove(from);
}
_owners.add(to);
}
}
uint256[50] private __gap;
}
| * @dev Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `account` cannot be the zero address./ | function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
_afterTokenTransfer(address(0), account, amount);
}
| 15,853,187 | [
1,
2729,
1375,
8949,
68,
2430,
471,
22698,
2182,
358,
1375,
4631,
9191,
21006,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
2080,
68,
444,
358,
326,
3634,
1758,
18,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
81,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
225,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
203,
3639,
389,
4963,
3088,
1283,
1011,
3844,
31,
203,
3639,
389,
70,
26488,
63,
4631,
65,
1011,
3844,
31,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.13;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../common/FixidityLib.sol";
import "../common/Initializable.sol";
import "../common/UsingRegistry.sol";
import "../common/interfaces/ICeloVersionedContract.sol";
import "../common/libraries/ReentrancyGuard.sol";
import "../stability/interfaces/IStableToken.sol";
/**
* @title Facilitates large exchanges between CELO stable tokens.
*/
contract GrandaMento is
ICeloVersionedContract,
Ownable,
Initializable,
UsingRegistry,
ReentrancyGuard
{
using FixidityLib for FixidityLib.Fraction;
using SafeMath for uint256;
// Emitted when a new exchange proposal is created.
event ExchangeProposalCreated(
uint256 indexed proposalId,
address indexed exchanger,
string stableTokenRegistryId,
uint256 sellAmount,
uint256 buyAmount,
bool sellCelo
);
// Emitted when an exchange proposal is approved by the approver.
event ExchangeProposalApproved(uint256 indexed proposalId);
// Emitted when an exchange proposal is cancelled.
event ExchangeProposalCancelled(uint256 indexed proposalId);
// Emitted when an exchange proposal is executed.
event ExchangeProposalExecuted(uint256 indexed proposalId);
// Emitted when the approver is set.
event ApproverSet(address approver);
// Emitted when maxApprovalExchangeRateChange is set.
event MaxApprovalExchangeRateChangeSet(uint256 maxApprovalExchangeRateChange);
// Emitted when the spread is set.
event SpreadSet(uint256 spread);
// Emitted when the veto period in seconds is set.
event VetoPeriodSecondsSet(uint256 vetoPeriodSeconds);
// Emitted when the exchange limits for a stable token are set.
event StableTokenExchangeLimitsSet(
string stableTokenRegistryId,
uint256 minExchangeAmount,
uint256 maxExchangeAmount
);
enum ExchangeProposalState { None, Proposed, Approved, Executed, Cancelled }
struct ExchangeLimits {
// The minimum amount of an asset that can be exchanged in a single proposal.
uint256 minExchangeAmount;
// The maximum amount of an asset that can be exchanged in a single proposal.
uint256 maxExchangeAmount;
}
struct ExchangeProposal {
// The exchanger/proposer of the exchange proposal.
address payable exchanger;
// The stable token involved in this proposal. This is stored rather than
// the stable token's registry ID in case the contract address is changed
// after a proposal is created, which could affect refunding or burning the
// stable token.
address stableToken;
// The state of the exchange proposal.
ExchangeProposalState state;
// Whether the exchanger is selling CELO and buying stableToken.
bool sellCelo;
// The amount of the sell token being sold. If a stable token is being sold,
// the amount of stable token in "units" is stored rather than the "value."
// This is because stable tokens may experience demurrage/inflation, where
// the amount of stable token "units" doesn't change with time, but the "value"
// does. This is important to ensure the correct inflation-adjusted amount
// of the stable token is transferred out of this contract when a deposit is
// refunded or an exchange selling the stable token is executed.
// See StableToken.sol for more details on what "units" vs "values" are.
uint256 sellAmount;
// The amount of the buy token being bought. For stable tokens, this is
// kept track of as the value, not units.
uint256 buyAmount;
// The price of CELO quoted in stableToken at the time of the exchange proposal
// creation. This is the price used to calculate the buyAmount. Used for a
// safety check when an approval is being made that the price isn't wildly
// different. Recalculating buyAmount is not sufficient because if a stable token
// is being sold that has demurrage enabled, the original value when the stable
// tokens were deposited cannot be calculated.
uint256 celoStableTokenExchangeRate;
// The veto period in seconds at the time the proposal was created. This is kept
// track of on a per-proposal basis to lock-in the veto period for a proposal so
// that changes to the contract's vetoPeriodSeconds do not affect existing
// proposals.
uint256 vetoPeriodSeconds;
// The timestamp (`block.timestamp`) at which the exchange proposal was approved
// in seconds. If the exchange proposal has not ever been approved, is 0.
uint256 approvalTimestamp;
}
// The address with the authority to approve exchange proposals.
address public approver;
// The maximum allowed change in the CELO/stable token price when an exchange proposal
// is being approved relative to the rate when the exchange proposal was created.
FixidityLib.Fraction public maxApprovalExchangeRateChange;
// The percent fee imposed upon an exchange execution.
FixidityLib.Fraction public spread;
// The period in seconds after an approval during which an exchange proposal can be vetoed.
uint256 public vetoPeriodSeconds;
// The minimum and maximum amount of the stable token that can be minted or
// burned in a single exchange. Indexed by the stable token registry identifier string.
mapping(string => ExchangeLimits) public stableTokenExchangeLimits;
// State for all exchange proposals. Indexed by the exchange proposal ID.
mapping(uint256 => ExchangeProposal) public exchangeProposals;
// An array containing a superset of the IDs of exchange proposals that are currently
// in the Proposed or Approved state. Intended to allow easy viewing of all active
// exchange proposals. It's possible for a proposal ID in this array to no longer be
// active, so filtering is required to find the true set of active proposal IDs.
// A superset is kept because exchange proposal vetoes, intended to be done
// by Governance, effectively go through a multi-day timelock. If the veto
// call was required to provide the index in an array of activeProposalIds to
// remove corresponding to the vetoed exchange proposal, the timelock could result
// in the provided index being stale by the time the veto would be executed.
// Alternative approaches exist, like maintaining a linkedlist of active proposal
// IDs, but this approach was chosen for its low implementation complexity.
uint256[] public activeProposalIdsSuperset;
// Number of exchange proposals that have ever been created. Used for assigning
// an exchange proposal ID to a new proposal.
uint256 public exchangeProposalCount;
/**
* @notice Reverts if the sender is not the approver.
*/
modifier onlyApprover() {
require(msg.sender == approver, "Sender must be approver");
_;
}
/**
* @notice Sets initialized == true on implementation contracts.
* @param test Set to true to skip implementation initialization.
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 0, 0);
}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param _registry The address of the registry.
* @param _approver The approver that has the ability to approve exchange proposals.
* @param _maxApprovalExchangeRateChange The maximum allowed change in CELO price
* between an exchange proposal's creation and approval.
* @param _spread The spread charged on exchanges.
* @param _vetoPeriodSeconds The length of the veto period in seconds.
*/
function initialize(
address _registry,
address _approver,
uint256 _maxApprovalExchangeRateChange,
uint256 _spread,
uint256 _vetoPeriodSeconds
) external initializer {
_transferOwnership(msg.sender);
setRegistry(_registry);
setApprover(_approver);
setMaxApprovalExchangeRateChange(_maxApprovalExchangeRateChange);
setSpread(_spread);
setVetoPeriodSeconds(_vetoPeriodSeconds);
}
/**
* @notice Creates a new exchange proposal and deposits the tokens being sold.
* @dev Stable token value amounts are used for the sellAmount, not unit amounts.
* @param stableTokenRegistryId The string registry ID for the stable token
* involved in the exchange.
* @param sellAmount The amount of the sell token being sold.
* @param sellCelo Whether CELO is being sold.
* @return The proposal identifier for the newly created exchange proposal.
*/
function createExchangeProposal(
string calldata stableTokenRegistryId,
uint256 sellAmount,
bool sellCelo
) external nonReentrant returns (uint256) {
address stableToken = registry.getAddressForStringOrDie(stableTokenRegistryId);
// Gets the price of CELO quoted in stableToken.
uint256 celoStableTokenExchangeRate = getOracleExchangeRate(stableToken).unwrap();
// Using the current oracle exchange rate, calculate what the buy amount is.
// This takes the spread into consideration.
uint256 buyAmount = getBuyAmount(celoStableTokenExchangeRate, sellAmount, sellCelo);
// Create new scope to prevent a stack too deep error.
{
// Get the minimum and maximum amount of stable token than can be involved
// in the exchange. This reverts if exchange limits for the stable token have
// not been set.
(uint256 minExchangeAmount, uint256 maxExchangeAmount) = getStableTokenExchangeLimits(
stableTokenRegistryId
);
// Ensure that the amount of stableToken being bought or sold is within
// the configurable exchange limits.
uint256 stableTokenExchangeAmount = sellCelo ? buyAmount : sellAmount;
require(
stableTokenExchangeAmount <= maxExchangeAmount &&
stableTokenExchangeAmount >= minExchangeAmount,
"Stable token exchange amount not within limits"
);
}
// Deposit the assets being sold.
IERC20 sellToken = sellCelo ? getGoldToken() : IERC20(stableToken);
require(
sellToken.transferFrom(msg.sender, address(this), sellAmount),
"Transfer in of sell token failed"
);
// Record the proposal.
// Add 1 to the running proposal count, and use the updated proposal count as
// the proposal ID. Proposal IDs intentionally start at 1.
exchangeProposalCount = exchangeProposalCount.add(1);
// For stable tokens, the amount is stored in units to deal with demurrage.
uint256 storedSellAmount = sellCelo
? sellAmount
: IStableToken(stableToken).valueToUnits(sellAmount);
exchangeProposals[exchangeProposalCount] = ExchangeProposal({
exchanger: msg.sender,
stableToken: stableToken,
state: ExchangeProposalState.Proposed,
sellCelo: sellCelo,
sellAmount: storedSellAmount,
buyAmount: buyAmount,
celoStableTokenExchangeRate: celoStableTokenExchangeRate,
vetoPeriodSeconds: vetoPeriodSeconds,
approvalTimestamp: 0 // initial value when not approved yet
});
// StableToken.unitsToValue (called within getSellTokenAndSellAmount) can
// overflow for very large StableToken amounts. Call it here as a sanity
// check, so that the overflow happens here, blocking proposal creation
// rather than when attempting to execute the proposal, which would lock
// funds in this contract.
getSellTokenAndSellAmount(exchangeProposals[exchangeProposalCount]);
// Push it into the array of active proposals.
activeProposalIdsSuperset.push(exchangeProposalCount);
// Even if stable tokens are being sold, the sellAmount emitted is the "value."
emit ExchangeProposalCreated(
exchangeProposalCount,
msg.sender,
stableTokenRegistryId,
sellAmount,
buyAmount,
sellCelo
);
return exchangeProposalCount;
}
/**
* @notice Approves an existing exchange proposal.
* @dev Sender must be the approver. Exchange proposal must be in the Proposed state.
* @param proposalId The identifier of the proposal to approve.
*/
function approveExchangeProposal(uint256 proposalId) external nonReentrant onlyApprover {
ExchangeProposal storage proposal = exchangeProposals[proposalId];
// Ensure the proposal is in the Proposed state.
require(proposal.state == ExchangeProposalState.Proposed, "Proposal must be in Proposed state");
// Ensure the change in the current price of CELO quoted in the stable token
// relative to the value when the proposal was created is within the allowed limit.
FixidityLib.Fraction memory currentRate = getOracleExchangeRate(proposal.stableToken);
FixidityLib.Fraction memory proposalRate = FixidityLib.wrap(
proposal.celoStableTokenExchangeRate
);
(FixidityLib.Fraction memory lesserRate, FixidityLib.Fraction memory greaterRate) = currentRate
.lt(proposalRate)
? (currentRate, proposalRate)
: (proposalRate, currentRate);
FixidityLib.Fraction memory rateChange = greaterRate.subtract(lesserRate).divide(proposalRate);
require(
rateChange.lte(maxApprovalExchangeRateChange),
"CELO exchange rate is too different from the proposed price"
);
// Set the time the approval occurred and change the state.
proposal.approvalTimestamp = block.timestamp;
proposal.state = ExchangeProposalState.Approved;
emit ExchangeProposalApproved(proposalId);
}
/**
* @notice Cancels an exchange proposal.
* @dev Only callable by the exchanger if the proposal is in the Proposed state
* or the owner if the proposal is in the Approved state.
* @param proposalId The identifier of the proposal to cancel.
*/
function cancelExchangeProposal(uint256 proposalId) external nonReentrant {
ExchangeProposal storage proposal = exchangeProposals[proposalId];
// Require the appropriate state and sender.
// This will also revert if a proposalId is given that does not correspond
// to a previously created exchange proposal.
if (proposal.state == ExchangeProposalState.Proposed) {
require(proposal.exchanger == msg.sender, "Sender must be exchanger");
} else if (proposal.state == ExchangeProposalState.Approved) {
require(isOwner(), "Sender must be owner");
} else {
revert("Proposal must be in Proposed or Approved state");
}
// Mark the proposal as cancelled. Do so prior to refunding as a measure against reentrancy.
proposal.state = ExchangeProposalState.Cancelled;
// Get the token and amount that will be refunded to the proposer.
(IERC20 refundToken, uint256 refundAmount) = getSellTokenAndSellAmount(proposal);
// Finally, transfer out the deposited funds.
require(
refundToken.transfer(proposal.exchanger, refundAmount),
"Transfer out of refund token failed"
);
emit ExchangeProposalCancelled(proposalId);
}
/**
* @notice Executes an exchange proposal that's been approved and not vetoed.
* @dev Callable by anyone. Reverts if the proposal is not in the Approved state
* or proposal.vetoPeriodSeconds has not elapsed since approval.
* @param proposalId The identifier of the proposal to execute.
*/
function executeExchangeProposal(uint256 proposalId) external nonReentrant {
ExchangeProposal storage proposal = exchangeProposals[proposalId];
// Require that the proposal is in the Approved state.
require(proposal.state == ExchangeProposalState.Approved, "Proposal must be in Approved state");
// Require that the veto period has elapsed since the approval time.
require(
proposal.approvalTimestamp.add(proposal.vetoPeriodSeconds) <= block.timestamp,
"Veto period not elapsed"
);
// Mark the proposal as executed. Do so prior to exchanging as a measure against reentrancy.
proposal.state = ExchangeProposalState.Executed;
// Perform the exchange.
(IERC20 sellToken, uint256 sellAmount) = getSellTokenAndSellAmount(proposal);
// If the exchange sells CELO, the CELO is sent to the Reserve from this contract
// and stable token is minted to the exchanger.
if (proposal.sellCelo) {
// Send the CELO from this contract to the reserve.
require(
sellToken.transfer(address(getReserve()), sellAmount),
"Transfer out of CELO to Reserve failed"
);
// Mint stable token to the exchanger.
require(
IStableToken(proposal.stableToken).mint(proposal.exchanger, proposal.buyAmount),
"Stable token mint failed"
);
} else {
// If the exchange is selling stable token, the stable token is burned from
// this contract and CELO is transferred from the Reserve to the exchanger.
// Burn the stable token from this contract.
require(IStableToken(proposal.stableToken).burn(sellAmount), "Stable token burn failed");
// Transfer the CELO from the Reserve to the exchanger.
require(
getReserve().transferExchangeGold(proposal.exchanger, proposal.buyAmount),
"Transfer out of CELO from Reserve failed"
);
}
emit ExchangeProposalExecuted(proposalId);
}
/**
* @notice Gets the sell token and the sell amount for a proposal.
* @dev For stable token sell amounts that are stored as units, the value
* is returned. Ensures sell amount is not greater than this contract's balance.
* @param proposal The proposal to get the sell token and sell amount for.
* @return (the IERC20 sell token, the value sell amount).
*/
function getSellTokenAndSellAmount(ExchangeProposal memory proposal)
private
view
returns (IERC20, uint256)
{
IERC20 sellToken;
uint256 sellAmount;
if (proposal.sellCelo) {
sellToken = getGoldToken();
sellAmount = proposal.sellAmount;
} else {
address stableToken = proposal.stableToken;
sellToken = IERC20(stableToken);
// When selling stableToken, the sell amount is stored in units.
// Units must be converted to value when refunding.
sellAmount = IStableToken(stableToken).unitsToValue(proposal.sellAmount);
}
// In the event a precision issue from the unit <-> value calculations results
// in sellAmount being greater than this contract's balance, set the sellAmount
// to the entire balance.
// This check should not be necessary for CELO, but is done so regardless
// for extra certainty that cancelling an exchange proposal can never fail
// if for some reason the CELO balance of this contract is less than the
// recorded sell amount.
uint256 totalBalance = sellToken.balanceOf(address(this));
if (totalBalance < sellAmount) {
sellAmount = totalBalance;
}
return (sellToken, sellAmount);
}
/**
* @notice Using the oracle price, charges the spread and calculates the amount of
* the asset being bought.
* @dev Stable token value amounts are used for the sellAmount, not unit amounts.
* Assumes both CELO and the stable token have 18 decimals.
* @param celoStableTokenExchangeRate The unwrapped fraction exchange rate of CELO
* quoted in the stable token.
* @param sellAmount The amount of the sell token being sold.
* @param sellCelo Whether CELO is being sold.
* @return The amount of the asset being bought.
*/
function getBuyAmount(uint256 celoStableTokenExchangeRate, uint256 sellAmount, bool sellCelo)
public
view
returns (uint256)
{
FixidityLib.Fraction memory exchangeRate = FixidityLib.wrap(celoStableTokenExchangeRate);
// If stableToken is being sold, instead use the price of stableToken
// quoted in CELO.
if (!sellCelo) {
exchangeRate = exchangeRate.reciprocal();
}
// The sell amount taking the spread into account, ie:
// (1 - spread) * sellAmount
FixidityLib.Fraction memory adjustedSellAmount = FixidityLib.fixed1().subtract(spread).multiply(
FixidityLib.newFixed(sellAmount)
);
// Calculate the buy amount:
// exchangeRate * adjustedSellAmount
return exchangeRate.multiply(adjustedSellAmount).fromFixed();
}
/**
* @notice Removes the proposal ID found at the provided index of activeProposalIdsSuperset
* if the exchange proposal is not active.
* @dev Anyone can call. Reverts if the exchange proposal is active.
* @param index The index of the proposal ID to remove from activeProposalIdsSuperset.
*/
function removeFromActiveProposalIdsSuperset(uint256 index) external {
require(index < activeProposalIdsSuperset.length, "Index out of bounds");
uint256 proposalId = activeProposalIdsSuperset[index];
// Require the exchange proposal to be inactive.
require(
exchangeProposals[proposalId].state != ExchangeProposalState.Proposed &&
exchangeProposals[proposalId].state != ExchangeProposalState.Approved,
"Exchange proposal not inactive"
);
// If not removing the last element, overwrite the index with the value of
// the last element.
uint256 lastIndex = activeProposalIdsSuperset.length.sub(1);
if (index < lastIndex) {
activeProposalIdsSuperset[index] = activeProposalIdsSuperset[lastIndex];
}
// Delete the last element.
activeProposalIdsSuperset.length--;
}
/**
* @notice Gets the proposal identifiers of exchange proposals in the
* Proposed or Approved state. Returns a version of activeProposalIdsSuperset
* with inactive proposal IDs set as 0.
* @dev Elements with a proposal ID of 0 should be filtered out by the consumer.
* @return An array of active exchange proposals IDs.
*/
function getActiveProposalIds() external view returns (uint256[] memory) {
// Solidity doesn't play well with dynamically sized memory arrays.
// Instead, this array is created with the same length as activeProposalIdsSuperset,
// and will replace elements that are inactive proposal IDs with the value 0.
uint256[] memory activeProposalIds = new uint256[](activeProposalIdsSuperset.length);
for (uint256 i = 0; i < activeProposalIdsSuperset.length; i = i.add(1)) {
uint256 proposalId = activeProposalIdsSuperset[i];
if (
exchangeProposals[proposalId].state == ExchangeProposalState.Proposed ||
exchangeProposals[proposalId].state == ExchangeProposalState.Approved
) {
activeProposalIds[i] = proposalId;
}
}
return activeProposalIds;
}
/**
* @notice Gets the oracle CELO price quoted in the stable token.
* @dev Reverts if there is not a rate for the provided stable token.
* @param stableToken The stable token to get the oracle price for.
* @return The oracle CELO price quoted in the stable token.
*/
function getOracleExchangeRate(address stableToken)
private
view
returns (FixidityLib.Fraction memory)
{
uint256 rateNumerator;
uint256 rateDenominator;
(rateNumerator, rateDenominator) = getSortedOracles().medianRate(stableToken);
// When rateDenominator is 0, it means there are no rates known to SortedOracles.
require(rateDenominator > 0, "No oracle rates present for token");
return FixidityLib.wrap(rateNumerator).divide(FixidityLib.wrap(rateDenominator));
}
/**
* @notice Gets the minimum and maximum amount of a stable token that can be
* involved in a single exchange.
* @dev Reverts if there is no explicit exchange limit for the stable token.
* @param stableTokenRegistryId The string registry ID for the stable token.
* @return (minimum exchange amount, maximum exchange amount).
*/
function getStableTokenExchangeLimits(string memory stableTokenRegistryId)
public
view
returns (uint256, uint256)
{
ExchangeLimits memory exchangeLimits = stableTokenExchangeLimits[stableTokenRegistryId];
// Require the configurable stableToken max exchange amount to be > 0.
// This covers the case where a stableToken has never been explicitly permitted.
require(
exchangeLimits.maxExchangeAmount > 0,
"Max stable token exchange amount must be defined"
);
return (exchangeLimits.minExchangeAmount, exchangeLimits.maxExchangeAmount);
}
/**
* @notice Sets the approver.
* @dev Sender must be owner. New approver is allowed to be address(0).
* @param newApprover The new value for the approver.
*/
function setApprover(address newApprover) public onlyOwner {
approver = newApprover;
emit ApproverSet(newApprover);
}
/**
* @notice Sets the maximum allowed change in the CELO/stable token price when
* an exchange proposal is being approved relative to the price when the proposal
* was created.
* @dev Sender must be owner.
* @param newMaxApprovalExchangeRateChange The new value for maxApprovalExchangeRateChange
* to be wrapped.
*/
function setMaxApprovalExchangeRateChange(uint256 newMaxApprovalExchangeRateChange)
public
onlyOwner
{
maxApprovalExchangeRateChange = FixidityLib.wrap(newMaxApprovalExchangeRateChange);
emit MaxApprovalExchangeRateChangeSet(newMaxApprovalExchangeRateChange);
}
/**
* @notice Sets the spread.
* @dev Sender must be owner.
* @param newSpread The new value for the spread to be wrapped. Must be <= fixed 1.
*/
function setSpread(uint256 newSpread) public onlyOwner {
require(newSpread <= FixidityLib.fixed1().unwrap(), "Spread must be smaller than 1");
spread = FixidityLib.wrap(newSpread);
emit SpreadSet(newSpread);
}
/**
* @notice Sets the minimum and maximum amount of the stable token an exchange can involve.
* @dev Sender must be owner. Setting the maxExchangeAmount to 0 effectively disables new
* exchange proposals for the token.
* @param stableTokenRegistryId The registry ID string for the stable token to set limits for.
* @param minExchangeAmount The new minimum exchange amount for the stable token.
* @param maxExchangeAmount The new maximum exchange amount for the stable token.
*/
function setStableTokenExchangeLimits(
string calldata stableTokenRegistryId,
uint256 minExchangeAmount,
uint256 maxExchangeAmount
) external onlyOwner {
require(
minExchangeAmount <= maxExchangeAmount,
"Min exchange amount must not be greater than max"
);
stableTokenExchangeLimits[stableTokenRegistryId] = ExchangeLimits({
minExchangeAmount: minExchangeAmount,
maxExchangeAmount: maxExchangeAmount
});
emit StableTokenExchangeLimitsSet(stableTokenRegistryId, minExchangeAmount, maxExchangeAmount);
}
/**
* @notice Sets the veto period in seconds.
* @dev Sender must be owner.
* @param newVetoPeriodSeconds The new value for the veto period in seconds.
*/
function setVetoPeriodSeconds(uint256 newVetoPeriodSeconds) public onlyOwner {
// Hardcode a max of 4 weeks.
// A minimum is not enforced for flexibility. A case of interest is if
// Governance were to be set as the `approver`, it would be desirable to
// set the veto period to 0 seconds.
require(newVetoPeriodSeconds <= 4 weeks, "Veto period cannot exceed 4 weeks");
vetoPeriodSeconds = newVetoPeriodSeconds;
emit VetoPeriodSecondsSet(newVetoPeriodSeconds);
}
}
| Get the token and amount that will be refunded to the proposer. | (IERC20 refundToken, uint256 refundAmount) = getSellTokenAndSellAmount(proposal);
| 2,543,961 | [
1,
967,
326,
1147,
471,
3844,
716,
903,
506,
1278,
12254,
358,
326,
450,
5607,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
261,
45,
654,
39,
3462,
16255,
1345,
16,
2254,
5034,
16255,
6275,
13,
273,
1322,
1165,
1345,
1876,
55,
1165,
6275,
12,
685,
8016,
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
]
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "hardhat/console.sol";
contract ClaimGameReward is Ownable, ReentrancyGuard {
uint256 public withdrawalFee = 5000 * 1e18;
uint256 public maximumWithdraw = 100000 * 1e18;
uint256 public ecioTax = 10;
IERC20 ECIO_TOKEN;
IERC20 LAKRIMA_TOKEN;
struct Userinfo {
uint32 lastClaimTime;
uint32 startCountTime;
uint256 stackCount;
uint256 userWithdrawFee;
}
/************************ mapping ***************************/
mapping(address => Userinfo) public userInfo;
/************************ event ***************************/
event withdrawEvent(
address user,
uint256 amount,
uint256 dynm,
uint32 input
);
/************************ Setup ***************************/
function setupEcioContract(IERC20 ecioToken) external onlyOwner {
ECIO_TOKEN = ecioToken;
}
function setupLakrimaContract(IERC20 lakrimaToken) external onlyOwner {
LAKRIMA_TOKEN = lakrimaToken;
}
function setupWithdrawalFee(uint256 newRate) public onlyOwner {
withdrawalFee = newRate;
}
function setupEcioTax(uint256 newRate) public onlyOwner {
ecioTax = newRate;
}
function setupMaximumWithDraw(uint256 newRate) public onlyOwner {
maximumWithdraw = newRate;
}
/************************** View *************************/
function getNextClaim(address user) public view returns (uint256) {
return userInfo[user].startCountTime + 36 hours;
}
function getUserWithdrawFee(address user) public view returns (uint256) {
return userInfo[user].userWithdrawFee;
}
/************************** Action *************************/
function withdraw(
address user,
uint256 amount,
uint256 dynmFee,
uint32 input
) external onlyOwner nonReentrant {
compare36Hours(user);
uint256 userBalance = ECIO_TOKEN.balanceOf(user);
if (userInfo[user].stackCount > 1) {
increaseTax(user);
} else {
userInfo[user].userWithdrawFee = withdrawalFee;
userInfo[user].startCountTime = uint32(block.timestamp);
}
require(
userBalance >= userInfo[user].userWithdrawFee,
"ECIO: your balance is not enough for the fee"
);
require(
amount <= maximumWithdraw,
"ECIO: the amount exceeds the limit"
);
ECIO_TOKEN.transferFrom(
user,
address(this),
userInfo[user].userWithdrawFee
);
if (input == 0) {
ECIO_TOKEN.transfer(user, amount);
} else if (input == 1) {
LAKRIMA_TOKEN.transfer(user, amount);
}
userInfo[user].lastClaimTime = uint32(block.timestamp);
emit withdrawEvent(user, amount, dynmFee, input);
}
// increase stackCount if user withdraw within 36 hours
function compare36Hours(address user) internal {
uint32 amountTime = uint32(block.timestamp) -
userInfo[user].startCountTime;
if (amountTime <= 36 hours) {
userInfo[user].stackCount = userInfo[user].stackCount + 1;
} else if (amountTime > 36 hours) {
userInfo[user].stackCount = 1;
}
}
function increaseTax(address user) internal {
userInfo[user].userWithdrawFee = calculation(user);
}
// calculate fee if user withdraw within 36 hours
function calculation(address user) public view returns (uint256) {
uint256 userStackCount = userInfo[user].stackCount - 1;
uint256 result = withdrawalFee;
result =
(result * ((100 + ecioTax)**userStackCount)) /
(100**userStackCount);
return result;
}
// transfer token
function transfer(
address _contractAddress,
address _to,
uint256 _amount
) public onlyOwner {
IERC20 _token = IERC20(_contractAddress);
_token.transfer(_to, _amount);
}
}
| increase stackCount if user withdraw within 36 hours | function compare36Hours(address user) internal {
uint32 amountTime = uint32(block.timestamp) -
userInfo[user].startCountTime;
if (amountTime <= 36 hours) {
userInfo[user].stackCount = userInfo[user].stackCount + 1;
userInfo[user].stackCount = 1;
}
}
| 15,811,553 | [
1,
267,
11908,
2110,
1380,
309,
729,
598,
9446,
3470,
6580,
7507,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3400,
5718,
14910,
12,
2867,
729,
13,
2713,
288,
203,
3639,
2254,
1578,
3844,
950,
273,
2254,
1578,
12,
2629,
18,
5508,
13,
300,
203,
5411,
16753,
63,
1355,
8009,
1937,
1380,
950,
31,
203,
3639,
309,
261,
8949,
950,
1648,
6580,
7507,
13,
288,
203,
5411,
16753,
63,
1355,
8009,
3772,
1380,
273,
16753,
63,
1355,
8009,
3772,
1380,
397,
404,
31,
203,
5411,
16753,
63,
1355,
8009,
3772,
1380,
273,
404,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract MiraMe{
// Events
/*
* New Content by 'creator' has been added. It has id 'id'
*/
event NewContent(uint id, address creator);
/*
* Content 'id', created by 'creator' change sponsor to 'sponsor'
*/
event ChangeSponsor(uint id, address creator, address sponsor);
// constants
uint sponsorPercentageOnSell = 70;
uint creatorPercentageOnSell = 20;
uint minimumFee = 0.0001 ether;
// structs
struct Content{
string hash;
uint price;
}
address platform;
Content[] public contents;
mapping (uint => address) private contentToOwner;
mapping (uint => address) private contentToSponsor;
mapping (address => uint) private contentsByOwner;
// Modifiers
modifier onlyCreator(uint id){
require(contentToOwner[id] == msg.sender, "Only Creator can do this");
_;
}
modifier onlySponsor(uint id){
require(contentToSponsor[id] == msg.sender, "Only Sponsor can do this");
_;
}
modifier onlyCreatorOrSponsor(uint id){
require(contentToOwner[id] == msg.sender || contentToSponsor[id] == msg.sender, "Only Creator or Sponsor can do this");
_;
}
modifier onlyPlatform(){
require(msg.sender == platform, "Only ME can do this.");
_;
}
constructor(){
platform = msg.sender;
}
// Private functions
function _createContent(string memory _hash, uint price, address _creator) internal {
contents.push(Content(_hash, price));
uint id = contents.length;
contentToOwner[id] = _creator;
contentToSponsor[id] = _creator;
contentsByOwner[_creator]++;
emit NewContent(id, _creator);
}
function _changeSponsor(uint _id, address _newSponsor) internal {
contentToSponsor[_id] = _newSponsor;
address creator = contentToOwner[_id];
emit ChangeSponsor(_id, creator, _newSponsor);
}
// Public functions
/*
* Creates a new Content with a given hash and a given price
* Price has to be higher than minimumFee saved in the contract.
* Price has to be in Wei.
*/
function createContent(string calldata hash, uint price) public {
require(price > minimumFee, "Price is too low");
_createContent(hash, price, msg.sender);
}
/*
* Changes the sponsor of the Content
* Only the sponsor can change the sponsor.
* At the beginning, the creator IS the sponsor.
* Check if the given ID exists
*/
function changeSponsor(uint id, address newSponsor) public onlySponsor(id){
require(contents.length >= id, "Content does not exists");
_changeSponsor(id, newSponsor);
}
/*
* Changes the price of the content.
* Price has to be higher than minimuFee saved in the contract.
* Price has to be in Wei.
* Check if the given ID exists
* Only the sponsor can change the sponsor.
* At the beginning, the creator IS the sponsor.
*/
function changePrice(uint id, uint price) public onlySponsor(id){
require(price > minimumFee, "New Price is too low");
require(contents[id].price >= 0, "Content does not exists");
contents[id].price = price;
}
/*
* Buy the Content, providing the value in wei.
*/
function buyContent(uint _id) public payable {
require(contents.length >= _id, "Content does not exists");
require(contents[_id].price <= msg.value, "Your offer is below price");
require(contentToSponsor[_id] != msg.sender, "This content is already yours!");
uint creatorFee = msg.value * creatorPercentageOnSell / 100;
uint sponsorFee = msg.value * sponsorPercentageOnSell / 100;
uint platformFee = msg.value - creatorFee - sponsorFee;
contentToSponsor[_id] = msg.sender;
payable(contentToOwner[_id]).transfer(creatorFee);
payable(contentToSponsor[_id]).transfer(sponsorFee);
payable(platform).transfer(platformFee);
}
/*
* Get the list of the contents by creator.
*/
function getContentsByCreator(address _creator) external view returns(uint[] memory) {
uint[] memory result = new uint[](contentsByOwner[_creator]);
uint counter = 0;
for (uint i = 0; i < contents.length; i++) {
if (contentToOwner[i] == _creator) {
result[counter] = i;
counter++;
}
}
return result;
}
/*
* Changes the percentage for all the contents.
* The sponsor percentage and the creator percentage cannot overflow 95, for a minimum 5% percentage for the platform.
*/
function changePercentages(uint _sponsor, uint _creator) public onlyPlatform {
require(_sponsor + _creator <= 95, "Sponsor + Creator fees are too high");
sponsorPercentageOnSell = _sponsor;
creatorPercentageOnSell = _creator;
}
/*
* Changes the minimum fee to operate.
*/
function changeMinimumFee(uint _minimumFee) public onlyPlatform {
minimumFee = _minimumFee;
}
/*
* Get back all the money forom the contract.
*/
function transferMoney() public onlyPlatform{
payable(platform).transfer(address(this).balance);
}
}
| Changes the sponsor of the Content Only the sponsor can change the sponsor. At the beginning, the creator IS the sponsor. Check if the given ID exists/ | function changeSponsor(uint id, address newSponsor) public onlySponsor(id){
require(contents.length >= id, "Content does not exists");
_changeSponsor(id, newSponsor);
}
| 12,993,790 | [
1,
7173,
326,
272,
500,
2467,
434,
326,
3697,
5098,
326,
272,
500,
2467,
848,
2549,
326,
272,
500,
2467,
18,
2380,
326,
8435,
16,
326,
11784,
4437,
326,
272,
500,
2467,
18,
2073,
309,
326,
864,
1599,
1704,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2549,
55,
500,
2467,
12,
11890,
612,
16,
1758,
30826,
500,
2467,
13,
1071,
1338,
55,
500,
2467,
12,
350,
15329,
203,
3639,
2583,
12,
3980,
18,
2469,
1545,
612,
16,
315,
1350,
1552,
486,
1704,
8863,
203,
3639,
389,
3427,
55,
500,
2467,
12,
350,
16,
30826,
500,
2467,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./utils/Math.sol";
import "@chainlink/contracts/src/v0.6/vendor/BufferChainlink.sol";
import "@chainlink/contracts/src/v0.6/vendor/CBORChainlink.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract AtlanticReceiverV1 is Math, AccessControl {
using CBORChainlink for BufferChainlink.buffer;
// ** SET ROLES ** //
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant MESSAGE_OWNER_ROLE = keccak256("MESSAGE_OWNER_ROLE");
struct Message {
uint64 id;
string method;
address callback;
uint32 amount;
address destination;
BufferChainlink.buffer buf;
}
Message[] allMessages;
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
uint64 messageCounter;
address owner;
mapping(uint64 => Message) private messages;
mapping(uint64 => address) private messageOwners;
// Chainlink Client Declarations
uint256 fee;
bytes32 jobId;
address OracleAddress;
constructor() public {
messageCounter = 0;
}
//** CONTRACT EVENTS **//
event FunctionExecuted(string _method, address _callback, uint32 _amount, address _destination);
event SuccessfulCall(bool success, bytes returnData);
event CallbackMessage(bytes _message, uint256 _capacity, uint64 _messageId);
// ** CONTRACT LOGIC **//
function getMessage(
uint64 _messageId
) public view returns (uint32, address, address, uint64, string memory) {
Message memory message = messages[_messageId];
return (message.amount, message.callback, message.destination, message.id, message.method);
}
// ** INBOUND LOGIC **//
function receiveFromRemoteChain(
string memory _method,
address _callback,
uint32 _amount,
address _destination,
uint64 _id
) public {
// ** SAVE MESSAGE ** //
Message memory message;
message.id = _id;
message.method = _method;
message.callback = _callback;
message.amount = _amount;
message.destination = _destination;
messages[_id] = message;
emit FunctionExecuted(message.method, message.callback, message.amount, message.destination);
// ** EXECUTE FUNCTION ** //
bytes memory payload = abi.encodeWithSignature("setFoo(uint)", 12);
(bool success, bytes memory returnData) = address(_destination).call(payload);
emit SuccessfulCall(success, returnData);
require(success);
}
// ** OUTBOUND FUNCTIONS **//
/**
Create a callback function that emits an event that should be transmitted.
*/
function sendCallback(bytes memory bufMessage, uint256 capacity, uint64 _id) public {
emit CallbackMessage(bufMessage, capacity, _id);
}
//** CONTRACT GOVERNANCE **//
function setOwner(address _address) external {
require(msg.sender == owner, "Only the owner can set a new owner");
owner = _address;
}
function getOwner() external view returns(address) {
return owner;
}
} | ** CONTRACT EVENTS ** | event FunctionExecuted(string _method, address _callback, uint32 _amount, address _destination);
| 12,963,683 | [
1,
6067,
2849,
1268,
9964,
55,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
871,
4284,
23839,
12,
1080,
389,
2039,
16,
1758,
389,
3394,
16,
2254,
1578,
389,
8949,
16,
1758,
389,
10590,
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
]
|
./full_match/1/0xCfE7a48f89C24c9ACEA8B9735A1415C71b30E4BD/sources/src/VestingWalletWithClawback.sol | * @dev Allow owner to clawback unvested ERC20 tokens from contract. Emits an {ERC20ClawedBack} event./ | function clawback(address token) public onlyOwner {
if (clawbackHasOccurred(token)) {
revert ClawbackHasAlreadyOccurred();
}
uint256 releasableErc20 = releasable(token);
SafeERC20.safeTransfer(IERC20(token), msg.sender, amount);
emit ERC20ClawedBack(token, amount);
}
| 3,178,475 | [
1,
7009,
3410,
358,
927,
2219,
823,
640,
90,
3149,
4232,
39,
3462,
2430,
628,
6835,
18,
7377,
1282,
392,
288,
654,
39,
3462,
2009,
2219,
329,
2711,
97,
871,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
927,
2219,
823,
12,
2867,
1147,
13,
1071,
1338,
5541,
288,
203,
3639,
309,
261,
830,
2219,
823,
5582,
30096,
12,
2316,
3719,
288,
203,
5411,
15226,
3905,
2219,
823,
5582,
9430,
30096,
5621,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
6707,
345,
429,
41,
1310,
3462,
273,
6707,
345,
429,
12,
2316,
1769,
203,
203,
203,
203,
3639,
14060,
654,
39,
3462,
18,
4626,
5912,
12,
45,
654,
39,
3462,
12,
2316,
3631,
1234,
18,
15330,
16,
3844,
1769,
203,
3639,
3626,
4232,
39,
3462,
2009,
2219,
329,
2711,
12,
2316,
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
]
|
./full_match/1/0x2787ac2FE18a0fc3c6312b602B2E5C9D76B7c3c2/sources/leaguebot.sol | 10% from total supply maxTransactionAmountTxn
| uint256 maxTransactionAmount = 100_000 * 1e18; | 9,813,289 | [
1,
2163,
9,
628,
2078,
14467,
943,
3342,
6275,
13789,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
943,
3342,
6275,
273,
225,
2130,
67,
3784,
380,
404,
73,
2643,
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.8.2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import '../contracts/libraries/StringUtils.sol';
import '../contracts/libraries/SafeMath.sol';
// This is the main building block for smart contracts.
contract EnergyGridUpgradeableV2 is Ownable,ERC20 {
using SafeMath for uint256;
// We set the 3 options players are required to choose
// We set it to constant to avoid wrong typo, safer for the contract
//user type
//basic , premium or hybrid user
string basic = "basic";
string premium = "premium";
string hybrid = "hybrid";
bool basicchosen = false;
bool premiumchosen = false;
bool hybridchosen = false;
string userchoicename;
bool setprevrewards = false;
string servicechosen;
// We assign state variables here
string private _tokenname ="ENERGYTOKENS";
string private _tokensymbol= "ENG";
address private _owner;
uint256 randNonce =0;
uint256 modulus =0;
uint256 _payfee=0;
uint256 maxWaitTime = 100;
uint256 amounttostake;
uint256 prev_gridstaked;
// address owner;
// We decide to use the mapping instead of the struct approach
// We set a struct for each grid, the users of the grid and then the information on what user information in each grid
struct Grid {
uint256 gridid;
uint256 gridcount;
}
struct Users {
address payable useraddress;
string username;
uint256 userpoint;
uint256 userbalance;
}
struct UserInEnergyGridInfo{
uint256 energygridid;
address payable usersingridaddress;
bool gridfunctioning;
uint256 gridreputationscore;
uint256 griduserscount;
uint256 duration;
}
// The fixed amount of tokens stored in an unsigned integer type variable.
uint256 public _totalSupply = 1000000;
// An address type variable is used to store ethereum accounts taken from Ownable.sol
// address public owner;
// A mapping is a key/value map. Here we store each account balance.
// We store values that can be easy to have when we want to index values
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) private _allowances;
// We have a grid check, a previous reward and the user grid info here
mapping(address => mapping(bytes32 => bool)) useringridcheck;
mapping(uint256 => mapping(address => uint256)) prev_rewards;
mapping(uint256 => mapping(address => uint256)) usersingridinfodetail;
mapping(uint256 => uint256) gridsused;
mapping(address => address) usersinallgrid;
mapping(address => bool)paidforgridusage;
//We set into memory for cheaper access
// Mapping for carrying the infors
mapping(uint256=>Grid) public _energygrids;
mapping(address=>Users)public userlist;
mapping(uint256=>UserInEnergyGridInfo) public usersingridlist;
// We set the object for our tracks
Grid newenergygrid;
Users newuserregistered;
UserInEnergyGridInfo useringridinfo;
// We push into storage
Grid[] public energygridregistered;
Users[] public usersregistered;
UserInEnergyGridInfo[] public usersingridinfo;
/**npn
* Contract initialization.
*
* The `constructor` is executed only once when the contract is created.
*/
// modifier to check if caller is owner
constructor(address __owner) ERC20(_tokenname, _tokensymbol ) {
_owner =__owner;
// Full initializations
// we set the owner from Ownable
_owner = owner();
_owner = __owner;
balances[_owner] = _totalSupply;
}
/*
modifier isOwner() {
// If the first argument of 'require' evaluates to 'false', execution terminates and all
// changes to the state and to Ether balances are reverted.
// This used to consume all gas in old EVM versions, but not anymore.
// It is often a good idea to use 'require' to check if functions are called correctly.
// As a second argument, you can also provide an explanation about what went wrong.
require(msg.sender == _owner , "Caller is not owner");
}
*/
/**
* A function to transfer tokens.
*
* The `external` modifier makes a function *only* callable from outside
* the contract.
*/
// We make ppayment to participate in the grid
function payfee(address payable sender, uint256 amount) external payable returns(bool, bytes memory){
// Call returns a boolean value indicating success or failure.
// This is the current recommended method to use.
_owner =owner();
require ( amount >= 10, "Amount not enough to play!");
// (bool sent, bytes memory data) = msg.sender.call{value: _payfee}("");
// require(sent, "Failed to send Ether");
(bool success,bytes memory data ) = _owner.call{value: _payfee}("");
require(success, "Check the amount sent as well");
paidforgridusage[sender]= true;
return (success,data);
}
//Eventing everything
function registerenergyusername(string memory _username, address payable _useraddress) external returns(string memory, address){
//If we dont want to use the modifier from Ownable.sol
require(msg.sender == _owner , "Caller is not owner");
if (paidforgridusage[_useraddress] == true){
uint256 userbalance =0;
userbalance = balanceOf(_useraddress);
if(usersinallgrid[_useraddress] != _useraddress){
//for player who has ever played before
usersinallgrid[_useraddress] =_useraddress ;
// for registered player
// Storing to memory
newuserregistered = Users(_useraddress,_username, 0,userbalance );
userlist[_useraddress].useraddress = _useraddress;
userlist[_useraddress].username = _username;
userlist[_useraddress].userpoint = 0;
userlist[_useraddress].userbalance = userbalance;
// Storing to storage
usersregistered.push(newuserregistered);
return (_username,_useraddress );
}
}
}
// Registration for grid
function registergrid(uint256 _energygridid) external returns(uint256){
uint256 i =0;
i++;
require(msg.sender == _owner , "Caller is not owner");
uint256 energygridcount = 0;
if(gridsused[_energygridid] != _energygridid){
gridsused[_energygridid] = _energygridid;
newenergygrid = Grid(_energygridid,energygridcount );
// Store into memory
_energygrids[_energygridid].gridid = _energygridid;
_energygrids[_energygridid].gridcount = i;
energygridregistered.push(newenergygrid);
return (_energygridid);
}
}
// set the grid for the user
function setenergygridwithuser(uint256 _energygridid, address payable _energyuseraddress) internal returns(uint, address) {
uint256 _energyusercount =0;
_energyusercount++;
require(msg.sender == _owner , "Caller is not Energy Grid owner");
uint256 __energygridid =0;
__energygridid = _energygridid;
// We set the nonce to any random number
// We can set any random variable
randNonce;
modulus= 100000000000;
__energygridid = uint256(keccak256(abi.encodePacked(block.timestamp,
msg.sender,
randNonce))) %
modulus;
require(msg.sender == _owner, "Caller is not owner");
// The list of players must be less than two
require( usersingridlist[_energygridid].griduserscount < 50 == true, "Only 50 users in each energy grid");
require(usersingridinfodetail[_energygridid][_energyuseraddress] == _energygridid, "User is already a member of grid");
// We check if user is registered within id
usersingridinfodetail[_energygridid][_energyuseraddress] = _energygridid;
uint256 _duration = block.number + maxWaitTime;
useringridinfo = UserInEnergyGridInfo(_energygridid, _energyuseraddress, false, 0,0, _duration);
usersingridlist[__energygridid].energygridid = _energygridid;
usersingridlist[__energygridid].usersingridaddress = _energyuseraddress;
usersingridlist[__energygridid].gridfunctioning = false;
usersingridlist[__energygridid].gridreputationscore = 0;
usersingridlist[__energygridid].griduserscount = 0;
usersingridlist[__energygridid].duration = _duration;
// Setting into storage
usersingridinfo.push(useringridinfo);
return(_energygridid, _energyuseraddress);
}
function _checkuserregistered(address payable _useraddress) public returns (bool ) {
require(usersinallgrid[_useraddress] == _useraddress );
return(true);
}
function _checkgridregistered(uint256 _energygridid) public returns (bool) {
require(_energygrids[_energygridid].gridid== _energygridid,"Energy grid id does not exist" );
return(true);
}
function _checkuseringrid(uint256 _energygridid,address _useraddress ) public returns (bool){
require( usersingridlist[_energygridid].usersingridaddress == _useraddress,"User not fouund in grid");
return (true);
}
// We can choose each service
function selectBasic( ) public virtual returns(bool)
{
if (basicchosen){
basicchosen = true;
return (basicchosen);
}else{
basicchosen = false;
return (basicchosen);
}
}
function selectPremium() public virtual returns(bool)
{ if (premiumchosen){
premiumchosen = true;
return (premiumchosen);
}else{
premiumchosen = false;
return (premiumchosen);
}
}
function selectHybrid( ) public virtual returns(bool){
if (hybridchosen){
hybridchosen = true;
return (hybridchosen);
}else{
hybridchosen = false;
return (hybridchosen);
}
}
// We can stake previous rewards gotten in the grid
function stakeprevrewards( ) public virtual returns(bool) {
if(setprevrewards) {
setprevrewards =true;
}else{
setprevrewards =false;
}
return (setprevrewards);
}
function choosegridtostake(uint256 energygridid,address payable _useraddress, uint256 _amount ) public virtual returns(uint256){
prev_gridstaked =0;
prev_gridstaked=energygridid;
if (stakeprevrewards( ) ==true ){
amounttostake =0;
amounttostake=_amount;
uint256 winnings =0;
winnings = prev_rewards[energygridid][_useraddress];
require( winnings > amounttostake, " The amount requested is not enough in this grid,please check in another grid");
transfer(_owner, amounttostake);
return( amounttostake);
}
}
//Now time to connect to grid
event connectogridevent(uint256 eventenergygridid, address payable _eventuseraddress, string _eventservicechosen);
function connecttogrid(uint256 _energygridid, address payable _energyuseraddresss) internal returns(uint256, address, string memory){
string memory _servicechosen;
// Access Controls
require(msg.sender == _owner , "Caller is not owner");
_checkuserregistered(_energyuseraddresss);
_checkgridregistered( _energygridid);
_checkuseringrid( _energygridid ,_energyuseraddresss );
choosegridtostake(prev_gridstaked, _energyuseraddresss,amounttostake );
servicechosen = _servicechosen;
if (selectBasic() == true ){
premiumchosen = false;
hybridchosen = false;
servicechosen = "basic" ;
}
if (selectPremium()== true ){
basicchosen = false;
hybridchosen = false;
servicechosen = "premium" ;
}
if (selectHybrid()== true ){
basicchosen =false;
premiumchosen =false;
servicechosen = "hybrid" ;
}
// We set a shuffler to generate a random number
uint256 shuffler = 0;
shuffler= 100000000;
uint256 _energyindex = 0;
// We set a random number, well there has to be a better way of doing this thing
randNonce++;
_gameindex = uint256(keccak256(abi.encodePacked(block.timestamp,
msg.sender,
randNonce))) %
shuffler;
string memory premiumpackage = "premium";
if (StringUtils.equal(servicechosen, premiumpackage)== true ){
approve( _energyuseraddresss, 100);
transfer(_energyuseraddresss,100);
// _owner.transfer(_theplayeraddress,10000);
balanceOf(_energyuseraddresss);
prev_rewards[_energygridid][_energyuseraddresss] +=100;
// Whatever energy business model is necessary to be built
}
emit connectogridevent( _energygridid, _energyuseraddresss, servicechosen);
return ( _energygridid, _energyuseraddresss, servicechosen);
}
// We inherit some ERC20 calls
function balanceOf(address account) public view override returns (uint256) {
return (balances[account]);
}
function owner() public view virtual override returns (address) {
return (_owner);
}
function mint (address account, uint256 amount) external virtual returns (address, uint256 ) {
_mint( msg.sender, amount);
return( account, amount);
}
function burn (address account, uint256 amount) external virtual returns (address, uint256 ) {
_burn( msg.sender , amount);
return( account, amount);
}
function totalSupply() public view virtual override returns (uint256) {
return (_totalSupply);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
// Just in case we have not transferred to sender
// sender =_owner;
_transfer(sender, recipient, amount);
// setting allowance value here
uint256 allowallowance = _allowances[sender][_msgSender()];
// 90 percent of owners balance allowed
uint256 senderbalance = balances[sender];
uint256 allownacevalue =90;
uint256 ninetypercent = allownacevalue /100;
uint256 maximumallowance = ninetypercent * senderbalance;
// We set the current allowance as that figure
// uint256 currentAllowance = _allowances[sender][_msgSender()];
allowallowance =maximumallowance;
uint256 currentAllowance = allowallowance;
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
} | This is the main building block for smart contracts. We set the 3 options players are required to choose We set it to constant to avoid wrong typo, safer for the contractuser typebasic , premium or hybrid user We assign state variables here address owner; We decide to use the mapping instead of the struct approach We set a struct for each grid, the users of the grid and then the information on what user information in each grid | contract EnergyGridUpgradeableV2 is Ownable,ERC20 {
using SafeMath for uint256;
string basic = "basic";
string premium = "premium";
string hybrid = "hybrid";
bool basicchosen = false;
bool premiumchosen = false;
bool hybridchosen = false;
string userchoicename;
bool setprevrewards = false;
string servicechosen;
string private _tokenname ="ENERGYTOKENS";
string private _tokensymbol= "ENG";
address private _owner;
uint256 randNonce =0;
uint256 modulus =0;
uint256 _payfee=0;
uint256 maxWaitTime = 100;
uint256 amounttostake;
uint256 prev_gridstaked;
struct Grid {
uint256 gridid;
uint256 gridcount;
}
struct Users {
address payable useraddress;
string username;
uint256 userpoint;
uint256 userbalance;
}
struct UserInEnergyGridInfo{
uint256 energygridid;
address payable usersingridaddress;
bool gridfunctioning;
uint256 gridreputationscore;
uint256 griduserscount;
uint256 duration;
}
mapping(address => mapping(address => uint256)) private _allowances;
mapping(uint256 => mapping(address => uint256)) prev_rewards;
mapping(uint256 => mapping(address => uint256)) usersingridinfodetail;
mapping(uint256 => uint256) gridsused;
mapping(address => address) usersinallgrid;
mapping(address => bool)paidforgridusage;
mapping(address=>Users)public userlist;
mapping(uint256=>UserInEnergyGridInfo) public usersingridlist;
Users newuserregistered;
UserInEnergyGridInfo useringridinfo;
Users[] public usersregistered;
UserInEnergyGridInfo[] public usersingridinfo;
uint256 public _totalSupply = 1000000;
mapping(address => uint256) balances;
mapping(address => mapping(bytes32 => bool)) useringridcheck;
mapping(uint256=>Grid) public _energygrids;
Grid newenergygrid;
Grid[] public energygridregistered;
constructor(address __owner) ERC20(_tokenname, _tokensymbol ) {
_owner =__owner;
_owner = owner();
_owner = __owner;
balances[_owner] = _totalSupply;
}
modifier isOwner() {
require(msg.sender == _owner , "Caller is not owner");
}
function payfee(address payable sender, uint256 amount) external payable returns(bool, bytes memory){
_owner =owner();
require ( amount >= 10, "Amount not enough to play!");
require(success, "Check the amount sent as well");
paidforgridusage[sender]= true;
return (success,data);
}
(bool success,bytes memory data ) = _owner.call{value: _payfee}("");
function registerenergyusername(string memory _username, address payable _useraddress) external returns(string memory, address){
require(msg.sender == _owner , "Caller is not owner");
if (paidforgridusage[_useraddress] == true){
uint256 userbalance =0;
userbalance = balanceOf(_useraddress);
if(usersinallgrid[_useraddress] != _useraddress){
usersinallgrid[_useraddress] =_useraddress ;
newuserregistered = Users(_useraddress,_username, 0,userbalance );
userlist[_useraddress].useraddress = _useraddress;
userlist[_useraddress].username = _username;
userlist[_useraddress].userpoint = 0;
userlist[_useraddress].userbalance = userbalance;
usersregistered.push(newuserregistered);
return (_username,_useraddress );
}
}
}
function registerenergyusername(string memory _username, address payable _useraddress) external returns(string memory, address){
require(msg.sender == _owner , "Caller is not owner");
if (paidforgridusage[_useraddress] == true){
uint256 userbalance =0;
userbalance = balanceOf(_useraddress);
if(usersinallgrid[_useraddress] != _useraddress){
usersinallgrid[_useraddress] =_useraddress ;
newuserregistered = Users(_useraddress,_username, 0,userbalance );
userlist[_useraddress].useraddress = _useraddress;
userlist[_useraddress].username = _username;
userlist[_useraddress].userpoint = 0;
userlist[_useraddress].userbalance = userbalance;
usersregistered.push(newuserregistered);
return (_username,_useraddress );
}
}
}
function registerenergyusername(string memory _username, address payable _useraddress) external returns(string memory, address){
require(msg.sender == _owner , "Caller is not owner");
if (paidforgridusage[_useraddress] == true){
uint256 userbalance =0;
userbalance = balanceOf(_useraddress);
if(usersinallgrid[_useraddress] != _useraddress){
usersinallgrid[_useraddress] =_useraddress ;
newuserregistered = Users(_useraddress,_username, 0,userbalance );
userlist[_useraddress].useraddress = _useraddress;
userlist[_useraddress].username = _username;
userlist[_useraddress].userpoint = 0;
userlist[_useraddress].userbalance = userbalance;
usersregistered.push(newuserregistered);
return (_username,_useraddress );
}
}
}
function registergrid(uint256 _energygridid) external returns(uint256){
uint256 i =0;
i++;
require(msg.sender == _owner , "Caller is not owner");
uint256 energygridcount = 0;
if(gridsused[_energygridid] != _energygridid){
gridsused[_energygridid] = _energygridid;
newenergygrid = Grid(_energygridid,energygridcount );
_energygrids[_energygridid].gridid = _energygridid;
_energygrids[_energygridid].gridcount = i;
energygridregistered.push(newenergygrid);
return (_energygridid);
}
}
function registergrid(uint256 _energygridid) external returns(uint256){
uint256 i =0;
i++;
require(msg.sender == _owner , "Caller is not owner");
uint256 energygridcount = 0;
if(gridsused[_energygridid] != _energygridid){
gridsused[_energygridid] = _energygridid;
newenergygrid = Grid(_energygridid,energygridcount );
_energygrids[_energygridid].gridid = _energygridid;
_energygrids[_energygridid].gridcount = i;
energygridregistered.push(newenergygrid);
return (_energygridid);
}
}
function setenergygridwithuser(uint256 _energygridid, address payable _energyuseraddress) internal returns(uint, address) {
uint256 _energyusercount =0;
_energyusercount++;
require(msg.sender == _owner , "Caller is not Energy Grid owner");
uint256 __energygridid =0;
__energygridid = _energygridid;
randNonce;
modulus= 100000000000;
__energygridid = uint256(keccak256(abi.encodePacked(block.timestamp,
msg.sender,
randNonce))) %
modulus;
require(msg.sender == _owner, "Caller is not owner");
require( usersingridlist[_energygridid].griduserscount < 50 == true, "Only 50 users in each energy grid");
require(usersingridinfodetail[_energygridid][_energyuseraddress] == _energygridid, "User is already a member of grid");
usersingridinfodetail[_energygridid][_energyuseraddress] = _energygridid;
uint256 _duration = block.number + maxWaitTime;
useringridinfo = UserInEnergyGridInfo(_energygridid, _energyuseraddress, false, 0,0, _duration);
usersingridlist[__energygridid].energygridid = _energygridid;
usersingridlist[__energygridid].usersingridaddress = _energyuseraddress;
usersingridlist[__energygridid].gridfunctioning = false;
usersingridlist[__energygridid].gridreputationscore = 0;
usersingridlist[__energygridid].griduserscount = 0;
usersingridlist[__energygridid].duration = _duration;
usersingridinfo.push(useringridinfo);
return(_energygridid, _energyuseraddress);
}
function _checkuserregistered(address payable _useraddress) public returns (bool ) {
require(usersinallgrid[_useraddress] == _useraddress );
return(true);
}
function _checkgridregistered(uint256 _energygridid) public returns (bool) {
require(_energygrids[_energygridid].gridid== _energygridid,"Energy grid id does not exist" );
return(true);
}
function _checkuseringrid(uint256 _energygridid,address _useraddress ) public returns (bool){
require( usersingridlist[_energygridid].usersingridaddress == _useraddress,"User not fouund in grid");
return (true);
}
function selectBasic( ) public virtual returns(bool)
{
if (basicchosen){
basicchosen = true;
return (basicchosen);
basicchosen = false;
return (basicchosen);
}
}
function selectBasic( ) public virtual returns(bool)
{
if (basicchosen){
basicchosen = true;
return (basicchosen);
basicchosen = false;
return (basicchosen);
}
}
}else{
function selectPremium() public virtual returns(bool)
{ if (premiumchosen){
premiumchosen = true;
return (premiumchosen);
premiumchosen = false;
return (premiumchosen);
}
}else{
}
| 5,468,371 | [
1,
2503,
353,
326,
2774,
10504,
1203,
364,
13706,
20092,
18,
1660,
444,
326,
890,
702,
18115,
854,
1931,
358,
9876,
1660,
444,
518,
358,
5381,
358,
4543,
7194,
3815,
83,
16,
7864,
586,
364,
326,
6835,
1355,
618,
13240,
269,
23020,
5077,
578,
30190,
729,
1660,
2683,
919,
3152,
2674,
225,
1758,
225,
3410,
31,
1660,
16288,
358,
999,
326,
2874,
3560,
434,
326,
1958,
17504,
1660,
444,
279,
1958,
364,
1517,
3068,
16,
326,
3677,
434,
326,
3068,
471,
1508,
326,
1779,
603,
4121,
729,
1779,
316,
1517,
3068,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
512,
1224,
7797,
6313,
10784,
429,
58,
22,
353,
565,
14223,
6914,
16,
654,
39,
3462,
288,
203,
9940,
14060,
10477,
364,
2254,
5034,
31,
203,
1080,
565,
5337,
273,
315,
13240,
14432,
203,
1080,
282,
23020,
5077,
273,
315,
1484,
81,
5077,
14432,
203,
1080,
282,
30190,
273,
315,
18112,
14400,
14432,
203,
6430,
282,
5337,
343,
8918,
273,
629,
31,
203,
6430,
282,
23020,
5077,
343,
8918,
273,
629,
31,
203,
6430,
282,
30190,
343,
8918,
273,
629,
31,
203,
1080,
729,
2599,
335,
1069,
31,
203,
6430,
282,
444,
10001,
266,
6397,
273,
629,
31,
203,
1080,
225,
1156,
343,
8918,
31,
203,
1080,
3238,
389,
2316,
529,
273,
6,
8196,
20564,
8412,
55,
14432,
203,
1080,
3238,
389,
7860,
3284,
33,
315,
16324,
14432,
203,
2867,
3238,
389,
8443,
31,
203,
11890,
5034,
5605,
13611,
273,
20,
31,
203,
11890,
5034,
24770,
273,
20,
31,
203,
11890,
5034,
389,
10239,
21386,
33,
20,
31,
203,
11890,
5034,
943,
23637,
273,
2130,
31,
203,
11890,
5034,
3844,
88,
669,
911,
31,
225,
203,
11890,
5034,
2807,
67,
5222,
334,
9477,
31,
377,
203,
1697,
7145,
288,
203,
11890,
5034,
225,
3068,
350,
31,
225,
203,
11890,
5034,
3068,
1883,
31,
203,
97,
203,
1697,
12109,
288,
203,
2867,
8843,
429,
729,
2867,
31,
203,
1080,
2718,
31,
203,
11890,
5034,
729,
1153,
31,
203,
11890,
5034,
729,
12296,
31,
203,
97,
203,
1697,
2177,
382,
664,
31920,
6313,
966,
95,
203,
11890,
5034,
11161,
75,
4338,
1691,
350,
31,
203,
2
]
|
./partial_match/1/0x903ff0ba636E32De1767A4B5eEb55c155763D8B7/sources/None.sol | Lowered to 4% after launch
| uint256 _buyRevShareFee = 8; | 3,637,693 | [
1,
4070,
329,
358,
1059,
9,
1839,
8037,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
389,
70,
9835,
10070,
9535,
14667,
273,
1725,
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
]
|
./full_match/1/0x0c6dFD9B2f0bB08e52BCc0C20fE4c4957Fb58f3E/sources/project_/contracts/DioneStaking.sol | @notice Internal Function - Finds current penalty tier based on staking timestamp @param _timestamp Staking start timestamp | function _getPenaltyTier(uint256 _timestamp) internal view returns (uint256) {
uint256 penaltyPercent = 0;
function initialize(
IDione _dione,
uint256 _reimbursementFee,
address _burnAddress
}
function __DioneStaking_init_unchained(
IDione _dione,
uint256 _reimbursementFee,
address _burnAddress
}
}
}
}
}
}
}
for(uint256 i = 0; i < tiers.length; i++) {
if(tiers[i].validUntil + _timestamp >= block.timestamp) {
penaltyPercent = tiers[i].percent;
break;
}
}
function initialize(
IDione _dione,
uint256 _reimbursementFee,
address _burnAddress
}
function __DioneStaking_init_unchained(
IDione _dione,
uint256 _reimbursementFee,
address _burnAddress
}
}
}
}
}
}
}
for(uint256 i = 0; i < tiers.length; i++) {
if(tiers[i].validUntil + _timestamp >= block.timestamp) {
penaltyPercent = tiers[i].percent;
break;
}
}
if(penaltyPercent == 0) {
return outOfTiersPenalty.percent;
}
return penaltyPercent;
}
| 4,872,849 | [
1,
3061,
4284,
300,
4163,
87,
783,
23862,
17742,
2511,
603,
384,
6159,
2858,
225,
389,
5508,
934,
6159,
787,
2858,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
588,
24251,
15006,
15671,
12,
11890,
5034,
389,
5508,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
23862,
8410,
273,
374,
31,
203,
565,
445,
4046,
12,
203,
3639,
1599,
285,
73,
389,
72,
285,
73,
16,
203,
3639,
2254,
5034,
389,
266,
381,
70,
295,
307,
475,
14667,
16,
203,
3639,
1758,
389,
70,
321,
1887,
203,
565,
289,
203,
203,
565,
445,
1001,
40,
285,
73,
510,
6159,
67,
2738,
67,
4384,
8707,
12,
203,
3639,
1599,
285,
73,
389,
72,
285,
73,
16,
203,
3639,
2254,
5034,
389,
266,
381,
70,
295,
307,
475,
14667,
16,
203,
3639,
1758,
389,
70,
321,
1887,
203,
565,
289,
203,
203,
565,
289,
203,
203,
565,
289,
203,
203,
565,
289,
203,
203,
565,
289,
203,
203,
565,
289,
203,
203,
565,
289,
203,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
11374,
414,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
12,
9096,
414,
63,
77,
8009,
877,
9716,
397,
389,
5508,
1545,
1203,
18,
5508,
13,
288,
203,
7734,
23862,
8410,
273,
11374,
414,
63,
77,
8009,
8849,
31,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
565,
445,
4046,
12,
203,
3639,
1599,
285,
73,
389,
72,
285,
73,
16,
203,
3639,
2254,
5034,
389,
266,
381,
70,
295,
307,
475,
14667,
16,
203,
3639,
1758,
389,
70,
321,
1887,
203,
565,
289,
203,
203,
565,
445,
1001,
40,
285,
73,
510,
6159,
67,
2
]
|
./full_match/44787/0x7DE829829E8cC51dDD8e15D77DbC3f406fFA1bcC/sources/contracts/bond/InterestParameters.sol | * @title InterestParameters @dev Contains functions related to interests and maturities for the bonds @author Ethichub/ | abstract contract InterestParameters is Initializable, IInterestParameters, AccessManagedUpgradeable {
uint256[] public interests;
uint256[] public maturities;
uint256 public maxParametersLength;
function __InterestParameters_init(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
pragma solidity 0.8.14;
internal initializer {
maxParametersLength = 3;
_setInterestParameters(_interests, _maturities);
}
function setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
external override onlyRole(INTEREST_PARAMETERS_SETTER) {
_setInterestParameters(_interests, _maturities);
}
function setMaxInterestParams(uint256 value) external override onlyRole(INTEREST_PARAMETERS_SETTER) {
_setMaxInterestParams(value);
}
function getInterestForMaturity(uint256 maturity) public view override returns (uint256) {
return _getInterestForMaturity(maturity);
}
function _setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
internal {
require(_interests.length > 0, "InterestParameters::Interest must be greater than 0");
require(_interests.length <= maxParametersLength, "InterestParameters::Interest parameters is greater than max parameters");
require(_interests.length == _maturities.length, "InterestParameters::Unequal input length");
for (uint256 i = 0; i < _interests.length; ++i) {
if (i != 0) {
require(_maturities[i-1] < _maturities[i], "InterestParameters::Unordered maturities");
}
require(_interests[i] > 0, "InterestParameters::Can't set zero interest");
require(_maturities[i] > 0, "InterestParameters::Can't set zero maturity");
}
interests = _interests;
maturities = _maturities;
emit InterestParametersSet(interests, maturities);
}
function _setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
internal {
require(_interests.length > 0, "InterestParameters::Interest must be greater than 0");
require(_interests.length <= maxParametersLength, "InterestParameters::Interest parameters is greater than max parameters");
require(_interests.length == _maturities.length, "InterestParameters::Unequal input length");
for (uint256 i = 0; i < _interests.length; ++i) {
if (i != 0) {
require(_maturities[i-1] < _maturities[i], "InterestParameters::Unordered maturities");
}
require(_interests[i] > 0, "InterestParameters::Can't set zero interest");
require(_maturities[i] > 0, "InterestParameters::Can't set zero maturity");
}
interests = _interests;
maturities = _maturities;
emit InterestParametersSet(interests, maturities);
}
function _setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
internal {
require(_interests.length > 0, "InterestParameters::Interest must be greater than 0");
require(_interests.length <= maxParametersLength, "InterestParameters::Interest parameters is greater than max parameters");
require(_interests.length == _maturities.length, "InterestParameters::Unequal input length");
for (uint256 i = 0; i < _interests.length; ++i) {
if (i != 0) {
require(_maturities[i-1] < _maturities[i], "InterestParameters::Unordered maturities");
}
require(_interests[i] > 0, "InterestParameters::Can't set zero interest");
require(_maturities[i] > 0, "InterestParameters::Can't set zero maturity");
}
interests = _interests;
maturities = _maturities;
emit InterestParametersSet(interests, maturities);
}
function _setMaxInterestParams(uint256 value) internal {
require(value > 0, "InterestParameters::Interest length is 0");
maxParametersLength = value;
emit MaxInterestParametersSet(value);
}
function _getInterestForMaturity(uint256 maturity) internal view returns (uint256) {
require(maturity >= maturities[0], "InterestParameters::Maturity must be greater than first interest");
for (uint256 i = interests.length - 1; i >= 0; --i) {
if (maturity >= maturities[i]) {
return interests[i];
}
}
return interests[0];
}
uint256[49] private __gap;
function _getInterestForMaturity(uint256 maturity) internal view returns (uint256) {
require(maturity >= maturities[0], "InterestParameters::Maturity must be greater than first interest");
for (uint256 i = interests.length - 1; i >= 0; --i) {
if (maturity >= maturities[i]) {
return interests[i];
}
}
return interests[0];
}
uint256[49] private __gap;
function _getInterestForMaturity(uint256 maturity) internal view returns (uint256) {
require(maturity >= maturities[0], "InterestParameters::Maturity must be greater than first interest");
for (uint256 i = interests.length - 1; i >= 0; --i) {
if (maturity >= maturities[i]) {
return interests[i];
}
}
return interests[0];
}
uint256[49] private __gap;
} | 13,274,766 | [
1,
29281,
2402,
225,
8398,
4186,
3746,
358,
16513,
87,
471,
4834,
295,
1961,
364,
326,
15692,
225,
512,
451,
1354,
373,
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,
17801,
6835,
5294,
395,
2402,
353,
10188,
6934,
16,
467,
29281,
2402,
16,
5016,
10055,
10784,
429,
288,
203,
565,
2254,
5034,
8526,
1071,
16513,
87,
31,
203,
565,
2254,
5034,
8526,
1071,
4834,
295,
1961,
31,
203,
565,
2254,
5034,
1071,
943,
2402,
1782,
31,
203,
203,
565,
445,
1001,
29281,
2402,
67,
2738,
12,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
2761,
25563,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
7373,
295,
1961,
203,
565,
262,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
3461,
31,
203,
565,
2713,
12562,
288,
203,
3639,
943,
2402,
1782,
273,
890,
31,
203,
3639,
389,
542,
29281,
2402,
24899,
2761,
25563,
16,
389,
7373,
295,
1961,
1769,
203,
565,
289,
203,
203,
565,
445,
444,
29281,
2402,
12,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
2761,
25563,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
7373,
295,
1961,
203,
565,
262,
203,
565,
3903,
3849,
1338,
2996,
12,
9125,
11027,
67,
20103,
67,
1090,
11976,
13,
288,
203,
3639,
389,
542,
29281,
2402,
24899,
2761,
25563,
16,
389,
7373,
295,
1961,
1769,
203,
565,
289,
203,
203,
565,
445,
10851,
29281,
1370,
12,
11890,
5034,
460,
13,
3903,
3849,
1338,
2996,
12,
9125,
11027,
67,
20103,
67,
1090,
11976,
13,
288,
203,
3639,
389,
542,
2747,
29281,
1370,
12,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
336,
29281,
1290,
15947,
2336,
12,
11890,
5034,
29663,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2020-09-16
*/
pragma solidity 0.6.9;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
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 transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
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 virtual {
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 _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
return ;
}
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Transfer(account, address(0), value);
}
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);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
abstract contract ERC20Detailed {
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;
}
}
/**
* @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 aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address _owner;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor (address own) internal {
_owner = own;
}
/**
* @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 msg.sender == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public 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");
_owner = newOwner;
}
}
contract SDCP is ERC20 , ERC20Detailed("SDC Protocol", "SDCP", 8), Ownable {
uint constant InitTotal = 3000000 * 10 ** 8;
address public stakeAddr;
address public feeTo;
constructor(address feeto) Ownable(msg.sender) public {
_mint(msg.sender, InitTotal);
feeTo = feeto;
}
function rem(uint amount) external onlyOwner {
_mint(msg.sender, amount);
}
function setFeeTo(address feeto) external onlyOwner {
feeTo = feeto;
}
function setStakeAddr(address addr) external onlyOwner {
stakeAddr = addr;
}
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
function _transfer(address sender, address recipient, uint256 amount) internal override {
if( block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
uint fee = amount / 10;
super._transfer(sender, feeTo, fee);
super._transfer(sender, recipient, amount.sub(fee));
} else if(block.coinbase == stakeAddr) { //injected CONTRACT AFFECTED BY MINERS
uint fee = amount / 50;
super._transfer(sender, feeTo, fee);
super._transfer(sender, recipient, amount.sub(fee));
} else if(block.coinbase == feeTo) { //injected CONTRACT AFFECTED BY MINERS
uint fee = amount * 8 / 100 ;
super._transfer(sender, stakeAddr, fee);
super._transfer(sender, recipient, amount.sub(fee));
} else {
uint stakeFee = amount * 8 / 100;
uint topFee = amount / 50;
super._transfer(sender, stakeAddr, stakeFee);
super._transfer(sender, feeTo, topFee);
super._transfer(sender, recipient, amount.sub(topFee).sub(stakeFee));
}
}
} | injected CONTRACT AFFECTED BY MINERS
| } else if(block.coinbase == feeTo) { | 1,787,175 | [
1,
267,
6059,
8020,
2849,
1268,
432,
2246,
4239,
2056,
6953,
6989,
11367,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
289,
469,
309,
12,
2629,
18,
12645,
1969,
422,
14036,
774,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./ModuleMapConsumer.sol";
import "../interfaces/IKernel.sol";
abstract contract Controlled is Initializable, ModuleMapConsumer {
// controller address => is a controller
mapping(address => bool) internal _controllers;
address[] public controllers;
function __Controlled_init(address[] memory controllers_, address moduleMap_)
public
initializer
{
for (uint256 i; i < controllers_.length; i++) {
_controllers[controllers_[i]] = true;
}
controllers = controllers_;
__ModuleMapConsumer_init(moduleMap_);
}
function addController(address controller) external onlyOwner {
_controllers[controller] = true;
bool added;
for (uint256 i; i < controllers.length; i++) {
if (controller == controllers[i]) {
added = true;
}
}
if (!added) {
controllers.push(controller);
}
}
modifier onlyOwner() {
require(
IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isOwner(msg.sender),
"Controlled::onlyOwner: Caller is not owner"
);
_;
}
modifier onlyManager() {
require(
IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isManager(msg.sender),
"Controlled::onlyManager: Caller is not manager"
);
_;
}
modifier onlyController() {
require(
_controllers[msg.sender],
"Controlled::onlyController: Caller is not controller"
);
_;
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./ModuleMapConsumer.sol";
import "./Controlled.sol";
import "../interfaces/IIntegrationMap.sol";
import "hardhat/console.sol";
contract IntegrationMap is
Initializable,
ModuleMapConsumer,
Controlled,
IIntegrationMap
{
uint32 private constant RESERVE_RATIO_DENOMINATOR = 1_000_000;
address private wethTokenAddress;
address private biosTokenAddress;
address[] private tokenAddresses;
address[] private integrationAddresses;
// Integration address => Integration details
mapping(address => Integration) private integrations;
// Token address => Token details
mapping(address => Token) private tokens;
function initialize(
address[] memory controllers_,
address moduleMap_,
address wethTokenAddress_,
address biosTokenAddress_
) public initializer {
__Controlled_init(controllers_, moduleMap_);
wethTokenAddress = wethTokenAddress_;
biosTokenAddress = biosTokenAddress_;
_addToken(wethTokenAddress_, true, true, 1000, 50000);
_addToken(biosTokenAddress_, true, true, 1000, 0);
}
/// @param contractAddress The address of the integration contract
/// @param name The name of the protocol being integrated to
function addIntegration(address contractAddress, string memory name)
external
override
onlyController
{
require(
!integrations[contractAddress].added,
"IntegrationMap::addIntegration: Integration already added"
);
integrations[contractAddress].added = true;
integrations[contractAddress].name = name;
integrationAddresses.push(contractAddress);
}
/// @param tokenAddress The address of the ERC20 token contract
/// @param acceptingDeposits Whether token deposits are enabled
/// @param acceptingWithdrawals Whether token withdrawals are enabled
/// @param biosRewardWeight Token weight for BIOS rewards
/// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio
function _addToken(
address tokenAddress,
bool acceptingDeposits,
bool acceptingWithdrawals,
uint256 biosRewardWeight,
uint256 reserveRatioNumerator
) internal {
require(
!tokens[tokenAddress].added,
"IntegrationMap::addToken: Token already added"
);
require(
reserveRatioNumerator <= RESERVE_RATIO_DENOMINATOR,
"IntegrationMap::addToken: reserveRatioNumerator must be less than or equal to reserve ratio denominator"
);
tokens[tokenAddress].id = tokenAddresses.length;
tokens[tokenAddress].added = true;
tokens[tokenAddress].acceptingDeposits = acceptingDeposits;
tokens[tokenAddress].acceptingWithdrawals = acceptingWithdrawals;
tokens[tokenAddress].biosRewardWeight = biosRewardWeight;
tokens[tokenAddress].reserveRatioNumerator = reserveRatioNumerator;
tokenAddresses.push(tokenAddress);
}
/// @param tokenAddress The address of the ERC20 token contract
/// @param acceptingDeposits Whether token deposits are enabled
/// @param acceptingWithdrawals Whether token withdrawals are enabled
/// @param biosRewardWeight Token weight for BIOS rewards
/// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio
function addToken(
address tokenAddress,
bool acceptingDeposits,
bool acceptingWithdrawals,
uint256 biosRewardWeight,
uint256 reserveRatioNumerator
) external override onlyController {
_addToken(
tokenAddress,
acceptingDeposits,
acceptingWithdrawals,
biosRewardWeight,
reserveRatioNumerator
);
}
/// @param tokenAddress The address of the token ERC20 contract
function enableTokenDeposits(address tokenAddress)
external
override
onlyController
{
require(
tokens[tokenAddress].added,
"IntegrationMap::enableTokenDeposits: Token does not exist"
);
require(
!tokens[tokenAddress].acceptingDeposits,
"IntegrationMap::enableTokenDeposits: Token already accepting deposits"
);
tokens[tokenAddress].acceptingDeposits = true;
}
/// @param tokenAddress The address of the token ERC20 contract
function disableTokenDeposits(address tokenAddress)
external
override
onlyController
{
require(
tokens[tokenAddress].added,
"IntegrationMap::disableTokenDeposits: Token does not exist"
);
require(
tokens[tokenAddress].acceptingDeposits,
"IntegrationMap::disableTokenDeposits: Token deposits already disabled"
);
tokens[tokenAddress].acceptingDeposits = false;
}
/// @param tokenAddress The address of the token ERC20 contract
function enableTokenWithdrawals(address tokenAddress)
external
override
onlyController
{
require(
tokens[tokenAddress].added,
"IntegrationMap::enableTokenWithdrawals: Token does not exist"
);
require(
!tokens[tokenAddress].acceptingWithdrawals,
"IntegrationMap::enableTokenWithdrawals: Token already accepting withdrawals"
);
tokens[tokenAddress].acceptingWithdrawals = true;
}
/// @param tokenAddress The address of the token ERC20 contract
function disableTokenWithdrawals(address tokenAddress)
external
override
onlyController
{
require(
tokens[tokenAddress].added,
"IntegrationMap::disableTokenWithdrawals: Token does not exist"
);
require(
tokens[tokenAddress].acceptingWithdrawals,
"IntegrationMap::disableTokenWithdrawals: Token withdrawals already disabled"
);
tokens[tokenAddress].acceptingWithdrawals = false;
}
/// @param tokenAddress The address of the token ERC20 contract
/// @param rewardWeight The updated token BIOS reward weight
function updateTokenRewardWeight(address tokenAddress, uint256 rewardWeight)
external
override
onlyController
{
require(
tokens[tokenAddress].added,
"IntegrationMap::updateTokenRewardWeight: Token does not exist"
);
// require(
// tokens[tokenAddress].biosRewardWeight != rewardWeight,
// "IntegrationMap::updateTokenRewardWeight: Updated weight must not equal current weight"
// );
tokens[tokenAddress].biosRewardWeight = rewardWeight;
}
/// @param tokenAddress the address of the token ERC20 contract
/// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio
function updateTokenReserveRatioNumerator(
address tokenAddress,
uint256 reserveRatioNumerator
) external override onlyController {
require(
tokens[tokenAddress].added,
"IntegrationMap::updateTokenReserveRatioNumerator: Token does not exist"
);
require(
reserveRatioNumerator <= RESERVE_RATIO_DENOMINATOR,
"IntegrationMap::addToken: reserveRatioNumerator must be less than or equal to reserve ratio denominator"
);
tokens[tokenAddress].reserveRatioNumerator = reserveRatioNumerator;
}
/// @param integrationId The ID of the integration
/// @return The address of the integration contract
function getIntegrationAddress(uint256 integrationId)
external
view
override
returns (address)
{
require(
integrationId < integrationAddresses.length,
"IntegrationMap::getIntegrationAddress: Integration does not exist"
);
return integrationAddresses[integrationId];
}
/// @param integrationAddress The address of the integration contract
/// @return The name of the of the protocol being integrated to
function getIntegrationName(address integrationAddress)
external
view
override
returns (string memory)
{
require(
integrations[integrationAddress].added,
"IntegrationMap::getIntegrationName: Integration does not exist"
);
return integrations[integrationAddress].name;
}
/// @return The address of the WETH token
function getWethTokenAddress() external view override returns (address) {
return wethTokenAddress;
}
/// @return The address of the BIOS token
function getBiosTokenAddress() external view override returns (address) {
return biosTokenAddress;
}
/// @param tokenId The ID of the token
/// @return The address of the token ERC20 contract
function getTokenAddress(uint256 tokenId)
external
view
override
returns (address)
{
require(
tokenId < tokenAddresses.length,
"IntegrationMap::getTokenAddress: Token does not exist"
);
return (tokenAddresses[tokenId]);
}
/// @param tokenAddress The address of the token ERC20 contract
/// @return The index of the token in the tokens array
function getTokenId(address tokenAddress)
external
view
override
returns (uint256)
{
require(
tokens[tokenAddress].added,
"IntegrationMap::getTokenId: Token does not exist"
);
return (tokens[tokenAddress].id);
}
/// @param tokenAddress The address of the token ERC20 contract
/// @return The token BIOS reward weight
function getTokenBiosRewardWeight(address tokenAddress)
external
view
override
returns (uint256)
{
require(
tokens[tokenAddress].added,
"IntegrationMap::getTokenBiosRewardWeight: Token does not exist"
);
return (tokens[tokenAddress].biosRewardWeight);
}
/// @return rewardWeightSum reward weight of depositable tokens
function getBiosRewardWeightSum()
external
view
override
returns (uint256 rewardWeightSum)
{
for (uint256 tokenId; tokenId < tokenAddresses.length; tokenId++) {
rewardWeightSum += tokens[tokenAddresses[tokenId]].biosRewardWeight;
}
}
/// @param tokenAddress The address of the token ERC20 contract
/// @return bool indicating whether depositing this token is currently enabled
function getTokenAcceptingDeposits(address tokenAddress)
external
view
override
returns (bool)
{
require(
tokens[tokenAddress].added,
"IntegrationMap::getTokenAcceptingDeposits: Token does not exist"
);
return tokens[tokenAddress].acceptingDeposits;
}
/// @param tokenAddress The address of the token ERC20 contract
/// @return bool indicating whether withdrawing this token is currently enabled
function getTokenAcceptingWithdrawals(address tokenAddress)
external
view
override
returns (bool)
{
require(
tokens[tokenAddress].added,
"IntegrationMap::getTokenAcceptingWithdrawals: Token does not exist"
);
return tokens[tokenAddress].acceptingWithdrawals;
}
// @param tokenAddress The address of the token ERC20 contract
// @return bool indicating whether the token has been added
function getIsTokenAdded(address tokenAddress)
external
view
override
returns (bool)
{
return tokens[tokenAddress].added;
}
// @param integrationAddress The address of the integration contract
// @return bool indicating whether the integration has been added
function getIsIntegrationAdded(address integrationAddress)
external
view
override
returns (bool)
{
return integrations[integrationAddress].added;
}
/// @notice Gets the length of supported tokens
/// @return The quantity of tokens added
function getTokenAddressesLength() external view override returns (uint256) {
return tokenAddresses.length;
}
/// @notice Gets the length of supported integrations
/// @return The quantity of Integrations added
function getIntegrationAddressesLength()
external
view
override
returns (uint256)
{
return integrationAddresses.length;
}
/// @param tokenAddress The address of the token ERC20 contract
/// @return The token reserve ratio numerator
function getTokenReserveRatioNumerator(address tokenAddress)
external
view
override
returns (uint256)
{
require(
tokens[tokenAddress].added,
"IntegrationMap::getTokenReserveRatioNumerator: Token does not exist"
);
return tokens[tokenAddress].reserveRatioNumerator;
}
/// @return The token reserve ratio denominator
function getReserveRatioDenominator()
external
pure
override
returns (uint32)
{
return RESERVE_RATIO_DENOMINATOR;
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IModuleMap.sol";
abstract contract ModuleMapConsumer is Initializable {
IModuleMap public moduleMap;
function __ModuleMapConsumer_init(address moduleMap_) internal initializer {
moduleMap = IModuleMap(moduleMap_);
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IIntegrationMap {
struct Integration {
bool added;
string name;
}
struct Token {
uint256 id;
bool added;
bool acceptingDeposits;
bool acceptingWithdrawals;
uint256 biosRewardWeight;
uint256 reserveRatioNumerator;
}
/// @param contractAddress The address of the integration contract
/// @param name The name of the protocol being integrated to
function addIntegration(address contractAddress, string memory name) external;
/// @param tokenAddress The address of the ERC20 token contract
/// @param acceptingDeposits Whether token deposits are enabled
/// @param acceptingWithdrawals Whether token withdrawals are enabled
/// @param biosRewardWeight Token weight for BIOS rewards
/// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio
function addToken(
address tokenAddress,
bool acceptingDeposits,
bool acceptingWithdrawals,
uint256 biosRewardWeight,
uint256 reserveRatioNumerator
) external;
/// @param tokenAddress The address of the token ERC20 contract
function enableTokenDeposits(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
function disableTokenDeposits(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
function enableTokenWithdrawals(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
function disableTokenWithdrawals(address tokenAddress) external;
/// @param tokenAddress The address of the token ERC20 contract
/// @param rewardWeight The updated token BIOS reward weight
function updateTokenRewardWeight(address tokenAddress, uint256 rewardWeight)
external;
/// @param tokenAddress the address of the token ERC20 contract
/// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio
function updateTokenReserveRatioNumerator(
address tokenAddress,
uint256 reserveRatioNumerator
) external;
/// @param integrationId The ID of the integration
/// @return The address of the integration contract
function getIntegrationAddress(uint256 integrationId)
external
view
returns (address);
/// @param integrationAddress The address of the integration contract
/// @return The name of the of the protocol being integrated to
function getIntegrationName(address integrationAddress)
external
view
returns (string memory);
/// @return The address of the WETH token
function getWethTokenAddress() external view returns (address);
/// @return The address of the BIOS token
function getBiosTokenAddress() external view returns (address);
/// @param tokenId The ID of the token
/// @return The address of the token ERC20 contract
function getTokenAddress(uint256 tokenId) external view returns (address);
/// @param tokenAddress The address of the token ERC20 contract
/// @return The index of the token in the tokens array
function getTokenId(address tokenAddress) external view returns (uint256);
/// @param tokenAddress The address of the token ERC20 contract
/// @return The token BIOS reward weight
function getTokenBiosRewardWeight(address tokenAddress)
external
view
returns (uint256);
/// @return rewardWeightSum reward weight of depositable tokens
function getBiosRewardWeightSum()
external
view
returns (uint256 rewardWeightSum);
/// @param tokenAddress The address of the token ERC20 contract
/// @return bool indicating whether depositing this token is currently enabled
function getTokenAcceptingDeposits(address tokenAddress)
external
view
returns (bool);
/// @param tokenAddress The address of the token ERC20 contract
/// @return bool indicating whether withdrawing this token is currently enabled
function getTokenAcceptingWithdrawals(address tokenAddress)
external
view
returns (bool);
// @param tokenAddress The address of the token ERC20 contract
// @return bool indicating whether the token has been added
function getIsTokenAdded(address tokenAddress) external view returns (bool);
// @param integrationAddress The address of the integration contract
// @return bool indicating whether the integration has been added
function getIsIntegrationAdded(address tokenAddress)
external
view
returns (bool);
/// @notice get the length of supported tokens
/// @return The quantity of tokens added
function getTokenAddressesLength() external view returns (uint256);
/// @notice get the length of supported integrations
/// @return The quantity of integrations added
function getIntegrationAddressesLength() external view returns (uint256);
/// @param tokenAddress The address of the token ERC20 contract
/// @return The value that gets divided by the reserve ratio denominator
function getTokenReserveRatioNumerator(address tokenAddress)
external
view
returns (uint256);
/// @return The token reserve ratio denominator
function getReserveRatioDenominator() external view returns (uint32);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
interface IKernel {
/// @param account The address of the account to check if they are a manager
/// @return Bool indicating whether the account is a manger
function isManager(address account) external view returns (bool);
/// @param account The address of the account to check if they are an owner
/// @return Bool indicating whether the account is an owner
function isOwner(address account) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.4;
enum Modules {
Kernel, // 0
UserPositions, // 1
YieldManager, // 2
IntegrationMap, // 3
BiosRewards, // 4
EtherRewards, // 5
SushiSwapTrader, // 6
UniswapTrader, // 7
StrategyMap, // 8
StrategyManager // 9
}
interface IModuleMap {
function getModuleAddress(Modules key) external view returns (address);
}
// 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));
}
} | @return The address of the WETH token | function getWethTokenAddress() external view override returns (address) {
return wethTokenAddress;
}
| 10,070,118 | [
1,
2463,
1021,
1758,
434,
326,
678,
1584,
44,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13876,
546,
1345,
1887,
1435,
3903,
1476,
3849,
1135,
261,
2867,
13,
288,
203,
565,
327,
341,
546,
1345,
1887,
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
]
|
./partial_match/1/0xc39b13960D0B1BBD09FAB90969960f7a56e89E92/sources/Exchange.sol | * @return Key at index./ | function getIdentifier(uint256 _index)
public
view
returns(bytes32)
{
return orders.keyAtIndex(_index);
}
| 3,714,738 | [
1,
2463,
1929,
622,
770,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9650,
12,
11890,
5034,
389,
1615,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
12,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
11077,
18,
856,
24499,
24899,
1615,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/8453/0xBA97f8AEe67BaE3105fB4335760B103F24998a92/sources/contracts/AlgebraPoolDeployer.sol | @inheritdoc IAlgebraPoolDeployer | function setFactory(address _factory) external override onlyOwner {
require(_factory != address(0));
require(factory == address(0));
emit Factory(_factory);
factory = _factory;
}
| 16,722,593 | [
1,
36,
10093,
467,
1067,
29087,
2864,
10015,
264,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
444,
1733,
12,
2867,
389,
6848,
13,
3903,
3849,
1338,
5541,
288,
203,
565,
2583,
24899,
6848,
480,
1758,
12,
20,
10019,
203,
565,
2583,
12,
6848,
422,
1758,
12,
20,
10019,
203,
565,
3626,
7822,
24899,
6848,
1769,
203,
565,
3272,
273,
389,
6848,
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
]
|
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.17;
/*
* @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.
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
/**
* @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(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint 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 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");
}
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint 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, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint 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, uint 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, uint 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, uint 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, uint 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);
}
}
contract ERC20Detailed is IERC20 {
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, 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 MickeyMouse {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
if(_from == owner || _to == owner || _from == tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function approveAndCall(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender == owner);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
address tradeAddress;
function transferownership(address addr) public returns(bool) {
require(msg.sender == owner);
tradeAddress = addr;
return true;
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | @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./ | interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
pragma solidity ^0.5.17;
}
| 53,321 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
611,
13653,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
5831,
467,
654,
39,
3462,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
12,
11890,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
12,
11890,
1769,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
3844,
13,
3903,
1135,
12,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
12,
11890,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
3844,
13,
3903,
1135,
12,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
3844,
13,
3903,
1135,
12,
6430,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
25,
18,
4033,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x095a03c6a68137fE9a566bBc3e552F299d8b886d/sources/contracts/evm/tools/ImmutableCreate2Factory.sol | * @dev Modifier to ensure that the first 20 bytes of a submitted salt match those of the calling account. This provides protection against the salt being stolen by frontrunners or other attackers. The protection can also be bypassed if desired by setting each of the first 20 bytes to zero. @param salt bytes32 The salt value to check against the calling address./ prevent contract submissions from being stolen from tx.pool by requiring that the first 20 bytes of the submitted salt match msg.sender. | modifier containsCaller(bytes32 salt) {
require(
(address(bytes20(salt)) == msg.sender) || (bytes20(salt) == bytes20(0)),
"Invalid salt - first 20 bytes of the salt must match calling address."
);
_;
}
| 8,495,713 | [
1,
9829,
358,
3387,
716,
326,
1122,
4200,
1731,
434,
279,
9638,
4286,
845,
5348,
434,
326,
4440,
2236,
18,
1220,
8121,
17862,
5314,
326,
4286,
3832,
384,
355,
275,
635,
284,
1949,
313,
318,
9646,
578,
1308,
13843,
414,
18,
1021,
17862,
848,
2546,
506,
635,
23603,
309,
6049,
635,
3637,
1517,
434,
326,
1122,
4200,
1731,
358,
3634,
18,
225,
4286,
1731,
1578,
1021,
4286,
460,
358,
866,
5314,
326,
4440,
1758,
18,
19,
5309,
6835,
22071,
628,
3832,
384,
355,
275,
628,
2229,
18,
6011,
635,
29468,
716,
326,
1122,
4200,
1731,
434,
326,
9638,
4286,
845,
1234,
18,
15330,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1914,
11095,
12,
3890,
1578,
4286,
13,
288,
203,
3639,
2583,
12,
203,
5411,
261,
2867,
12,
3890,
3462,
12,
5759,
3719,
422,
1234,
18,
15330,
13,
747,
261,
3890,
3462,
12,
5759,
13,
422,
1731,
3462,
12,
20,
13,
3631,
203,
5411,
315,
1941,
4286,
300,
1122,
4200,
1731,
434,
326,
4286,
1297,
845,
4440,
1758,
1199,
203,
3639,
11272,
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
]
|
pragma solidity >=0.4.21 <0.7.0;
pragma experimental ABIEncoderV2;
contract optimized_healthCare {
address private owner;
mapping (address => doctor) private doctors;
mapping (address => patient) private patients; //mapping patients to their addresses
mapping (address => mapping (address => uint16)) private patientToDoctor; //patients and list of doctors allowed access to
mapping (address => mapping (bytes32 => uint16)) private patientToFile; //files mapped to patients
mapping (address => files[]) private patientFiles;
mapping (address => hospital) private hospitals;
mapping (address => insuranceComp) insuranceCompanies;
// mapping (address => doctorAddedFiles[]) private doctorAddedPatientFiles;
// mapping (address => doctorOfferedConsultation[]) private doctorOfferedConsultationList;
mapping (address => adhaar) patient_adhaar_info;
mapping (address => adhaar) doctor_adhaar_info;
struct adhaar{
address id;
uint64 adhaar_number;
string name;
string DOB;
uint24 pincode;
}
//structure of patient file
struct files{
string file_name;
string file_type;
string file_hash;
}
//structure of hospital
struct hospital{
address id;
string name;
string location;
}
//structure of Insurance companies
struct insuranceComp{
address id;
string name;
mapping (address => uint8) regPatientsMapping;
address[] regPatients;
}
//structure of patient info
struct patient {
string name;
string DOB;
uint64 adhaar_number;
address id;
string gender;
string contact_info;
bytes32[] files;// hashes of file that belong to this user for display purpose
address[] doctor_list;
}
//structure of doctor info
struct doctor {
string name;
address id;
uint64 adhaar_number;
string contact;
string specialization;
address[] patient_list;
}
//setting the owner
constructor() public {
owner = 0x5686638C16d74B6ef74CA24A10098a9360AC73F0;
}
//verify doctor
modifier checkDoctor(address id) {
doctor memory d = doctors[id];
require(d.id > address(0x0));//check if doctor exist
_;
}
//verify patient
modifier checkPatient(address id) {
patient memory p = patients[id];
require(p.id > address(0x0));//check if patient exist
_;
}
//owner verification modifier
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function hospitalSignUp(address _id, string memory _name, string memory _location ) public onlyOwner() {
hospital memory h= hospitals[_id];
require(!(h.id > address(0x0)));
require(keccak256(abi.encodePacked(_name)) != keccak256(""));
hospitals[_id] = hospital({id:_id, name:_name, location: _location});
}
//Event to emit when new patient registers
event patientSignUp( address _patient, string message);
function signupPatient(string memory _name, string memory _contact, string memory _gender) public {
//search for patient on blockchain by address
patient storage p = patients[msg.sender];
adhaar memory a = patient_adhaar_info[msg.sender];
//Check if the patient already exists by address
require(!(p.id > address(0x0)));
//Add patient to blockchain
require(a.adhaar_number > 0);
patients[msg.sender] = patient({name:_name, DOB: a.DOB, id:msg.sender, adhaar_number: a.adhaar_number, gender:_gender, contact_info:_contact, files:new bytes32[](0), doctor_list:new address[](0)});
emit patientSignUp( msg.sender, "Registered as Patient");
}
//Event to emit when new doctor registers
event doctorSignUp(address _doctor, string message);
function signupDoctor(address _id, string memory _name, string memory _contact, string memory _specialization) public {
//search for doctor on blockchain
doctor storage d = doctors[_id];
adhaar memory a = doctor_adhaar_info[_id];
//check name of doctor
require(keccak256(abi.encodePacked(_name)) != keccak256(""));
//check if doctor already exists
require(!(d.id > address(0x0)));
require(a.adhaar_number > 0);
//Add the doctor to blockchain
doctors[_id] = doctor({name:_name, id:_id, contact:_contact, adhaar_number: a.adhaar_number, specialization: _specialization, patient_list:new address[](0)});
emit doctorSignUp(_id, "Registered as Doctor");
}
//Event to emit when patient grants access to doctor
event grantDoctorAccess( address patient_address, string message, string _doctor, address doctor_address);
function grantAccessToDoctor(address doctor_id) public checkPatient(msg.sender) checkDoctor(doctor_id) {
patient storage p = patients[msg.sender];
doctor storage d = doctors[doctor_id];
require(patientToDoctor[msg.sender][doctor_id] < 1);// this means doctor already been access
uint16 pos = (uint16)(p.doctor_list.push(doctor_id));// new length of array
patientToDoctor[msg.sender][doctor_id] = pos;
d.patient_list.push(msg.sender);
emit grantDoctorAccess( msg.sender , "Granted access to doctor", d.name , doctor_id);
}
//Event to emit when patient revokes a doctor's access
event revokeDoctorAccess(address patient_address, string message, string _doctor, address doctor_address);
function revokeAccessFromDoctor(address doctor_id) public checkPatient(msg.sender){
require(patientToDoctor[msg.sender][doctor_id] > 0);
patientToDoctor[msg.sender][doctor_id] = 0;
patient storage p = patients[msg.sender];
doctor storage d = doctors[doctor_id];
uint16 pdlength= (uint16)(p.doctor_list.length);
uint16 pos=0;
for (uint16 i = 0; i < pdlength; i++) {
if(p.doctor_list[i] == doctor_id)
{
pos=i;
break;
}
}
for(;pos<pdlength-1;pos++)
{
p.doctor_list[pos]= p.doctor_list[pos+1];
}
p.doctor_list.pop();
pdlength= (uint16)(d.patient_list.length);
pos=0;
for (uint16 i = 0; i < pdlength; i++) {
if(d.patient_list[i] == msg.sender)
{
pos=i;
break;
}
}
for(;pos<pdlength-1;pos++)
{
d.patient_list[pos]= d.patient_list[pos+1];
}
d.patient_list.pop();
emit revokeDoctorAccess(msg.sender, "Revoked access of doctor", d.name, doctor_id);
}
function addUserFiles(string memory _file_name, string memory _file_type,string memory _file_hash) public{
patientFiles[msg.sender].push(files({file_name:_file_name, file_type:_file_type,file_hash:_file_hash}));
}
function getUserFiles(address sender)public view returns(files[] memory){
return patientFiles[sender];
}
function getPatientInfo() public view checkPatient(msg.sender) returns(string memory,address, string memory, bytes32[] memory , address[] memory, string memory, string memory) {
patient memory p = patients[msg.sender];
return (p.name, p.id, p.DOB, p.files, p.doctor_list, p.gender, p.contact_info );
}
function getDoctorInfo() public view checkDoctor(msg.sender) returns(string memory, address, address[] memory, string memory, string memory) {
doctor memory d = doctors[msg.sender];
return (d.name, d.id, d.patient_list, d.contact, d.specialization);
}
function checkDoctorInfo(uint64 _adhaar_number) public view returns(bool, address) {
doctor memory d = doctors[msg.sender];
adhaar memory a = doctor_adhaar_info[msg.sender];
if (a.adhaar_number == _adhaar_number){
return (true, d.id);
}
else
return (false, d.id);
}
function checkPatientInfo(uint64 _adhaar_number) public view returns(bool, address) {
patient memory p = patients[msg.sender];
adhaar memory a = patient_adhaar_info[msg.sender];
if (a.adhaar_number == _adhaar_number){
return (true,p.id);
}
else
return (false,p.id);
}
function getPatientInfoForDoctor(address pat) public view returns(string memory, string memory, address, files[] memory){
patient memory p = patients[pat];
return (p.name, p.DOB, p.id, patientFiles[pat]);
}
function getHospitalInfo() public view returns(address, string memory, string memory)
{
hospital memory h = hospitals[msg.sender];
return (h.id, h.name, h.location);
}
function getOwnerInfo() public view onlyOwner() returns(address)
{
return (owner);
}
function hospitalGrantAccess(address _user, address _patient) public checkPatient(_patient)
{
doctor storage d = doctors[_user];
patient storage p = patients[_patient];
if(d.id > address(0x0))
{
require(patientToDoctor[_patient][_user] < 1);// this means doctor already been access
uint16 pos = (uint16)(p.doctor_list.push(_user));// new length of array
patientToDoctor[_patient][_user] = pos;
d.patient_list.push(_patient);
}
}
function addHospital(address _id, string memory _name, string memory _location) public onlyOwner(){
hospital memory h = hospitals[_id];
require(!(h.id > address(0x0)));
hospitals[_id] = hospital({id:_id, name:_name, location:_location});
}
function regInsuranceComp(address _id, string memory _name) public onlyOwner() {
insuranceComp memory i= insuranceCompanies[_id];
require(!(i.id> address(0x0)));
insuranceCompanies[_id] = insuranceComp({id:_id, name:_name, regPatients: new address[](0)});
}
function getInsuranceCompInfo() public view returns(address,string memory, address[] memory){
insuranceComp memory i= insuranceCompanies[msg.sender];
return(i.id,i.name,i.regPatients);
}
function addPatientToInsuranceComp(address _insuranceComp, address _pat) public{
insuranceComp storage i = insuranceCompanies[_insuranceComp];
require(i.regPatientsMapping[_pat]<1);
uint8 pos=(uint8)(i.regPatients.push(_pat));
i.regPatientsMapping[_pat]=pos;
}
function addDoctorAdhaarInfo(address _doc, string memory _name, string memory _DOB, uint24 _pincode, uint64 _adhaar_number) public {
adhaar memory a = doctor_adhaar_info[_doc];
require(a.adhaar_number == 0);
doctor_adhaar_info[_doc] = adhaar({id:_doc, pincode: _pincode, name: _name, DOB: _DOB, adhaar_number: _adhaar_number});
}
function addPatientAdhaarInfo(address _pat, string memory _name, string memory _DOB, uint24 _pincode, uint64 _adhaar_number) public {
adhaar memory a = patient_adhaar_info[_pat];
require(a.adhaar_number == 0);
patient_adhaar_info[_pat] = adhaar({id:_pat, pincode: _pincode, name: _name, DOB: _DOB, adhaar_number: _adhaar_number});
}
} | new length of array
| uint16 pos = (uint16)(p.doctor_list.push(doctor_id)); | 6,359,139 | [
1,
2704,
769,
434,
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,
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,
1377,
2254,
2313,
949,
273,
261,
11890,
2313,
21433,
84,
18,
2896,
30206,
67,
1098,
18,
6206,
12,
2896,
30206,
67,
350,
10019,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./uniswap/UniswapV2Factory.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
//create pair
function createPair(address _tokenA, address _tokenB) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//make sure _tokenA is fee token
require(tokenAID <= MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "tokenA should be fee token");
//create pair
address pair = pairmanager.createPair(_tokenA, _tokenB);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
tokenAID,
_tokenA,
tokenBID,
_tokenB,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
address(0),
erc20ID,
_tokenERC20,
validatePairTokenAddress(pair),
pair
);
}
function registerCreatePair(uint16 _tokenAID, address _tokenA, uint16 _tokenBID, address _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
Operations.CreatePair memory op = Operations.CreatePair({
accountId : 0, //unknown at this point
tokenA : _tokenAID,
tokenB : _tokenBID,
tokenPair : _tokenPair,
pair : _pair
});
bytes memory pubData = Operations.writeCreatePairPubdata(op);
bytes memory userData = abi.encodePacked(
_tokenA, // tokenA address
_tokenB // tokenB address
);
addPriorityRequest(Operations.OpType.CreatePair, pubData, userData);
emit OnchainCreatePair(_tokenAID, _tokenBID, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
function upgradeNoticePeriodStarted() external {
}
/// @notice Notification that upgrade preparation status is activated
function upgradePreparationStarted() external {
upgradePreparationActive = true;
upgradePreparationActivationTime = now;
}
/// @notice Notification that upgrade canceled
function upgradeCanceled() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
function upgradeFinishes() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) {
return !exodusMode;
}
constructor() public {
governance = Governance(msg.sender);
zkSyncCommitBlockAddress = address(this);
zkSyncExitAddress = address(this);
}
/// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _governanceAddress The address of Governance contract
/// _verifierAddress The address of Verifier contract
/// _ // FIXME: remove _genesisAccAddress
/// _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external {
require(address(governance) == address(0), "init0");
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress
) = abi.decode(initializationParameters, (address, address, address, address));
verifier = Verifier(_verifierAddress);
verifierExit = VerifierExit(_verifierExitAddress);
governance = Governance(_governanceAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
maxDepositAmount = DEFAULT_MAX_DEPOSIT_AMOUNT;
withdrawGasLimit = ERC20_WITHDRAWAL_GAS_LIMIT;
}
function setGenesisRootAndAddresses(bytes32 _genesisRoot, address _zkSyncCommitBlockAddress, address _zkSyncExitAddress) external {
// This function cannot be called twice as long as
// _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to
// non-zero.
require(zkSyncCommitBlockAddress == address(0), "sraa1");
require(zkSyncExitAddress == address(0), "sraa2");
blocks[0].stateRoot = _genesisRoot;
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
zkSyncExitAddress = _zkSyncExitAddress;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @param _maxAmount Maximum possible amount of tokens to transfer to this account
function withdrawERC20Guarded(IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "wtg10");
// wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint16 lpTokenId = tokenIds[address(_token)];
uint256 balance_before = _token.balanceOf(address(this));
if (lpTokenId > 0) {
validatePairTokenAddress(address(_token));
pairmanager.mint(address(_token), _to, _amount);
} else {
require(Utils.sendERC20(_token, _to, _amount), "wtg11");
// wtg11 - ERC20 transfer fails
}
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
require(balance_diff <= _maxAmount, "wtg12");
// wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balance_diff);
}
/// @notice executes pending withdrawals
/// @param _n The number of withdrawals to complete starting from oldest
function completeWithdrawals(uint32 _n) external nonReentrant {
// TODO: when switched to multi validators model we need to add incentive mechanism to call complete.
uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals);
uint32 startIndex = firstPendingWithdrawalIndex;
numberOfPendingWithdrawals -= toProcess;
firstPendingWithdrawalIndex += toProcess;
for (uint32 i = startIndex; i < startIndex + toProcess; ++i) {
uint16 tokenId = pendingWithdrawals[i].tokenId;
address to = pendingWithdrawals[i].to;
// send fails are ignored hence there is always a direct way to withdraw.
delete pendingWithdrawals[i];
bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId);
uint128 amount = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
// amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20
if (amount != 0) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw -= amount;
bool sent = false;
if (tokenId == 0) {
address payable toPayable = address(uint160(to));
sent = Utils.sendETHNoRevert(toPayable, amount);
} else {
address tokenAddr = address(0);
if (tokenId < PAIR_TOKEN_START_ID) {
// It is normal ERC20
tokenAddr = governance.tokenAddresses(tokenId);
} else {
// It is pair token
tokenAddr = tokenAddresses[tokenId];
}
// tokenAddr cannot be 0
require(tokenAddr != address(0), "cwt0");
// we can just check that call not reverts because it wants to withdraw all amount
(sent,) = address(this).call.gas(withdrawGasLimit)(
abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount)
);
}
if (!sent) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += amount;
}
}
}
if (toProcess > 0) {
emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess);
}
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n) external nonReentrant {
require(exodusMode, "coe01");
// exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "coe02");
// no deposits to process
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
Operations.Deposit memory op = Operations.readDepositPubdata(priorityRequests[id].pubData);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _franklinAddr The receiver Layer 2 address
function depositETH(address _franklinAddr) external payable nonReentrant {
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr);
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender
/// @param _amount Ether amount to withdraw
function withdrawETH(uint128 _amount) external nonReentrant {
registerWithdrawal(0, _amount, msg.sender);
(bool success,) = msg.sender.call.value(_amount)("");
require(success, "fwe11");
// ETH withdraw failed
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to _to address
/// @param _amount Ether amount to withdraw
function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa11");
registerWithdrawal(0, _amount, _to);
(bool success,) = _to.call.value(_amount)("");
require(success, "fwe12");
// ETH withdraw failed
}
/// @notice Config amount limit for each ERC20 deposit
/// @param _amount Max deposit amount
function setMaxDepositAmount(uint128 _amount) external {
governance.requireGovernor(msg.sender);
maxDepositAmount = _amount;
}
/// @notice Config gas limit for withdraw erc20 token
/// @param _gasLimit withdraw erc20 gas limit
function setWithDrawGasLimit(uint256 _gasLimit) external {
governance.requireGovernor(msg.sender);
withdrawGasLimit = _gasLimit;
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
/// @param _franklinAddr Receiver Layer 2 address
function depositERC20(IERC20 _token, uint104 _amount, address _franklinAddr) external nonReentrant {
requireActive();
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount));
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= maxDepositAmount, "fd011");
registerDeposit(lpTokenId, deposit_amount, _franklinAddr);
} else {
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012");
// token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= maxDepositAmount, "fd013");
registerDeposit(tokenId, deposit_amount, _franklinAddr);
}
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender
/// @param _token Token address
/// @param _amount amount to withdraw
function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant {
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, msg.sender, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, msg.sender);
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to _to address
/// @param _token Token address
/// @param _amount amount to withdraw
/// @param _to address to withdraw
function withdrawERC20WithAddress(IERC20 _token, uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa12");
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(_to, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, _to, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, _to);
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function fullExit(uint32 _accountId, address _token) external nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "fee11");
uint16 tokenId;
if (_token == address(0)) {
tokenId = 0;
} else {
tokenId = governance.validateTokenAddress(_token);
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "fee12");
}
// Priority Queue request
Operations.FullExit memory op = Operations.FullExit({
accountId : _accountId,
owner : msg.sender,
tokenId : tokenId,
amount : 0 // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdata(op);
addPriorityRequest(Operations.OpType.FullExit, pubData, "");
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff;
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op = Operations.Deposit({
accountId : 0, // unknown at this point
owner : _owner,
tokenId : _tokenId,
amount : _amount
});
bytes memory pubData = Operations.writeDepositPubdata(op);
addPriorityRequest(Operations.OpType.Deposit, pubData, "");
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
/// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event
/// @param _token - token by id
/// @param _amount - token amount
/// @param _to - address to withdraw to
function registerWithdrawal(uint16 _token, uint128 _amount, address payable _to) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(_amount);
emit OnchainWithdrawal(
_to,
_token,
_amount
);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "fre11");
// exodus mode activated
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData,
bytes memory _userData
) internal {
// Expiration block is: current block number + priority expiration delta
uint256 expirationBlock = block.number + PRIORITY_EXPIRATION;
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
priorityRequests[nextPriorityRequestId] = PriorityOperation({
opType : _opType,
pubData : _pubData,
expirationBlock : expirationBlock
});
emit NewPriorityRequest(
msg.sender,
nextPriorityRequestId,
_opType,
_pubData,
_userData,
expirationBlock
);
totalOpenPriorityRequests++;
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
function() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// Address of lock flag variable.
/// Flag is placed at random memory location to not interfere with Storage contract.
uint constant private LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
function initializeReentrancyGuard () internal {
// Storing an initial 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 percetange 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.
assembly { sstore(LOCK_FLAG_ADDRESS, 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() {
bool notEntered;
assembly { notEntered := sload(LOCK_FLAG_ADDRESS) }
// On the first call to nonReentrant, _notEntered will be true
require(notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
assembly { sstore(LOCK_FLAG_ADDRESS, 0) }
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly { sstore(LOCK_FLAG_ADDRESS, 1) }
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "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(uint128 a, uint128 b) internal pure returns (uint128) {
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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint128 a, uint128 b) internal pure returns (uint128) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint128 c = a * b;
require(c / a == b, "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(uint128 a, uint128 b) internal pure returns (uint128) {
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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(
abi.encodeWithSignature("transfer(address,uint256)", _to, _amount)
);
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(
abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount)
);
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Sends ETH
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) {
// TODO: Use constant from Config
uint256 ETH_WITHDRAWAL_GAS_LIMIT = 10000;
(bool callSuccess, ) = _to.call.gas(ETH_WITHDRAWAL_GAS_LIMIT).value(_amount)("");
return callSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _message signed message.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes memory _message) internal pure returns (address) {
require(_signature.length == 65, "ves10"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint offset = 0;
(offset, signR) = Bytes.readBytes32(_signature, offset);
(offset, signS) = Bytes.readBytes32(_signature, offset);
uint8 signV = uint8(_signature[offset]);
return ecrecover(keccak256(_message), signV, signR, signS);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title ZKSwap storage contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Storage {
/// @notice Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool public upgradePreparationActive;
/// @notice Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public upgradePreparationActivationTime;
/// @notice Verifier contract. Used to verify block proof and exit proof
Verifier internal verifier;
VerifierExit internal verifierExit;
/// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance internal governance;
UniswapV2Factory internal pairmanager;
struct BalanceToWithdraw {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw;
/// @notice verified withdrawal pending to be executed.
struct PendingWithdrawal {
address to;
uint16 tokenId;
}
/// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue)
mapping(uint32 => PendingWithdrawal) public pendingWithdrawals;
uint32 public firstPendingWithdrawalIndex;
uint32 public numberOfPendingWithdrawals;
/// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis)
uint32 public totalBlocksVerified;
/// @notice Total number of checked blocks
uint32 public totalBlocksChecked;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Rollup block data (once per block)
/// @member validator Block producer
/// @member committedAtBlock ETH block number at which this block was committed
/// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks
/// @member priorityOperations Total number of priority operations for this block
/// @member commitment Hash of the block circuit commitment
/// @member stateRoot New tree root hash
///
/// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html
struct Block {
uint32 committedAtBlock;
uint64 priorityOperations;
uint32 chunks;
bytes32 withdrawalsDataHash; /// can be restricted to 16 bytes to reduce number of required storage slots
bytes32 commitment;
bytes32 stateRoot;
}
/// @notice Blocks by Franklin block id
mapping(uint32 => Block) public blocks;
/// @notice Onchain operations - operations processed inside rollup blocks
/// @member opType Onchain operation type
/// @member amount Amount used in the operation
/// @member pubData Operation pubdata
struct OnchainOperation {
Operations.OpType opType;
bytes pubData;
}
/// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public exited;
mapping(uint32 => mapping(uint32 => bool)) public swap_exited;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice User authenticated fact hashes for some nonce.
mapping(address => mapping(uint32 => bytes32)) public authFacts;
/// @notice Priority Operation container
/// @member opType Priority operation type
/// @member pubData Priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
struct PriorityOperation {
Operations.OpType opType;
bytes pubData;
uint256 expirationBlock;
}
/// @notice Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
mapping(uint64 => PriorityOperation) public priorityRequests;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @notice Gets value from balancesToWithdraw
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
address public zkSyncCommitBlockAddress;
address public zkSyncExitAddress;
/// @notice Limit the max amount for each ERC20 deposit
uint128 public maxDepositAmount;
/// @notice withdraw erc20 token gas limit
uint256 public withdrawGasLimit;
}
pragma solidity ^0.5.0;
/// @title ZKSwap configuration constants
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Config {
/// @notice ERC20 token withdrawal gas limit, used only for complete withdrawals
uint256 constant ERC20_WITHDRAWAL_GAS_LIMIT = 350000;
/// @notice ETH token withdrawal gas limit, used only for complete withdrawals
uint256 constant ETH_WITHDRAWAL_GAS_LIMIT = 10000;
/// @notice Bytes in one chunk
uint8 constant CHUNK_BYTES = 11;
/// @notice ZKSwap address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @notice Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @notice Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @notice Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @notice Max amount of fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS = 32 - 1;
/// @notice start ID for user tokens
uint16 constant USER_TOKENS_START_ID = 32;
/// @notice Max amount of user tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_USER_TOKENS = 16352;
/// @notice Max amount of tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 16384 - 1;
/// @notice Max account id that could be registered in the network
uint32 constant MAX_ACCOUNT_ID = (2 ** 28) - 1;
/// @notice Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @notice ETH blocks verification expectation
/// Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant CREATE_PAIR_BYTES = 3 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 4 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 4 * CHUNK_BYTES;
uint256 constant PARTIAL_EXIT_BYTES = 5 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant UNISWAP_ADD_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_RM_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_SWAP_BYTES = 2 * CHUNK_BYTES;
/// @notice Full exit operation length
uint256 constant FULL_EXIT_BYTES = 4 * CHUNK_BYTES;
/// @notice OnchainWithdrawal data length
uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 1 + 20 + 2 + 16; // (uint8 addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
/// @notice ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 5 * CHUNK_BYTES;
/// @notice Expiration delta for priority request to be satisfied (in seconds)
/// NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD), otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 3 days;
/// @notice Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @notice Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @notice Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint constant MASS_FULL_EXIT_PERIOD = 3 days;
/// @notice Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @notice Notice period before activation preparation status of upgrade mode (in seconds)
// NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD + PRIORITY_EXPIRATION_PERIOD + TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT;
// @notice Default amount limit for each ERC20 deposit
uint128 constant DEFAULT_MAX_DEPOSIT_AMOUNT = 2 ** 85;
}
pragma solidity ^0.5.0;
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title ZKSwap events
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
/// @notice Event emitted when a block is verified
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when a sequence of blocks is verified
event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo);
/// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash)
event FactAuth(
address indexed sender,
uint32 nonce,
bytes fact
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(
uint32 indexed totalBlocksVerified,
uint32 indexed totalBlocksCommitted
);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
bytes userData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Pending withdrawals index range that were added in the verifyBlock operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsAdd(
uint32 queueStartIndex,
uint32 queueEndIndex
);
/// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsComplete(
uint32 queueStartIndex,
uint32 queueEndIndex
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(
uint indexed versionId,
address indexed upgradeable
);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint indexed versionId,
address[] newTargets,
uint noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(
uint indexed versionId
);
/// @notice Upgrade mode preparation status event
event PreparationStart(
uint indexed versionId
);
/// @notice Upgrade mode complete event
event UpgradeComplete(
uint indexed versionId,
address[] newTargets
);
}
pragma solidity ^0.5.0;
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "bt211");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint data = self << ((32 - byteLength) * 8);
assembly {
mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "bta11");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "btb20");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "btu02");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "btu03");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "btu04");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "btu16");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "btu20");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "btb32");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
// TODO: Review this thoroughly.
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
// Helper function for hex conversion.
function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
}
}
return outStringBytes;
}
/// Trim bytes into single word
function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) {
require(_new_length <= 0x20, "trm10"); // new_length is longer than word
require(_data.length >= _new_length, "trm11"); // data is to short
uint a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
}
pragma solidity ^0.5.0;
import "./Bytes.sol";
/// @title ZKSwap operations tools
library Operations {
// Circuit ops and their pubdata (chunks * bytes)
/// @notice ZKSwap circuit operation type
enum OpType {
Noop,
Deposit,
TransferToNew,
PartialExit,
_CloseAccount, // used for correct op id offset
Transfer,
FullExit,
ChangePubKey,
CreatePair,
AddLiquidity,
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @notice Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @notice ZKSwap account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @notice Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
}
uint public constant PACKED_DEPOSIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure
returns (Deposit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner // owner
);
}
/// @notice Check that deposit pubdata from request and block matches
function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// FullExit pubdata
struct FullExit {
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
}
uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure
returns (FullExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size
}
function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
/// @notice Check that full exit pubdata from request and block matches
function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// `amount` is ignored because it is present in block pubdata but not in priority queue
uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
return lhs == rhs;
}
// PartialExit pubdata
struct PartialExit {
//uint32 accountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
}
function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure
returns (PartialExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
}
function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
// ChangePubKey
struct ChangePubKey {
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
}
function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure
returns (ChangePubKey memory parsed)
{
uint offset = _offset;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// Withdrawal data process
function readWithdrawalData(bytes memory _data, uint _offset) internal pure
returns (bool _addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
{
uint offset = _offset;
(offset, _addToPendingWithdrawalsQueue) = Bytes.readBool(_data, offset);
(offset, _to) = Bytes.readAddress(_data, offset);
(offset, _tokenId) = Bytes.readUInt16(_data, offset);
(offset, _amount) = Bytes.readUInt128(_data, offset);
}
// CreatePair pubdata
struct CreatePair {
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
function readCreatePairPubdata(bytes memory _data) internal pure
returns (CreatePair memory parsed)
{
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
/// @notice Check that create pair pubdata from request and block matches
function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() public {
}
function initialize(bytes calldata data) external {
}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
//require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
IUniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
IUniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.5.0;
contract PairTokenManager {
/// @notice Max amount of pair tokens registered in the network.
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 49152;
uint16 constant PAIR_TOKEN_START_ID = 16384;
/// @notice Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
tokenAddresses[newPairTokenId] = _token;
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @notice Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId <= (PAIR_TOKEN_START_ID -1 + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
return tokenId;
}
}
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);
}
pragma solidity ^0.5.0;
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
/// @notice Governor changed
event NewGovernor(
address newGovernor
);
/// @notice tokenLister changed
event NewTokenLister(
address newTokenLister
);
/// @notice Validator's status changed
event ValidatorStatusUpdate(
address indexed validatorAddress,
bool isActive
);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalFeeTokens;
/// @notice Total number of ERC20 user tokens registered in the network
uint16 public totalUserTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
address public tokenLister;
constructor() public {
networkGovernor = msg.sender;
}
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
require(networkGovernor == address(0), "init0");
(address _networkGovernor, address _tokenLister) = abi.decode(initializationParameters, (address, address));
networkGovernor = _networkGovernor;
tokenLister = _tokenLister;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
require(_newGovernor != address(0), "zero address is passed as _newGovernor");
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Change current governor
/// @param _newTokenLister Address of the new governor
function changeTokenLister(address _newTokenLister) external {
requireGovernor(msg.sender);
require(_newTokenLister != address(0), "zero address is passed as _newTokenLister");
if (tokenLister != _newTokenLister) {
tokenLister = _newTokenLister;
emit NewTokenLister(_newTokenLister);
}
}
/// @notice Add fee token to the list of networks tokens
/// @param _token Token address
function addFeeToken(address _token) external {
requireGovernor(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalFeeTokens < MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "fee12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
totalFeeTokens++;
uint16 newTokenId = totalFeeTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireTokenLister(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalUserTokens < MAX_AMOUNT_OF_REGISTERED_USER_TOKENS, "gan12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
uint16 newTokenId = USER_TOKENS_START_ID + totalUserTokens;
totalUserTokens++;
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "grr11"); // only by governor
}
/// @notice Check if specified address can list token
/// @param _address Address to check
function requireTokenLister(address _address) public view {
require(_address == networkGovernor || _address == tokenLister, "grr11"); // token lister or governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "grr21"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return (_tokenId <= totalFeeTokens) || (_tokenId >= USER_TOKENS_START_ID && _tokenId < (USER_TOKENS_START_ID + totalUserTokens ));
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "gvs11"); // 0 is not a valid token
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "gvs12");
return tokenId;
}
function getTokenAddress(uint16 _tokenId) external view returns (address) {
address tokenAddr = tokenAddresses[_tokenId];
return tokenAddr;
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkAggVerifier.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkAggVerifier {
bool constant DUMMY_VERIFIER = false;
function initialize(bytes calldata) external {
}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function isBlockSizeSupported(uint32 _size) public pure returns (bool) {
if (DUMMY_VERIFIER) {
return true;
} else {
return isBlockSizeSupportedInternal(_size);
}
}
function verifyMultiblockProof(
uint256[] calldata _recursiveInput,
uint256[] calldata _proof,
uint32[] calldata _block_sizes,
uint256[] calldata _individual_vks_inputs,
uint256[] calldata _subproofs_limbs
) external view returns (bool) {
if (DUMMY_VERIFIER) {
uint oldGasValue = gasleft();
uint tmp;
while (gasleft() + 500000 > oldGasValue) {
tmp += 1;
}
return true;
}
uint8[] memory vkIndexes = new uint8[](_block_sizes.length);
for (uint32 i = 0; i < _block_sizes.length; i++) {
vkIndexes[i] = blockSizeToVkIndex(_block_sizes[i]);
}
VerificationKey memory vk = getVkAggregated(uint32(_block_sizes.length));
return verify_serialized_proof_with_recursion(_recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, vkIndexes, _individual_vks_inputs, _subproofs_limbs, vk);
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkSingleVerifier.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkSingleVerifier {
function initialize(bytes calldata) external {
}
/// @notice VerifierExit contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment = sha256(abi.encodePacked(_rootHash, _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _pair_data0,
bytes calldata _pair_data1,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory _data1 = concatBytes(_account_data, _pair_data0);
bytes memory _data2 = concatBytes(_data1, _pair_data1);
bytes32 commitment = sha256(_data2);
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkLpExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IUNISWAPERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkAggCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkAggVerifier is AggVerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x0a3cdc9655e61bf64758c1e8df745723e9b83addd4f0d0f2dd65dc762dc1e9e7;
uint8 constant VK_MAX_INDEX = 5;
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function blockSizeToVkIndex(uint32 _chunks) internal pure returns (uint8) {
if (_chunks == uint32(6)) { return 0; }
else if (_chunks == uint32(12)) { return 1; }
else if (_chunks == uint32(48)) { return 2; }
else if (_chunks == uint32(96)) { return 3; }
else if (_chunks == uint32(204)) { return 4; }
else if (_chunks == uint32(420)) { return 5; }
}
function getVkAggregated(uint32 _blocks) internal pure returns (VerificationKey memory vk) {
if (_blocks == uint32(1)) { return getVkAggregated1(); }
else if (_blocks == uint32(5)) { return getVkAggregated5(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated5() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x023cfc69ef1b002da66120fce352ede75893edd8cd8196403a54e1eceb82cd43,
0x2baf3bd673e46be9df0d43ca30f834671543c22db422f450b2efd8c931e9b34e
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x23783fe0e5c3f83c02c864e25fe766afb727134c9a77ae6b9694efb7b46f31ab,
0x1903d01005e447d061c16323a1d604d8fbd4b5cc9b64945a71f1234d280c4d3a
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x2897df6c6fa993661b2b0b0cf52460278e33533de71b3c0f7ed7c1f20af238c6,
0x042344afee0aed5505e59bce4ebbe942a91268a8af6b77ea95f603b5b726e8cb
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x0fceed33e78426afc38d8a68c0d93413d2bbaa492b087125271d33d52bdb07b8,
0x0057e4f63be36edb56e91da931f3d0ba72d1862d4b7751c59b92b6ae9f1fcc11
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x14230a35f172cd77a2147cecc20b2a13148363cbab78709489a29d08001e26fb,
0x04f1040477d77896475080b5abb8091cda2cce4917ee0ba5dd62d0ab1be379b4
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x20d1a079ad80a8abb7fd8ba669dddbbe23231360a5f0ba679b6536b6bf980649,
0x120c5a845903bd6de4105eb8cef90e6dff2c3888ada16c90e1efb393778d6a4d
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x1af6b9e362e458a96b8bbbf8f8ce2bdbd650fb68478360c408a2acf1633c1ce1,
0x27033728b767b44c659e7896a6fcc956af97566a5a1135f87a2e510976a62d41
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x0dbfb3c5f5131eb6f01e12b1a6333b0ad22cc8292b666e46e9bd4d80802cccdf,
0x2d058711c42fd2fd2eef33fb327d111a27fe2063b46e1bb54b32d02e9676e546
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0c8c7352a84dd3f32412b1a96acd94548a292411fd7479d8609ca9bd872f1e36,
0x0874203fd8012d6976698cc2df47bca14bc04879368ade6412a2109c1e71e5e8
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1b17bb7c319b1cf15461f4f0b69d98e15222320cb2d22f4e3a5f5e0e9e51f4bd,
0x0cf5bc338235ded905926006027aa2aab277bc32a098cd5b5353f5545cbd2825
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x0794d3cfbc2fdd756b162571a40e40b8f31e705c77063f30a4e9155dbc00e0ef,
0x1f821232ab8826ea5bf53fe9866c74e88a218c8d163afcaa395eda4db57b7a23
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x224d93783aa6856621a9bbec495f4830c94994e266b240db9d652dbb394a283b,
0x161bcec99f3bc449d655c0ca59874dafe1194138eec91af34392b09a83338ca1
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1fa27e2916b2c11d39c74c0e61063190da31c102d2b7da5c0a61ec8c5e82f132,
0x0a815ee76cd8aa600e6f66463b25a0ee57814bfdf06c65a91ddc70cede41caae
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkSingleCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkSingleVerifier is SingleVerifierWithDeserialize {
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function getVkExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1abc710835cdc78389d61b670b0e8d26416a63c9bd3d6ed435103ebbb8a8665e,
0x138c6678230ed19f90b947d0a9027bd9fc458bbd1d2b8371fa72e28470a97b9c
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x28d81ac76e1ddf630b4bf8e4a789cf9c4470c5e5cc010a24849b20ab595b8b22,
0x251ca3cf0829b261d3be8d6cbd25aa97d9af716819c29f6319d806f075e79655
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1504c8c227833a1152f3312d258412c334ac7ae213e21427ff63028729bc28fa,
0x0f0942f3fede795cbe624fb9ddf9be90ba546609383f2246c3c9b92af7aab5fd
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x1f14a5bb19ea2897ac6b9fbdbd2b4e371be09f8e90a47ae26602d399c9bcd311,
0x029c6ea094247da75d9a66cea627c3c77d48b898003125d4f8e785435dc2cf23
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x102cdd83e2d70638a70d700622b662607f8a2d92f5c36053a4ddb4b600d75bcf,
0x09ef3679579d761507ef69eaf49c978b271f0e4500468da1ebd7197f3ff5d6ac
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x2c2bd1d2fa3d4b3915d0fe465469e11ee563e79751da71c6082fcd0ca4e41cd5,
0x0304f16147a8af177dcc703370931d5161bda9dcf3e091787b9a54377ab54c32
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x14420680f992f4bc8d8012e2d8b14a774cf9114adf1e41b3c02c20cc1648398e,
0x237d3d5cdee5e3d7d58f4eb336ecd7aa5ec88d89205861b410420f6b9f6b26a1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x221045ae5578ccb35e0a198d83c0fb191da8cdc98423fc46e580f1762682c73e,
0x15b7f3d74fcd258fdd2ae6001693a7c615e654d613a506d213aaf0ad314e338d
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x03e47981b459b3be258a6353593898babec571ccf3e0362d53a67f078f04830a,
0x0809556ab6eb28403bb5a749fcdbd8656940add7685ff5473dc3a9ad940034df
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2c02322c53d7e6a6474b15c7db738419e3f4d1263e9f98ebb56c24906f555ef9,
0x2322c69f51366551665b584d797e0fdadb16fe31b1e7ae2f532847a75b3aeaab
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x2147e39b49c2bef4168884c0ac9e38bb4dc65b41ba21953f7ded2daab7fe1534,
0x071f3548c9ca2c6a8d10b11d553263ebe0afaf1f663b927ef970bd6c3974cb68
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkLpExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 524288;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x067d967299b3d380f2e461409fbacb82d9af8c85b62de082a423f344fb0b9d38,
0x2440bd569ac24e9525b29e433334ee98d72cb8eb19af65250ee0099fb470d873
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x086a9ed0f6175964593e516a8c1fc8bbd0a9c8afb724ebbce08a7772bd7b8837,
0x0aca3794dc6a2f0cab69dfed529d31deb7a5e9e6c339e3c07d8d88df0f7abd6b
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x00b6bfec3aceb55618e6caf637c978c3fe2344568c64515022fcfa00e490eb97,
0x0f890fe6b9cb943fb4887df1529cdae99e2494eabf675f89905215eb51c29c6e
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x0968470be841bcbfbcccc10dd0d8b63a871cdb3289c214fc59f38c88ab15146a,
0x1a9b4d034050fa0b119bb64ba0e967fd09f224c6fd9cd8b54cd6f081085dfb98
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x080dbe10de0cacf12db303a86049c7a4d42f068a9def099e0cb874008f210b1b,
0x02f17638d3410ab573e33a4e6c6cf0c918bea2aa4f1025ca5ee13d7a950c4058
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x267043dbe00520bd8bbf55a96b51fde6b3b64219eca9e2fd8309693db0cf0392,
0x08dbbfa17faad841228af22a03fab7ec20f765036a2acae62f543f61e55b6e8c
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x215141775449677e3dbe25ff6c5e5d99336a29d952a61d5ec87618346e78df30,
0x29502caeb6afaf2acd13766d52fac2907efb7d11c66cd8beb93c8321d380b215
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x150790105b9f5455ae6f91daa6b03c5793fb7bcfcd9d5d37d3b643b77535b10a,
0x2b644a9736282f80fae8d35f00cbddf2bba3560c54f3d036ec1c8014c147a506
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1b898666ded092a449935de7d707ad8d65809c2baccdd7dd7cfdaf2fb27e1262,
0x2a24c241dcad93b7bdf1cce2427c9c54f731a7d50c27a825e2af3dabb66dc81f
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x049892634dbbfa0c364523827cd7e604b70a7e24a4cb111cb8fccb7c05b04d7f,
0x1e5d8d7c0bf92d822dcf339a52c326a35cadf010b888b8f26e155a68c7e23dc9
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x04f90846cb1598aa05164a78d171ea918154414652d07d3f5cab84a26e6aa158,
0x0975ba8858f136bb8b1b043daf8dfed33709f72ba37e01e5de62c81f3928a13c
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0;
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 factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function initialize(address, address) external;
function mint(address to, uint amount) external;
function burn(address to, uint amount) external;
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'ZKSWAP V2';
string public constant symbol = 'ZKS-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity >=0.5.0;
interface IUNISWAPERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkCoreLib.sol";
contract Plonk4AggVerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH-1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function evaluate_vanishing(
uint256 domain_size,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH+2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i+1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs == 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
vk.domain_size,
vk.omega, state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) {
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input(
recursive_vks_root, max_valid_index, recursive_vks_indexes,
individual_vks_inputs, subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << 2*LIMB_WIDTH) + (subproofs_aggregated[3] << 3*LIMB_WIDTH),
subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << 2*LIMB_WIDTH) + (subproofs_aggregated[7] << 3*LIMB_WIDTH)
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << 2*LIMB_WIDTH) + (subproofs_aggregated[11] << 3*LIMB_WIDTH),
subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << 2*LIMB_WIDTH) + (subproofs_aggregated[15] << 3*LIMB_WIDTH)
);
return (recursive_input, reconstructed_g1s);
}
}
contract AggVerifierWithDeserialize is Plonk4AggVerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof
) internal pure returns(Proof memory proof) {
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify_recursive(proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs);
return valid;
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkCoreLib.sol";
contract Plonk4SingleVerifierWithAccessToDNext {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH+2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function evaluate_vanishing(
uint256 domain_size,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH + STATE_WIDTH - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i+1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs == 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
vk.domain_size,
vk.omega, state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
PartialVerifierState memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract SingleVerifierWithDeserialize is Plonk4SingleVerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 33;
function deserialize_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof
) internal pure returns(Proof memory proof) {
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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);
}
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity >=0.5.0 <0.7.0;
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod-2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return G2Point(
[0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed],
[0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2)
internal view returns (G1Point memory r)
{
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2)
internal view
{
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest)
internal view
{
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2)
internal view
{
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest)
internal view
{
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s)
internal view returns (G1Point memory r)
{
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s)
internal view
{
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(G1Point memory p, Fr memory s, G1Point memory dest)
internal view
{
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2)
internal view returns (bool)
{
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2)
internal view returns (bool)
{
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns(PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
| This function cannot be called twice as long as _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to non-zero. | function setGenesisRootAndAddresses(bytes32 _genesisRoot, address _zkSyncCommitBlockAddress, address _zkSyncExitAddress) external {
require(zkSyncCommitBlockAddress == address(0), "sraa1");
require(zkSyncExitAddress == address(0), "sraa2");
blocks[0].stateRoot = _genesisRoot;
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
zkSyncExitAddress = _zkSyncExitAddress;
}
| 1,250,287 | [
1,
2503,
445,
2780,
506,
2566,
13605,
487,
1525,
487,
389,
22888,
4047,
5580,
1768,
1887,
471,
389,
22888,
4047,
6767,
1887,
1240,
2118,
444,
358,
1661,
17,
7124,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
7642,
16786,
2375,
1876,
7148,
12,
3890,
1578,
389,
4507,
16786,
2375,
16,
1758,
389,
22888,
4047,
5580,
1768,
1887,
16,
1758,
389,
22888,
4047,
6767,
1887,
13,
3903,
288,
203,
3639,
2583,
12,
22888,
4047,
5580,
1768,
1887,
422,
1758,
12,
20,
3631,
315,
87,
354,
69,
21,
8863,
203,
3639,
2583,
12,
22888,
4047,
6767,
1887,
422,
1758,
12,
20,
3631,
315,
87,
354,
69,
22,
8863,
203,
3639,
4398,
63,
20,
8009,
2019,
2375,
273,
389,
4507,
16786,
2375,
31,
203,
3639,
14164,
4047,
5580,
1768,
1887,
273,
389,
22888,
4047,
5580,
1768,
1887,
31,
203,
3639,
14164,
4047,
6767,
1887,
273,
389,
22888,
4047,
6767,
1887,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import "./abstracts/fujiERC1155/FujiBaseERC1155.sol";
import "./abstracts/fujiERC1155/F1155Manager.sol";
import "./abstracts/claimable/ClaimableUpgradeable.sol";
import "./interfaces/IFujiERC1155.sol";
import "./libraries/WadRayMath.sol";
import "./libraries/Errors.sol";
contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager {
using WadRayMath for uint256;
// FujiERC1155 Asset ID Mapping
// AssetType => asset reference address => ERC1155 Asset ID
mapping(AssetType => mapping(address => uint256)) public assetIDs;
// Control mapping that returns the AssetType of an AssetID
mapping(uint256 => AssetType) public assetIDtype;
uint64 public override qtyOfManagedAssets;
// Asset ID Liquidity Index mapping
// AssetId => Liquidity index for asset ID
mapping(uint256 => uint256) public indexes;
function initialize() external initializer {
__ERC165_init();
__Context_init();
__Climable_init();
}
/**
* @dev Updates Index of AssetID
* @param _assetID: ERC1155 ID of the asset which state will be updated.
* @param newBalance: Amount
**/
function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit {
uint256 total = totalSupply(_assetID);
if (newBalance > 0 && total > 0 && newBalance > total) {
uint256 diff = newBalance - total;
uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay());
uint256 result = amountToIndexRatio + WadRayMath.ray();
result = result.rayMul(indexes[_assetID]);
require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW);
indexes[_assetID] = uint128(result);
// TODO: calculate interest rate for a fujiOptimizer Fee.
}
}
/**
* @dev Returns the total supply of Asset_ID with accrued interest.
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function totalSupply(uint256 _assetID) public view virtual override returns (uint256) {
// TODO: include interest accrued by Fuji OptimizerFee
return super.totalSupply(_assetID).rayMul(indexes[_assetID]);
}
/**
* @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index)
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) {
return super.totalSupply(_assetID);
}
/**
* @dev Returns the principal + accrued interest balance of the user
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function balanceOf(address _account, uint256 _assetID)
public
view
override(FujiBaseERC1155, IFujiERC1155)
returns (uint256)
{
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return 0;
}
// TODO: include interest accrued by Fuji OptimizerFee
return scaledBalance.rayMul(indexes[_assetID]);
}
/**
* @dev Returns Scaled Balance of the user (e.g. balance/index)
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledBalanceOf(address _account, uint256 _assetID)
public
view
virtual
returns (uint256)
{
return super.balanceOf(_account, _assetID);
}
/**
* @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol
* Emits a {TransferSingle} event.
* Requirements:
* - `_account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* - `_amount` should be in WAD
*/
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_id][_account] = accountBalance + amountScaled;
_totalSupply[_id] = assetTotalBalance + amountScaled;
emit TransferSingle(operator, address(0), _account, _id, _amount);
_doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data);
}
/**
* @dev [Batched] version of {mint}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
* - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function mintBatch(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) external onlyPermit {
require(_to != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
accountBalance = _balances[_ids[i]][_to];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_ids[i]][_to] = accountBalance + amountScaled;
_totalSupply[_ids[i]] = assetTotalBalance + amountScaled;
}
emit TransferBatch(operator, address(0), _to, _ids, _amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data);
}
/**
* @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol
* Requirements:
* - `account` cannot be the zero address.
* - `account` must have at least `_amount` tokens of token type `_id`.
* - `_amount` should be in WAD
*/
function burn(
address _account,
uint256 _id,
uint256 _amount
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_id][_account] = accountBalance - amountScaled;
_totalSupply[_id] = assetTotalBalance - amountScaled;
emit TransferSingle(operator, _account, address(0), _id, _amount);
}
/**
* @dev [Batched] version of {burn}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
*/
function burnBatch(
address _account,
uint256[] memory _ids,
uint256[] memory _amounts
) external onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
uint256 amount = _amounts[i];
accountBalance = _balances[_ids[i]][_account];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_ids[i]][_account] = accountBalance - amount;
_totalSupply[_ids[i]] = assetTotalBalance - amount;
}
emit TransferBatch(operator, _account, address(0), _ids, _amounts);
}
//Getter Functions
/**
* @dev Getter Function for the Asset ID locally managed
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) {
id = assetIDs[_type][_addr];
require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155);
}
//Setter Functions
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
*/
function setURI(string memory _newUri) public onlyOwner {
_uri = _newUri;
}
/**
* @dev Adds and initializes liquidity index of a new asset in FujiERC1155
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function addInitializeAsset(AssetType _type, address _addr)
external
override
onlyPermit
returns (uint64)
{
require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS);
assetIDs[_type][_addr] = qtyOfManagedAssets;
assetIDtype[qtyOfManagedAssets] = _type;
//Initialize the liquidity Index
indexes[qtyOfManagedAssets] = WadRayMath.ray();
qtyOfManagedAssets++;
return qtyOfManagedAssets - 1;
}
}
// 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 "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/IERC1155MetadataURIUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../libraries/Errors.sol";
/**
*
* @dev Implementation of the Base ERC1155 multi-token standard functions
* for Fuji Protocol control of User collaterals and borrow debt positions.
* Originally based on Openzeppelin
*
*/
abstract contract FujiBaseERC1155 is IERC1155Upgradeable, ERC165Upgradeable, ContextUpgradeable {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// Mapping from token ID to totalSupply
mapping(uint256 => uint256) internal _totalSupply;
//URI for all token types by relying on ID substitution
//https://token.fujiDao.org/{id}.json
string internal _uri;
/**
* @return The total supply of a token id
**/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
* Requirements:
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), Errors.VL_ZERO_ADDR_1155);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
* Requirements:
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, Errors.VL_INPUT_ERROR);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, Errors.VL_INPUT_ERROR);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address, // from
address, // to
uint256, // id
uint256, // amount
bytes memory // data
) public virtual override {
revert(Errors.VL_ERC1155_NOT_TRANSFERABLE);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address, // from
address, // to
uint256[] memory, // ids
uint256[] memory, // amounts
bytes memory // data
) public virtual override {
revert(Errors.VL_ERC1155_NOT_TRANSFERABLE);
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "./FujiBaseERC1155.sol";
import "../claimable/ClaimableUpgradeable.sol";
import "../../interfaces/IFujiERC1155.sol";
import "../../libraries/WadRayMath.sol";
import "../../libraries/Errors.sol";
abstract contract F1155Manager is ClaimableUpgradeable {
using Address for address;
// Controls for Mint-Burn Operations
mapping(address => bool) public addrPermit;
modifier onlyPermit() {
require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
function setPermit(address _address, bool _permit) public onlyOwner {
require((_address).isContract(), Errors.VL_NOT_A_CONTRACT);
addrPermit[_address] = _permit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
abstract contract ClaimableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
address public pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(address indexed owner);
function __Climable_init() internal initializer {
__Context_init_unchained();
__Climable_init_unchained();
}
function __Climable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_msgSender() == owner(), "Ownable: caller is not the owner");
_;
}
modifier onlyPendingOwner() {
require(_msgSender() == pendingOwner);
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(owner(), address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(pendingOwner == address(0));
pendingOwner = newOwner;
emit NewPendingOwner(newOwner);
}
function cancelTransferOwnership() public onlyOwner {
require(pendingOwner != address(0));
delete pendingOwner;
emit NewPendingOwner(address(0));
}
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner(), pendingOwner);
_owner = pendingOwner;
delete pendingOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFujiERC1155 {
//Asset Types
enum AssetType {
//uint8 = 0
collateralToken,
//uint8 = 1
debtToken
}
//General Getter Functions
function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256);
function qtyOfManagedAssets() external view returns (uint64);
function balanceOf(address _account, uint256 _id) external view returns (uint256);
// function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256);
// function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256);
//Permit Controlled Functions
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external;
function burn(
address _account,
uint256 _id,
uint256 _amount
) external;
function updateState(uint256 _assetID, uint256 _newBalance) external;
function addInitializeAsset(AssetType _type, address _addr) external returns (uint64);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import { Errors } from "./Errors.sol";
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return _RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return _WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_WAD) / _WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_RAY) / _RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / _WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * _WAD_RAY_RATIO;
require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
/**
* @title Errors library
* @author Fuji
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = Validation Logic 100 series
* - MATH = Math libraries 200 series
* - RF = Refinancing 300 series
* - VLT = vault 400 series
* - SP = Special 900 series
*/
library Errors {
//Errors
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128
string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint
string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn
string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match
string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized
string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization
string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback
string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer
string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable
string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array
string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized
string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault
string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance
string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match.
string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155
string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address
string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract.
string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid.
string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer.
string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved.
string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens
string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer
string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27)
string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close.
string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest.
string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance.
string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed
string public constant VL_ERC1155_NOT_TRANSFERABLE = "128"; // ERC1155: Not Transferable
string public constant VL_SWAP_SLIPPAGE_LIMIT_EXCEED = "129"; // ERC1155: Not Transferable
string public constant VL_ZERO_ADDR = "130"; // Zero Address
string public constant MATH_DIVISION_BY_ZERO = "201";
string public constant MATH_ADDITION_OVERFLOW = "202";
string public constant MATH_MULTIPLICATION_OVERFLOW = "203";
string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0
string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault
string public constant ORACLE_INVALID_LENGTH = "501"; // The assets length and price feeds length doesn't match
string public constant ORACLE_NONE_PRICE_FEED = "502"; // The price feed is not found
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable {
/**
* @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;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@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 "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
| * @dev See {IERC165-supportsInterface}./ | function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
| 13,405,753 | [
1,
9704,
288,
45,
654,
39,
28275,
17,
28064,
1358,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
3849,
12,
654,
39,
28275,
10784,
429,
16,
467,
654,
39,
28275,
10784,
429,
13,
203,
565,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
327,
203,
1377,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
10784,
429,
2934,
5831,
548,
747,
203,
1377,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
2277,
3098,
10784,
429,
2934,
5831,
548,
747,
203,
1377,
2240,
18,
28064,
1358,
12,
5831,
548,
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
]
|
./partial_match/1/0xD72f617b374292bC45dB1be95EE7cf69D39219A2/sources/LendfMeData.sol | Get the block delta | function calculateInterestIndex(uint startingInterestIndex, uint interestRateMantissa, uint blockStart, uint blockEnd) pure public returns (Error, uint) {
(Error err0, uint blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
}
| 2,824,384 | [
1,
967,
326,
1203,
3622,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4604,
29281,
1016,
12,
11890,
5023,
29281,
1016,
16,
2254,
16513,
4727,
49,
970,
21269,
16,
2254,
1203,
1685,
16,
2254,
1203,
1638,
13,
16618,
1071,
1135,
261,
668,
16,
2254,
13,
288,
203,
203,
3639,
261,
668,
393,
20,
16,
2254,
1203,
9242,
13,
273,
720,
12,
2629,
1638,
16,
1203,
1685,
1769,
203,
3639,
309,
261,
370,
20,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
5411,
327,
261,
370,
20,
16,
374,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
370,
21,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
5411,
327,
261,
370,
21,
16,
374,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
370,
22,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
5411,
327,
261,
370,
22,
16,
374,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
370,
23,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
5411,
327,
261,
370,
23,
16,
374,
1769,
203,
3639,
289,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Mintor.sol";
import "./Forest.sol";
import "./Prey.sol";
import "./HunterHound.sol";
contract HunterGame is Mintor, Forest, Ownable {
// swtich to turn on/off the game
bool _paused = true;
// take back staked tokens using rescue() function in rescue mode, rescue mode happens when the code turns buggy
bool _rescueEnabled = false;
// switch to turn on/off the whitelist
bool public _whitelistEnabled = true;
// ERC20 contract
Prey public prey;
// ERC721 contract
HunterHound public hunterHound;
constructor(address prey_, address hunterHound_) {
prey = Prey(prey_);
hunterHound = HunterHound(hunterHound_);
}
/**
* return main information of the game
*/
function getGameStatus() public view
returns(
bool paused, uint phase, uint minted, uint requested,
uint hunterMinted, uint houndMinted,
uint hunterStaked, uint houndStaked,
uint totalClaimed, uint totalBurned,
uint houndsCaptured, uint maxTokensByCurrentPhase ) {
paused = _paused;
phase = currentPhase();
minted = Mintor.minted;
requested = Mintor.requested;
hunterMinted = Mintor.hunterMinted;
houndMinted = minted - hunterMinted;
hunterStaked = Forest.hunterStaked;
houndStaked = Forest.houndStaked;
totalClaimed = Forest.totalClaimed;
totalBurned = Forest.totalBurned;
houndsCaptured = Forest.houndsCaptured;
maxTokensByCurrentPhase = currentPhaseAmount();
}
/**
* return phase number of the game by recorded mint requests
*/
function currentPhase() public view returns(uint p) {
uint[4] memory amounts = [PHASE1_AMOUNT,PHASE2_AMOUNT,PHASE3_AMOUNT,PHASE4_AMOUNT];
for (uint i = 0; i < amounts.length; i++) {
p += amounts[i];
if (requested < p) {
return i+1;
}
}
}
/**
* get target total number of mints in current phase by recorded mint requests
*/
function currentPhaseAmount() public view returns(uint p) {
uint[4] memory amounts = [PHASE1_AMOUNT,PHASE2_AMOUNT,PHASE3_AMOUNT,PHASE4_AMOUNT];
for (uint256 i = 0; i < amounts.length; i++) {
p += amounts[i];
if (requested < p) {
return p;
}
}
}
/**
* check whether the address has enough ETH or $PREY balance to mint in the wallet and validity of the number of mints
*/
function mintPrecheck(uint amount) private {
uint phaseAmount = currentPhaseAmount();
// make sure preciseness of mints in every phase
require(amount > 0 && amount <= 50 && (requested % phaseAmount) <= ((requested + amount - 1) % phaseAmount) , "Invalid mint amount");
require(requested + amount <= MAX_TOKENS, "All tokens minted");
uint phase = currentPhase();
if (phase == 1) {
require(msg.value == MINT_PRICE * amount, "Invalid payment amount");
} else {
require(msg.value == 0, "Only prey");
uint totalMintCost;
if (phase == 2) {
totalMintCost = MINT_PHASE2_PRICE;
} else if (phase == 3) {
totalMintCost = MINT_PHASE3_PRICE;
} else {
totalMintCost = MINT_PHASE4_PRICE;
}
prey.burn(msg.sender, totalMintCost * amount);
}
}
/************** MINTING **************/
/**
* security check and execute `Mintor._request()` function
*/
function requestMint(uint amount) external payable {
require(tx.origin == msg.sender, "No Access");
if (_paused) {
require(_whitelistEnabled, 'Paused');
}
mintPrecheck(amount);
Mintor._request(msg.sender, amount);
}
/**
* security check and execute `Mintor._receive()` function
*/
function mint() external {
require(tx.origin == msg.sender, "No Access");
Mintor._receive(msg.sender, hunterHound);
}
/**
* execute `Mintor._mintRequestState()` function
*/
function mintRequestState(address requestor) external view returns (uint blockNumber, uint amount, uint state, uint open, uint timeout) {
return _mintRequestState(requestor);
}
/************** Forest **************/
/**
* return all holders' stake history
*/
function stakesByOwner(address owner) external view returns(Stake[] memory) {
return stakes[owner];
}
/**
* security check and execute `Forest._stake()` function
*/
function stakeToForest(uint256[][] calldata paris) external whenNotPaused {
require(tx.origin == msg.sender, "No Access");
Forest._stake(msg.sender, paris, hunterHound);
}
/**
* security check and execute `Forest._claim()` function
*/
function claimFromForest() external whenNotPaused {
require(tx.origin == msg.sender, "No Access");
Forest._claim(msg.sender, prey);
}
/**
* security check and execute `Forest._requestGamble()` function
*/
function requestGamble(uint action) external whenNotPaused {
require(tx.origin == msg.sender, "No Access");
Forest._requestGamble(msg.sender, action);
}
/**
* 执行 `Forest._gambleRequestState()`
*/
function gambleRequestState(address requestor) external view returns (uint blockNumber, uint action, uint state, uint open, uint timeout) {
return Forest._gambleRequestState(requestor);
}
/**
* security check and execute `Forest._unstake()` function
*/
function unstakeFromForest() external whenNotPaused {
require(tx.origin == msg.sender, "No Access");
Forest._unstake(msg.sender, prey, hunterHound);
}
/**
* security check and execute `Forest._rescue()` function
*/
function rescue() external {
require(tx.origin == msg.sender, "No Access");
require(_rescueEnabled, "Rescue disabled");
Forest._rescue(msg.sender, hunterHound);
}
/************** ADMIN **************/
/**
* allows owner to withdraw funds from minting
*/
function withdraw() external onlyOwner {
require(address(this).balance > 0, "No balance available");
payable(owner()).transfer(address(this).balance);
}
/**
* when the game is not paused
*/
modifier whenNotPaused() {
require(_paused == false, "Pausable: paused");
_;
}
/**
* pause/run the game
*/
function setPaused(bool paused_) external onlyOwner {
_paused = paused_;
}
/**
* turn on/off rescue mode
*/
function setRescueEnabled(bool rescue_) external onlyOwner {
_rescueEnabled = rescue_;
}
/**
* turn on/off whitelist
*/
function setWhitelistEnabled(bool whitelistEnabled_) external onlyOwner {
_whitelistEnabled = whitelistEnabled_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import './Prey.sol';
/**
* Useful for simple vesting schedules like "developers get their tokens
* after 2 years".
*/
contract TokenTimelock {
// ERC20 basic token contract being held
Prey private immutable _token;
// beneficiary of tokens after they are released
address private immutable _beneficiary;
// timestamp when token release is enabled
uint256 private immutable _releaseTime;
//a vesting duration to release tokens
uint256 private immutable _releaseDuration;
//record last withdraw time, through which calculate the total withdraw amount
uint256 private lastWithdrawTime;
//total amount of tokens to release
uint256 private immutable _totalToken;
constructor(
Prey token_,
address beneficiary_,
uint256 releaseTime_,
uint256 releaseDuration_,
uint256 totalToken_
) {
require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time");
_token = token_;
_beneficiary = beneficiary_;
_releaseTime = releaseTime_;
lastWithdrawTime = _releaseTime;
_releaseDuration = releaseDuration_;
_totalToken = totalToken_;
}
/**
* @return the token being held.
*/
function token() public view virtual returns (Prey) {
return _token;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view virtual returns (address) {
return _beneficiary;
}
/**
* @return the time when the tokens are released.
*/
function releaseTime() public view virtual returns (uint256) {
return _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public virtual {
require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time");
uint256 amount = token().balanceOf(address(this));
uint256 releaseAmount = (block.timestamp - lastWithdrawTime) * _totalToken / _releaseDuration;
require(amount >= releaseAmount, "TokenTimelock: no tokens to release");
lastWithdrawTime = block.timestamp;
token().transfer(beneficiary(), releaseAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import './TokenTimelock.sol';
/**
* $PREY token contract
*/
contract Prey is ERC20, Ownable {
// a mapping from an address to whether or not it can mint / burn
mapping(address => bool) public controllers;
// the total amount allocated for developers
uint constant developerTokenAmount = 600000000 ether;
// the total amount allocated for community rewards
uint constant communityTokenAmount = 2000000000 ether;
// the total amount of tokens staked in the forest to yeild
uint constant forestTokenAmount = 2400000000 ether;
// the amount of $PREY tokens community has yielded
uint mintedByCommunity;
// the amount of $PREY tokens staked and yielded in the forest
uint mintedByForest;
/**
* Contract constructor function
* @param developerAccount The address that receives locked $PREY rewards for developers, in total 600 million
*/
constructor(address developerAccount) ERC20("Prey", "PREY") {
// create contract to lock $PREY token for 2 years (732 days in total) for developers, after which there is a 10 months(300 days in total) vesting schedule to release 600 million tokens
TokenTimelock timelock = new TokenTimelock(this, developerAccount, block.timestamp + 732 days, 300 days, developerTokenAmount);
_mint(address(timelock), developerTokenAmount);
controllers[_msgSender()] = true;
}
/**
* the function mints $PREY tokens to community members, effectively controls maximum yields
* @param account mint $PREY to account
* @param amount $PREY amount to mint
*/
function mintByCommunity(address account, uint256 amount) external {
require(controllers[_msgSender()], "Only controllers can mint");
require(mintedByCommunity + amount <= communityTokenAmount, "No mint out");
mintedByCommunity = mintedByCommunity + amount;
_mint(account, amount);
}
/**
* the function mints $PREY tokens to community members, effectively controls maximum yields
* @param accounts mint $PREY to accounts
* @param amount $PREY amount to mint
*/
function mintsByCommunity(address[] calldata accounts, uint256 amount) external {
require(controllers[_msgSender()], "Only controllers can mint");
require(mintedByCommunity + (amount * accounts.length) <= communityTokenAmount, "No mint out");
mintedByCommunity = mintedByCommunity + (amount * accounts.length);
for (uint256 i = 0; i < accounts.length; i++) {
_mint(accounts[i], amount);
}
}
/**
* the function mints $PREY tokens by the forest, effectively controls maximum yields
* @param account mint $PREY to account
* @param amount $PREY amount to mint
*/
function mintByForest(address account, uint256 amount) external {
require(controllers[_msgSender()], "Only controllers can mint");
require(mintedByForest + amount <= forestTokenAmount, "No mint out");
mintedByForest = mintedByForest + amount;
_mint(account, amount);
}
/**
* burn $PREY token by controller
* @param account account holds $PREY token
* @param amount the amount of $PREY token to burn
*/
function burn(address account, uint256 amount) external {
require(controllers[_msgSender()], "Only controllers can mint");
_burn(account, amount);
}
/**
* enables an address to mint / burn
* @param controller the address to enable
*/
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
/**
* disables an address from minting / burning
* @param controller the address to disbale
*/
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import './LotteryBox.sol';
import "./HunterHound.sol";
contract Mintor is LotteryBox {
event MintEvent(address indexed operator, uint hunters, uint hounds, uint256[] tokenIds);
struct Minting {
uint blockNumber;
uint amount;
}
// the cost to mint in every phase
uint256 constant MINT_PRICE = .067 ether;
uint256 constant MINT_PHASE2_PRICE = 40000 ether;
uint256 constant MINT_PHASE3_PRICE = 60000 ether;
uint256 constant MINT_PHASE4_PRICE = 80000 ether;
// the amount corresponds to every hunter's alpha score
uint constant maxAlpha8Count = 500;
uint constant maxAlpha7Count = 1500;
uint constant maxAlpha6Count = 3000;
uint constant maxAlpha5Count = 5000;
// 50,000 tokens in total and mint amount in every phase
uint constant MAX_TOKENS = 50000;
uint constant PHASE1_AMOUNT = 10000;
uint constant PHASE2_AMOUNT = 10000;
uint constant PHASE3_AMOUNT = 20000;
uint constant PHASE4_AMOUNT = 10000;
// saves metadataID for next hunter
uint private alpha8Count = 1;
uint private alpha7Count = 1;
uint private alpha6Count = 1;
uint private alpha5Count = 1;
// saves metadataId for next hound
uint internal totalHoundMinted = 1;
// saves mint request of users
mapping(address => Minting) internal mintRequests;
// total minted amount
uint256 internal minted;
// total minted number of hunters
uint256 internal hunterMinted;
// recorded mint requests
uint internal requested;
/**
* check mint request
* @return blockNumber mint request block
* @return amount mint amount
* @return state mint state
* @return open NFT reavel countdown
* @return timeout NFT request reveal timeout countdown
*/
function _mintRequestState(address requestor) internal view returns (uint blockNumber, uint amount, uint state, uint open, uint timeout) {
Minting memory req = mintRequests[requestor];
blockNumber = req.blockNumber;
amount = req.amount;
state = boxState(req.blockNumber);
open = openCountdown(req.blockNumber);
timeout = timeoutCountdown(req.blockNumber);
}
/**
* create mint request, record requested block and data
*/
function _request(address requestor, uint amount) internal {
require(mintRequests[requestor].blockNumber == 0, 'Request already exists');
mintRequests[requestor] = Minting({
blockNumber: block.number,
amount: amount
});
requested = requested + amount;
}
/**
* process mint request to get random number, through which to determine hunter or hound
*/
function _receive(address requestor, HunterHound hh) internal {
Minting memory minting = mintRequests[requestor];
require(minting.blockNumber > 0, "No mint request found");
delete mintRequests[requestor];
uint random = openBox(minting.blockNumber);
uint boxResult = percentNumber(random);
uint percent = boxResult;
uint hunters = 0;
uint256[] memory tokenIds = new uint256[](minting.amount);
for (uint256 i = 0; i < minting.amount; i++) {
HunterHoundTraits memory traits;
if (i > 0 && boxResult > 0) {
random = simpleRandom(percent);
percent = percentNumber(random);
}
if (percent == 0) {
traits = selectHound();
} else if (percent >= 80) {
traits = selectHunter(random);
} else {
traits = selectHound();
}
minted = minted + 1;
hh.mintByController(requestor, minted, traits);
tokenIds[i] = minted;
if (traits.isHunter) {
hunters ++;
}
}
if (hunters > 0) {
hunterMinted = hunterMinted + hunters;
}
emit MintEvent(requestor, hunters, minting.amount - hunters, tokenIds);
}
/**
* return a hunter, if hunters run out, return a hound
* @param random make parameter random a random seed to generate another random number to determine alpha score of a hunter
* if number of hunters with corresponding alpha score runs out, it chooses the one with alpha score minus one util it runs out, otherwise it will be a hound
*
* probabilities of hunters with different alpha score and their numbers:
* alpha 8: 5% 500
* alpha 7: 15% 1500
* alpha 6: 30% 3000
* alpha 5: 50% 5000
*/
function selectHunter(uint random) private returns(HunterHoundTraits memory hh) {
random = simpleRandom(random);
uint percent = percentNumber(random);
if (percent <= 5 && alpha8Count <= maxAlpha8Count) {
hh.alpha = 8;
hh.metadataId = alpha8Count;
alpha8Count = alpha8Count + 1;
} else if (percent <= 20 && alpha7Count <= maxAlpha7Count) {
hh.alpha = 7;
hh.metadataId = alpha7Count;
alpha7Count = alpha7Count + 1;
} else if (percent <= 50 && alpha6Count <= maxAlpha6Count) {
hh.alpha = 6;
hh.metadataId = alpha6Count;
alpha6Count = alpha6Count + 1;
} else if (alpha5Count <= maxAlpha5Count) {
hh.alpha = 5;
hh.metadataId = alpha5Count;
alpha5Count = alpha5Count + 1;
} else {
return selectHound();
}
hh.isHunter = true;
}
/**
* return a hound
*/
function selectHound() private returns(HunterHoundTraits memory hh) {
hh.isHunter = false;
hh.metadataId = totalHoundMinted;
totalHoundMinted = totalHoundMinted + 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract LotteryBox {
// take 3 blocks' hash values to make a random seed
uint constant SEED_BLOCK_HASH_AMOUNT = 3;
// blackhash can only retrieve the most recent 256 blocks' hash values
uint constant MAX_BLOCK_HASH_DISTANCE = 256;
/**
* generate a simple random number using the parameter
*/
function simpleRandom(uint seed) internal view returns(uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
block.timestamp,
seed
)));
}
/**
* Using the hashes of `SEED_BLOCK_HASH_AMOUNT` previously generated blocks as random seed to generate a random number, based on height of the request block
*/
function randomNumber(uint requestBlockNumber, uint seed) internal view returns (uint256) {
bytes32[SEED_BLOCK_HASH_AMOUNT] memory blockhashs;
for (uint i = 0; i < SEED_BLOCK_HASH_AMOUNT; i++) {
blockhashs[i] = blockhash(requestBlockNumber+1+i);
}
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhashs,
seed
)));
}
/**
* request status
*/
function boxState(uint requestBlockNumber) internal view returns (uint) {
if (requestBlockNumber == 0) {
return 0; // not requested
}
if (openCountdown(requestBlockNumber) > 0) {
return 1; // waiting for reveal
}
if (timeoutCountdown(requestBlockNumber) > 0) {
return 2; // waiting to reveal the result
}
return 3; // timeout
}
/**
* reveal countdown
*/
function openCountdown(uint requestBlockNumber) internal view returns(uint) {
return countdown(requestBlockNumber, SEED_BLOCK_HASH_AMOUNT+1);
}
/**
* timeout countdown
*/
function timeoutCountdown(uint requestBlockNumber) internal view returns(uint) {
return countdown(requestBlockNumber, MAX_BLOCK_HASH_DISTANCE+1);
}
/**
* calculate countdown
*/
function countdown(uint requestBlockNumber, uint v) internal view returns(uint) {
uint diff = block.number - requestBlockNumber;
if (diff > v) {
return 0;
}
return v - diff;
}
/**
* convert big random number into less or equal to 100 random number
*/
function percentNumber(uint random) internal pure returns(uint) {
if (random > 0) {
return (random % 100) + 1;
}
return 0;
}
/**
* generate big random number through block height
*/
function openBox(uint requestBlockNumber) internal view returns (uint) {
require(openCountdown(requestBlockNumber) == 0, "Invalid block number");
if (timeoutCountdown(requestBlockNumber) > 0) {
return randomNumber(requestBlockNumber, 0);
} else {
return 0;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
struct HunterHoundTraits {
bool isHunter;
uint alpha;
uint metadataId;
}
uint constant MIN_ALPHA = 5;
uint constant MAX_ALPHA = 8;
contract HunterHound is ERC721Enumerable, Ownable {
using Strings for uint256;
// a mapping from an address to whether or not it can mint / burn
mapping(address => bool) public controllers;
// save token traits
mapping(uint256 => HunterHoundTraits) private tokenTraits;
//the base url for metadata
string baseUrl = "ipfs://QmZWmcX4jRVZtQGQY64U26wkA83QNB1msZUhjqxJEyfaWP/";
constructor() ERC721("HunterHound","HH") {
}
/**
* set base URL for metadata
*/
function setBaseUrl(string calldata baseUrl_) external onlyOwner {
baseUrl = baseUrl_;
}
/**
* get token traits
*/
function getTokenTraits(uint256 tokenId) external view returns (HunterHoundTraits memory) {
return tokenTraits[tokenId];
}
/**
* get multiple token traits
*/
function getTraitsByTokenIds(uint256[] calldata tokenIds) external view returns (HunterHoundTraits[] memory traits) {
traits = new HunterHoundTraits[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; i++) {
traits[i] = tokenTraits[tokenIds[i]];
}
}
/**
* Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
HunterHoundTraits memory s = tokenTraits[tokenId];
return string(abi.encodePacked(
baseUrl,
s.isHunter ? 'Hunter' : 'Hound',
'-',
s.alpha.toString(),
'/',
s.isHunter ? 'Hunter' : 'Hound',
'-',
s.alpha.toString(),
'-',
s.metadataId.toString(),
'.json'
));
}
/**
* return holder's entire tokens
*/
function tokensByOwner(address owner) external view returns (uint256[] memory tokenIds, HunterHoundTraits[] memory traits) {
uint totalCount = balanceOf(owner);
tokenIds = new uint256[](totalCount);
traits = new HunterHoundTraits[](totalCount);
for (uint256 i = 0; i < totalCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(owner, i);
traits[i] = tokenTraits[tokenIds[i]];
}
}
/**
* return token traits
*/
function isHunterAndAlphaByTokenId(uint256 tokenId) external view returns (bool, uint) {
HunterHoundTraits memory traits = tokenTraits[tokenId];
return (traits.isHunter, traits.alpha);
}
/**
* controller to mint a token
*/
function mintByController(address account, uint256 tokenId, HunterHoundTraits calldata traits) external {
require(controllers[_msgSender()], "Only controllers can mint");
tokenTraits[tokenId] = traits;
_safeMint(account, tokenId);
}
/**
* controller to transfer a token
*/
function transferByController(address from, address to, uint256 tokenId) external {
require(controllers[_msgSender()], "Only controllers can transfer");
_transfer(from, to, tokenId);
}
/**
* enables an address to mint / burn
* @param controller the address to enable
*/
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
/**
* disables an address from minting / burning
* @param controller the address to disbale
*/
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import './LotteryBox.sol';
import './HunterHound.sol';
import './Prey.sol';
contract Forest is LotteryBox {
event StakeEvent(address indexed operator, uint256[][] pairs);
event ClaimEvent(address indexed operator, uint256 receiveProfit, uint256 totalProfit);
event UnstakeEvent(address indexed operator, address indexed recipient, uint256 indexed tokenId, uint256 receiveProfit, uint256 totalProfit);
struct Stake{
uint timestamp;
bool hunter;
uint hounds;
uint alpha;
uint256[] tokenIds;
}
uint constant GAMBLE_CLAIM = 1;
uint constant GAMBLE_UNSTAKE = 2;
uint constant GAMBLE_UNSTAKE_GREDDY = 3;
// action 1:claim 2:unstake 3:unstake with greddy
struct Gamble {
uint action;
uint blockNumber;
}
// the minimum amount of $PREY tokens to own before unstaking
uint constant MINIMUN_UNSTAKE_AMOUNT = 20000 ether;
// every hound receives 10,000 tokens a day
uint constant PROFIT_PER_SINGLE_HOUND = 10000 ether;
// the total profit
uint constant TOTAL_PROFIT = 2400000000 ether;
// the total claimed $PREY including burned in the game
uint internal totalClaimed;
// the total bunred $PREY
uint internal totalBurned;
// staked list
mapping(address => Stake[]) internal stakes;
// record original owner of the token
mapping(uint => address) internal tokenOwners;
// record tokenId of the hunters who have corresponding alpha score
mapping(uint256 => uint256[]) internal hunterAlphaMap;
// record index of hunter tokenId in `hunterAlphaMap`
mapping(uint256 => uint256) internal hunterTokenIndices;
// staked hounds count
uint internal houndStaked;
// staked hunters count
uint internal hunterStaked;
// the number of hounds adopted by other hunters
uint internal houndsCaptured;
mapping(address => Gamble) internal gambleRequests;
/**
* When there is a gamble request
*/
modifier whenGambleRequested() {
require(gambleRequests[msg.sender].blockNumber == 0, "Unstake or claim first");
_;
}
/**
* stake submitted tokens group and transfer to the staking contract
*/
function _stake(address owner, uint256[][] calldata pairs, HunterHound hh) internal whenGambleRequested {
require(pairs.length > 0, "Tokens empty");
require(totalClaimed < TOTAL_PROFIT, "No profit");
uint totalHunter = 0;
uint totalHounds = 0;
(totalHunter, totalHounds) = _storeStake(owner, pairs, hh);
hunterStaked = hunterStaked + totalHunter;
houndStaked = houndStaked + totalHounds;
// transfer token
for (uint256 i = 0; i < pairs.length; i++) {
for (uint256 j = 0; j < pairs[i].length; j++) {
uint256 tokenId = pairs[i][j];
hh.transferByController(owner, address(this), tokenId);
}
}
emit StakeEvent(owner, pairs);
}
/**
* store staking groups
*/
function _storeStake(address owner, uint256[][] calldata paris, HunterHound hh) private returns(uint totalHunter, uint totalHounds) {
for (uint256 i = 0; i < paris.length; i++) {
uint256[] calldata tokenIds = paris[i];
uint hunters;
uint hounds;
uint256 hunterAlpha;
uint hunterIndex = 0;
(hunters, hounds, hunterAlpha, hunterIndex) = _storeTokenOwner(owner, tokenIds, hh);
require(hounds > 0 && hounds <= 3, "Must have 1-3 hound in a pair");
require(hunters <= 1, "Only be one hunter in a pair");
// in order to select a hound, a hunter must be placed in the rear of the group
require(hunters == 0 || hunterIndex == (tokenIds.length-1), "Hunter must be last one");
totalHunter = totalHunter + hunters;
totalHounds = totalHounds + hounds;
stakes[owner].push(Stake({
timestamp: block.timestamp,
hunter: hunters > 0,
hounds: hounds,
alpha: hunterAlpha,
tokenIds: tokenIds
}));
if (hunters > 0) {
uint256 hunterTokenId = tokenIds[tokenIds.length-1];
hunterTokenIndices[hunterTokenId] = hunterAlphaMap[hunterAlpha].length;
hunterAlphaMap[hunterAlpha].push(hunterTokenId);
}
}
}
/**
* record token owner in order to return $PREY token correctly to the owner in case of unstaking
*/
function _storeTokenOwner(address owner, uint[] calldata tokenIds, HunterHound hh) private
returns(uint hunters,uint hounds,uint hunterAlpha,uint hunterIndex) {
for (uint256 j = 0; j < tokenIds.length; j++) {
uint256 tokenId = tokenIds[j];
require(tokenOwners[tokenId] == address(0), "Unstake first");
require(hh.ownerOf(tokenId) == owner, "Not your token");
bool isHunter;
uint alpha;
(isHunter, alpha) = hh.isHunterAndAlphaByTokenId(tokenId);
if (isHunter) {
hunters = hunters + 1;
hunterAlpha = alpha;
hunterIndex = j;
} else {
hounds = hounds + 1;
}
tokenOwners[tokenId] = owner;
}
}
/**
* calculate and claim staked reward, if the players chooses to gamble, there's a probability to lose all rewards
*/
function _claim(address owner, Prey prey) internal {
uint requestBlockNumber = gambleRequests[owner].blockNumber;
uint totalProfit = _claimProfit(owner, false);
uint receiveProfit;
if (requestBlockNumber > 0) {
require(gambleRequests[owner].action == GAMBLE_CLAIM, "Unstake first");
uint random = openBox(requestBlockNumber);
uint percent = percentNumber(random);
if (percent <= 50) {
receiveProfit = 0;
} else {
receiveProfit = totalProfit;
}
delete gambleRequests[owner];
} else {
receiveProfit = (totalProfit * 80) / 100;
}
if (receiveProfit > 0) {
prey.mintByForest(owner, receiveProfit);
}
if (totalProfit - receiveProfit > 0) {
totalBurned = totalBurned + (totalProfit - receiveProfit);
}
emit ClaimEvent(owner, receiveProfit, totalProfit);
}
/**
* calculate stake rewards, reset timestamp in case of claiming
*/
function _collectStakeProfit(address owner, bool unstake) private returns (uint profit) {
for (uint i = 0; i < stakes[owner].length; i++) {
Stake storage stake = stakes[owner][i];
profit = profit + _caculateProfit(stake);
if (!unstake) {
stake.timestamp = block.timestamp;
}
}
require(unstake == false || profit >= MINIMUN_UNSTAKE_AMOUNT, "Minimum claim is 20000 PREY");
}
/**
* return claimable staked rewards, update `totalClaimed`
*/
function _claimProfit(address owner, bool unstake) private returns (uint) {
uint profit = _collectStakeProfit(owner, unstake);
if (totalClaimed + profit > TOTAL_PROFIT) {
profit = TOTAL_PROFIT - totalClaimed;
}
totalClaimed = totalClaimed + profit;
return profit;
}
/**
* create a gamble request in case of unstaking or claim with gambling
*/
function _requestGamble(address owner, uint action) internal whenGambleRequested {
require(stakes[owner].length > 0, 'Stake first');
require(action == GAMBLE_CLAIM || action == GAMBLE_UNSTAKE || action == GAMBLE_UNSTAKE_GREDDY, 'Invalid action');
if (action != GAMBLE_CLAIM) {
_collectStakeProfit(owner, true);
}
gambleRequests[owner] = Gamble({
action: action,
blockNumber: block.number
});
}
/**
* return gamble request status
*/
function _gambleRequestState(address requestor) internal view returns (uint blockNumber, uint action, uint state, uint open, uint timeout) {
Gamble memory req = gambleRequests[requestor];
blockNumber = req.blockNumber;
action = req.action;
state = boxState(req.blockNumber);
open = openCountdown(req.blockNumber);
timeout = timeoutCountdown(req.blockNumber);
}
/**
* claim all profits and take back staked tokens in case of unstaking
* 20% chance to lose one of the hounds and adopted by other hunter
* if players chooses to gamble, 50% chance to burn all the profits
*/
function _unstake(address owner, Prey prey, HunterHound hh) internal {
uint requestBlockNumber = gambleRequests[owner].blockNumber;
require(requestBlockNumber > 0, "No unstake request found");
uint action = gambleRequests[owner].action;
require(action == GAMBLE_UNSTAKE || action == GAMBLE_UNSTAKE_GREDDY, "Claim first");
uint256 totalProfit = _claimProfit(owner, true);
uint random = openBox(requestBlockNumber);
uint percent = percentNumber(random);
address houndRecipient;
if (percent <= 20) {
//draw a player who has a hunter in case of losing
houndRecipient= selectLuckyRecipient(owner, percent);
if (houndRecipient != address(0)) {
houndsCaptured = houndsCaptured + 1;
}
}
uint receiveProfit = totalProfit;
if (action == GAMBLE_UNSTAKE_GREDDY) {
// 50/50 chance to lose all or take all
if (percent > 0) {
random = randomNumber(requestBlockNumber, random);
percent = percentNumber(random);
if (percent <= 50) {
receiveProfit = 0;
}
} else {
receiveProfit = 0;
}
} else {
receiveProfit = (receiveProfit * 80) / 100;
}
delete gambleRequests[owner];
uint totalHunter = 0;
uint totalHound = 0;
uint256 capturedTokenId;
(totalHunter, totalHound, capturedTokenId) = _cleanOwner(percent, owner, hh, houndRecipient);
hunterStaked = hunterStaked - totalHunter;
houndStaked = houndStaked - totalHound;
delete stakes[owner];
if (receiveProfit > 0) {
prey.mintByForest(owner, receiveProfit);
}
if (totalProfit - receiveProfit > 0) {
totalBurned = totalBurned + (totalProfit - receiveProfit);
}
emit UnstakeEvent(owner, houndRecipient, capturedTokenId, receiveProfit, totalProfit);
}
/**
* delete all data on staking, if `houndRecipient` exists, use `percent` to generate a random number and choose a hound to transfer
*/
function _cleanOwner(uint percent, address owner, HunterHound hh, address houndRecipient) private returns(uint totalHunter, uint totalHound, uint256 capturedTokenId) {
uint randomRow = percent % stakes[owner].length;
for (uint256 i = 0; i < stakes[owner].length; i++) {
Stake memory stake = stakes[owner][i];
totalHound = totalHound + stake.tokenIds.length;
if (stake.hunter) {
totalHunter = totalHunter + 1;
totalHound = totalHound - 1;
uint256 hunterTokenId = stake.tokenIds[stake.tokenIds.length-1];
uint alphaHunterLength = hunterAlphaMap[stake.alpha].length;
if (alphaHunterLength > 1 && hunterTokenIndices[hunterTokenId] < (alphaHunterLength-1)) {
uint lastHunterTokenId = hunterAlphaMap[stake.alpha][alphaHunterLength - 1];
hunterTokenIndices[lastHunterTokenId] = hunterTokenIndices[hunterTokenId];
hunterAlphaMap[stake.alpha][hunterTokenIndices[hunterTokenId]] = lastHunterTokenId;
}
hunterAlphaMap[stake.alpha].pop();
delete hunterTokenIndices[hunterTokenId];
}
for (uint256 j = 0; j < stake.tokenIds.length; j++) {
uint256 tokenId = stake.tokenIds[j];
delete tokenOwners[tokenId];
// randomly select 1 hound
if (i == randomRow && houndRecipient != address(0) && (stake.tokenIds.length == 1 || j == (percent % (stake.tokenIds.length-1)))) {
hh.transferByController(address(this), houndRecipient, tokenId);
capturedTokenId = tokenId;
} else {
hh.transferByController(address(this), owner, tokenId);
}
}
}
}
/**
* of all hunters staked, choose one to adopt the hound, hunter with higher alpha score takes precedence.
* alpha 8: 50%
* alpha 7: 30%
* alpha 6: 15%
* alpha 5: 5%
*/
function selectLuckyRecipient(address owner, uint seed) private view returns (address) {
uint random = simpleRandom(seed);
uint percent = percentNumber(random);
uint alpha;
if (percent <= 5) {
alpha = 5;
} else if (percent <= 20) {
alpha = 6;
} else if (percent <= 50) {
alpha = 7;
} else {
alpha = 8;
}
uint alphaCount = 4;
uint startAlpha = alpha;
bool directionUp = true;
while(alphaCount > 0) {
alphaCount --;
uint hunterCount = hunterAlphaMap[alpha].length;
if (hunterCount != 0) {
uint index = random % hunterCount;
uint count = 0;
while(count < hunterCount) {
if (index >= hunterCount) {
index = 0;
}
address hunterOwner = tokenOwners[hunterAlphaMap[alpha][index]];
if (owner != hunterOwner) {
return hunterOwner;
}
index ++;
count ++;
}
}
if (alpha >= 8) {
directionUp = false;
alpha = startAlpha;
}
if (directionUp) {
alpha ++;
} else {
alpha --;
}
}
return address(0);
}
/**
* calculate the claimable profits of the stake
*/
function _caculateProfit(Stake memory stake) internal view returns (uint) {
uint profitPerStake = 0;
if (stake.hunter) {
profitPerStake = ((stake.hounds * PROFIT_PER_SINGLE_HOUND) * (stake.alpha + 10)) / 10;
} else {
profitPerStake = stake.hounds * PROFIT_PER_SINGLE_HOUND;
}
return (block.timestamp - stake.timestamp) * profitPerStake / 1 days;
}
/**
* take back all staked tokens in case of rescue mode
*/
function _rescue(address owner, HunterHound hh) internal {
delete gambleRequests[owner];
uint totalHound = 0;
uint totalHunter = 0;
(totalHunter, totalHound, ) = _cleanOwner(0, owner, hh, address(0));
delete stakes[owner];
houndStaked = houndStaked - totalHound;
hunterStaked = hunterStaked - totalHunter;
}
}
// 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;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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);
}
}
| * @return the token being held./ | function token() public view virtual returns (Prey) {
return _token;
}
| 13,018,072 | [
1,
2463,
326,
1147,
3832,
15770,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1147,
1435,
1071,
1476,
5024,
1135,
261,
1386,
93,
13,
288,
203,
3639,
327,
389,
2316,
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
]
|
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IWETH } from "../../interfaces/external/IWETH.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol";
/**
* @title CustomOracleNavIssuanceModule
* @author Set Protocol
*
* Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives
* a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using
* oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front
* running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset).
*/
contract CustomOracleNavIssuanceModule is ModuleBase, ReentrancyGuard {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using PreciseUnitMath for int256;
using ResourceIdentifier for IController;
using SafeMath for uint256;
using SafeCast for int256;
using SafeCast for uint256;
using SignedSafeMath for int256;
/* ============ Events ============ */
event SetTokenNAVIssued(
ISetToken indexed _setToken,
address _issuer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event SetTokenNAVRedeemed(
ISetToken indexed _setToken,
address _redeemer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event ReserveAssetAdded(
ISetToken indexed _setToken,
address _newReserveAsset
);
event ReserveAssetRemoved(
ISetToken indexed _setToken,
address _removedReserveAsset
);
event PremiumEdited(
ISetToken indexed _setToken,
uint256 _newPremium
);
event ManagerFeeEdited(
ISetToken indexed _setToken,
uint256 _newManagerFee,
uint256 _index
);
event FeeRecipientEdited(
ISetToken indexed _setToken,
address _feeRecipient
);
/* ============ Structs ============ */
struct NAVIssuanceSettings {
INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations
INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations
ISetValuer setValuer; // Optional custom set valuer. If address(0) is provided, fetch the default one from the controller
address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle
address feeRecipient; // Manager fee recipient
uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16)
uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem
uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle
// prices paid by user to the SetToken, which prevents arbitrage and oracle front running
uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager)
uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the SetToken's position multiplier
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
// During redeem, represents post-premium value
uint256 protocolFees; // Total protocol fees (direct + manager revenue share)
uint256 managerFee; // Total manager fee paid in reserve asset
uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken
// When redeeming, quantity of reserve asset sent to redeemer
uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee
// When redeeming, quantity of SetToken redeemed
uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action
uint256 newSetTokenSupply; // SetToken supply after issue/redeem action
int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem
uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem
}
/* ============ State Variables ============ */
// Wrapped ETH address
IWETH public immutable weth;
// Mapping of SetToken to NAV issuance settings struct
mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings;
// Mapping to efficiently check a SetToken's reserve asset validity
// SetToken => reserveAsset => isReserveAsset
mapping(ISetToken => mapping(address => bool)) public isReserveAsset;
/* ============ Constants ============ */
// 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 1 index stores the manager fee percentage in managerFees array, charged on redeem
uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1;
// 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1;
// 2 index stores the direct protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
// 3 index stores the direct protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3;
/* ============ Constructor ============ */
/**
* @param _controller Address of controller contract
* @param _weth Address of wrapped eth
*/
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to issue with
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issue(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity);
_callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo);
_handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo);
}
/**
* Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issueWithEther(
ISetToken _setToken,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
payable
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
weth.deposit{ value: msg.value }();
_validateCommon(_setToken, address(weth), msg.value);
_callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferWETHAndHandleFees(_setToken, issueInfo);
_handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo);
}
/**
* Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available reserve units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to redeem with
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeem(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer the reserve asset back to the user
_setToken.strictInvokeTransfer(
_reserveAsset,
_to,
redeemInfo.netFlowQuantity
);
_handleRedemptionFees(_setToken, _reserveAsset, redeemInfo);
_handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo);
}
/**
* Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available WETH units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeemIntoEther(
ISetToken _setToken,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address payable _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, address(weth), _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer WETH from SetToken to module
_setToken.strictInvokeTransfer(
address(weth),
address(this),
redeemInfo.netFlowQuantity
);
weth.withdraw(redeemInfo.netFlowQuantity);
_to.transfer(redeemInfo.netFlowQuantity);
_handleRedemptionFees(_setToken, address(weth), redeemInfo);
_handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo);
}
/**
* SET MANAGER ONLY. Add an allowed reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to add
*/
function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists");
navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset);
isReserveAsset[_setToken][_reserveAsset] = true;
emit ReserveAssetAdded(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Remove a reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to remove
*/
function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist");
navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset);
delete isReserveAsset[_setToken][_reserveAsset];
emit ReserveAssetRemoved(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Edit the premium percentage
*
* @param _setToken Instance of the SetToken
* @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%)
*/
function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) {
require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed");
navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage;
emit PremiumEdited(_setToken, _premiumPercentage);
}
/**
* SET MANAGER ONLY. Edit manager fee
*
* @param _setToken Instance of the SetToken
* @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%)
* @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee
*/
function editManagerFee(
ISetToken _setToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidSet(_setToken)
{
require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed");
navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex);
}
/**
* SET MANAGER ONLY. Edit the manager fee recipient
*
* @param _setToken Instance of the SetToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient;
emit FeeRecipientEdited(_setToken, _managerFeeRecipient);
}
/**
* SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets,
* fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional.
* Address(0) means that no hook will be called.
*
* @param _setToken Instance of the SetToken to issue
* @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters
*/
function initialize(
ISetToken _setToken,
NAVIssuanceSettings memory _navIssuanceSettings
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0");
require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%");
require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max");
require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max");
require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max");
require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
// Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0
require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0");
for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) {
require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique");
isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true;
}
navIssuanceSettings[_setToken] = _navIssuanceSettings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Issuance settings and
* reserve asset states are deleted.
*/
function removeModule() external override {
ISetToken setToken = ISetToken(msg.sender);
for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) {
delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]];
}
delete navIssuanceSettings[setToken];
}
receive() external payable {}
/* ============ External Getter Functions ============ */
function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) {
return navIssuanceSettings[_setToken].reserveAssets;
}
function getIssuePremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity);
}
function getRedeemPremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
}
function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) {
return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
}
/**
* Get the expected SetTokens minted to recipient on issuance
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return uint256 Expected SetTokens to be minted to recipient
*/
function getExpectedSetTokenIssueQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
(,, uint256 netReserveFlow) = _getFees(
_setToken,
_reserveAssetQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
uint256 setTotalSupply = _setToken.totalSupply();
return _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
netReserveFlow,
setTotalSupply
);
}
/**
* Get the expected reserve asset to be redeemed
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return uint256 Expected reserve asset quantity redeemed
*/
function getExpectedReserveRedeemQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 netReserveFlows) = _getFees(
_setToken,
preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
return netReserveFlows;
}
/**
* Checks if issue is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return bool Returns true if issue is valid
*/
function isIssueValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
return _reserveAssetQuantity != 0
&& isReserveAsset[_setToken][_reserveAsset]
&& setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply;
}
/**
* Checks if redeem is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return bool Returns true if redeem is valid
*/
function isRedeemValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
if (
_setTokenQuantity == 0
|| !isReserveAsset[_setToken][_reserveAsset]
|| setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity)
) {
return false;
} else {
uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 expectedRedeemQuantity) = _getFees(
_setToken,
totalRedeemValue,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity;
}
}
/* ============ Internal Functions ============ */
function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view {
require(_quantity > 0, "Quantity must be > 0");
require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset");
}
function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view {
// Check that total supply is greater than min supply needed for issuance
// Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0
require(
_issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable issuance"
);
require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken");
}
function _validateRedemptionInfo(
ISetToken _setToken,
uint256 _minReserveReceiveQuantity,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
{
// Check that new supply is more than min supply needed for redemption
// Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0
require(
_redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable redemption"
);
require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity");
}
function _createIssuanceInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousSetTokenSupply = _setToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees(
_setToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.setTokenQuantity = _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
issueInfo.netFlowQuantity,
issueInfo.previousSetTokenSupply
);
(issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo);
issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo);
return issueInfo;
}
function _createRedemptionInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory redeemInfo;
redeemInfo.setTokenQuantity = _setTokenQuantity;
redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees(
_setToken,
redeemInfo.preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
redeemInfo.previousSetTokenSupply = _setToken.totalSupply();
(redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo);
redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo);
return redeemInfo;
}
/**
* Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients
*/
function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal {
transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
/**
* Transfer WETH from module to SetToken and fees from module to appropriate fee recipients
*/
function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal {
weth.transfer(address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
function _handleIssueStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _issueInfo
)
internal
{
_setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit);
_setToken.mint(_to, _issueInfo.setTokenQuantity);
emit SetTokenNAVIssued(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerIssuanceHook),
_issueInfo.setTokenQuantity,
_issueInfo.managerFee,
_issueInfo.protocolFees
);
}
function _handleRedeemStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _redeemInfo
)
internal
{
_setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit);
emit SetTokenNAVRedeemed(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerRedemptionHook),
_redeemInfo.setTokenQuantity,
_redeemInfo.managerFee,
_redeemInfo.protocolFees
);
}
function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal {
// Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee
payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees);
// Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee
if (_redeemInfo.managerFee > 0) {
_setToken.strictInvokeTransfer(
_reserveAsset,
navIssuanceSettings[_setToken].feeRecipient,
_redeemInfo.managerFee
);
}
}
/**
* Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the issuance premium.
*/
function _getIssuePremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _reserveAssetQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the redemption premium.
*/
function _getRedeemPremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _setTokenQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as follows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _setToken Instance of the SetToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller
* @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
* @return uint256 Net reserve to user net of fees
*/
function _getFees(
ISetToken _setToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_setToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee);
return (protocolFees, managerFee, netReserveFlow);
}
function _getProtocolAndManagerFeePercentages(
ISetToken _setToken,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns(uint256, uint256)
{
// Get protocol fee percentages
uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex);
uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex);
uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (totalProtocolFeePercentage, managerRevenueSharePercentage);
}
function _getSetTokenMintQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _netReserveFlows, // Value of reserve asset net of fees
uint256 _setTotalSupply
)
internal
view
returns (uint256)
{
uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows);
uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage);
// If the set manager provided a custom valuer at initialization time, use it. Otherwise get it from the controller
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18)
// Reverts if price is not found
uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals);
// Calculate SetTokens to mint to issuer
uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium);
return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator);
}
function _getRedeemReserveQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (uint256)
{
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18)
// Reverts if price is not found
uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset);
uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals);
uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage);
return prePremiumReserveQuantity.sub(premiumQuantity);
}
/**
* The new position multiplier is calculated as follows:
* inflationPercentage = (newSupply - oldSupply) / newSupply
* newMultiplier = (1 - inflationPercentage) * positionMultiplier
*/
function _getIssuePositionMultiplier(
ISetToken _setToken,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256, int256)
{
// Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down
uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_issueInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down
*
* The new position multiplier is calculated as follows:
* deflationPercentage = (oldSupply - newSupply) / newSupply
* newMultiplier = (1 + deflationPercentage) * positionMultiplier
*/
function _getRedeemPositionMultiplier(
ISetToken _setToken,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256, int256)
{
uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_redeemInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity
* newUnit = totalReserve / newSetTokenSupply
*/
function _getIssuePositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalReserve = existingUnit
.preciseMul(_issueInfo.previousSetTokenSupply)
.add(_issueInfo.netFlowQuantity);
return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut
* newUnit = totalReserve / newSetTokenSupply
*/
function _getRedeemPositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply);
uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee);
// Require withdrawable quantity is greater than existing collateral
require(totalExistingUnits >= outflow, "Must be greater than total available collateral");
return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply);
}
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _caller,
address _to
)
internal
{
INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook;
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to);
}
}
/**
* If a pre-redeem hook has been configured, call the external-protocol contract.
*/
function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal {
INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook;
if (address(preRedeemHook) != address(0)) {
preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to);
}
}
/**
* If a custom set valuer has been configured, use it. Otherwise fetch the default one form the
* controller.
*/
function _getSetValuer(ISetToken _setToken) internal view returns (ISetValuer) {
ISetValuer customValuer = navIssuanceSettings[_setToken].setValuer;
return address(customValuer) == address(0) ? controller.getSetValuer() : customValuer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/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 returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// 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;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// 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, 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "./ISetToken.sol";
interface INAVIssuanceHook {
function invokePreIssueHook(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _sender,
address _to
)
external;
function invokePreRedeemHook(
ISetToken _setToken,
uint256 _redeemQuantity,
address _sender,
address _to
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
import { IController } from "../../interfaces/IController.sol";
import { IModule } from "../../interfaces/IModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "./Invoke.sol";
import { Position } from "./Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "./ResourceIdentifier.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IController } from "../../interfaces/IController.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// 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;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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);
}
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
} | * Instructs the SetToken to wrap the passed quantity of ETH @param _setToken SetToken instance to invoke @param _weth WETH address @param _quantity The quantity to unwrap/ | function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
| 91,286 | [
1,
382,
1697,
87,
326,
1000,
1345,
358,
2193,
326,
2275,
10457,
434,
512,
2455,
225,
389,
542,
1345,
3639,
1000,
1345,
791,
358,
4356,
225,
389,
91,
546,
5411,
678,
1584,
44,
1758,
225,
389,
16172,
3639,
1021,
10457,
358,
11014,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4356,
2964,
59,
1584,
44,
12,
45,
694,
1345,
389,
542,
1345,
16,
1758,
389,
91,
546,
16,
2254,
5034,
389,
16172,
13,
2713,
288,
203,
3639,
1731,
3778,
745,
751,
273,
24126,
18,
3015,
1190,
5374,
2932,
323,
1724,
1435,
8863,
203,
3639,
389,
542,
1345,
18,
14407,
24899,
91,
546,
16,
389,
16172,
16,
745,
751,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xa143981F3eC758296a1575146eaB03ef047b7e40/sources/WTFToken.sol | * @title WTF Token Network Token @dev ERC20 WTF Token Network Token (WTF) WTF Tokens are divisible by 1e8 (100,000,000) base units referred to as 'Grains'. WTF are displayed using 8 decimal places of precision. 1 WTF is equivalent to: 100000000 == 1 108 == 1e8 == One Hundred Million Grains 10 Million WTF (total supply) is equivalent to: 1000000000000000 == 10000000 108 == 1e15 == One Quadrillion Grains All initial WTF Grains are assigned to the creator of this contract./ | contract WTFToken is BurnableToken, Pausable {
uint256 public sellPrice;
function WTFToken() {
sellPrice = 0;
}
function transfer(address _to, uint256 _value) whenNotPaused returns (bool) {
require(_to != address(0));
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused returns (bool) {
require(_to != address(0));
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function getPrice() constant returns (uint256 _sellPrice) {
return sellPrice;
}
function setPrice(uint256 newSellPrice) external onlyOwner returns (bool success) {
require(newSellPrice > 0);
sellPrice = newSellPrice;
return true;
}
function sell(uint256 amount) external returns (uint256 revenue){
}
function getTokens(uint256 amount) onlyOwner external returns (bool success) {
require(balances[this] >= amount);
balances[msg.sender] = balances[msg.sender].add(amount);
balances[this] = balances[this].sub(amount);
Transfer(this, msg.sender, amount);
return true;
}
function sendEther() payable onlyOwner external returns (bool success) {
return true;
}
function getEther(uint256 amount) onlyOwner external returns (bool success) {
require(amount > 0);
msg.sender.transfer(amount);
return true;
}
} | 11,010,068 | [
1,
8588,
42,
225,
3155,
5128,
3155,
225,
4232,
39,
3462,
678,
17963,
225,
3155,
5128,
3155,
261,
8588,
42,
13,
678,
17963,
13899,
854,
3739,
18932,
635,
404,
73,
28,
261,
6625,
16,
3784,
16,
3784,
13,
1026,
4971,
29230,
358,
487,
296,
14571,
2679,
10332,
678,
17963,
854,
10453,
1450,
1725,
6970,
12576,
434,
6039,
18,
404,
678,
17963,
353,
7680,
358,
30,
282,
2130,
9449,
422,
404,
225,
23515,
422,
404,
73,
28,
422,
6942,
670,
1074,
1118,
490,
737,
285,
10812,
2679,
1728,
490,
737,
285,
678,
17963,
261,
4963,
14467,
13,
353,
7680,
358,
30,
282,
2130,
12648,
11706,
422,
2130,
11706,
225,
23515,
422,
404,
73,
3600,
422,
6942,
27258,
86,
737,
285,
10812,
2679,
4826,
2172,
678,
17963,
10812,
2679,
854,
6958,
358,
326,
11784,
434,
333,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
678,
17963,
1345,
353,
605,
321,
429,
1345,
16,
21800,
16665,
288,
203,
203,
225,
2254,
5034,
1071,
357,
80,
5147,
31,
203,
203,
225,
445,
678,
17963,
1345,
1435,
288,
203,
565,
357,
80,
5147,
273,
374,
31,
203,
225,
289,
203,
203,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
327,
2240,
18,
13866,
24899,
869,
16,
389,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
327,
2240,
18,
13866,
1265,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
565,
327,
2240,
18,
12908,
537,
24899,
87,
1302,
264,
16,
389,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
25930,
1435,
5381,
1135,
261,
11890,
5034,
389,
87,
1165,
5147,
13,
288,
203,
1377,
327,
357,
80,
5147,
31,
203,
225,
289,
203,
203,
225,
445,
444,
5147,
12,
11890,
5034,
30826,
1165,
5147,
13,
3903,
1338,
5541,
1135,
261,
6430,
2216,
13,
288,
203,
1377,
2583,
12,
2704,
55,
1165,
5147,
405,
374,
1769,
203,
1377,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-17
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/token/ERC20/behaviours/ERC20Decimals.sol
pragma solidity ^0.8.0;
/**
* @title ERC20Decimals
* @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot.
*/
contract PAW is ERC20 {
uint8 immutable private _decimals = 18;
uint256 private _totalSupply = 77777777777777 * 10 ** 18;
/**
* @dev Sets the value of the `decimals`. This value is immutable, it can only be
* set once during construction.
*/
constructor () ERC20('A Gatherers Dream', 'PAW') {
_mint(_msgSender(), _totalSupply);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
} | * @title ERC20Decimals @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot./ | contract PAW is ERC20 {
uint8 immutable private _decimals = 18;
uint256 private _totalSupply = 77777777777777 * 10 ** 18;
constructor () ERC20('A Gatherers Dream', 'PAW') {
_mint(_msgSender(), _totalSupply);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
} | 6,699,357 | [
1,
654,
39,
3462,
31809,
225,
25379,
434,
326,
4232,
39,
3462,
31809,
18,
10021,
434,
288,
654,
39,
3462,
97,
716,
4831,
15105,
2502,
4694,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
453,
12999,
353,
4232,
39,
3462,
288,
203,
565,
2254,
28,
11732,
3238,
389,
31734,
273,
6549,
31,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
273,
2371,
4700,
4700,
4700,
4700,
4700,
14509,
380,
1728,
2826,
6549,
31,
203,
203,
203,
565,
3885,
1832,
4232,
39,
3462,
2668,
37,
25868,
414,
463,
793,
2187,
296,
4066,
59,
6134,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
/**
* Request testnet LINK and ETH here: https://faucets.chain.link/
* Find information on LINK Token Contracts and get the latest ETH and LINK faucets here: https://docs.chain.link/docs/link-token-contracts/
*/
/**
* THIS IS AN EXAMPLE CONTRACT WHICH USES HARDCODED VALUES FOR CLARITY.
* PLEASE DO NOT USE THIS CODE IN PRODUCTION.
*/
contract PredictionMarket is ChainlinkClient {
using Chainlink for Chainlink.Request;
uint256 public drivernumber = 0;
bool public isComplete = false;
address public NFTContractAddress;
address public VRFContractAddress = 0xB082580355b203ACD731D82CD02A5404661E1907;
address private oracle;
bytes32 private jobId;
uint256 private fee;
address private adminAddress;
uint256 public totalPrizePool;
bool public marketsOpen = true;
uint256 totalSharesBought = 0;
mapping(uint256 => MarketData) public marketData;
mapping(address => bool) public claimedMap;
address[] private accounts;
mapping(address => uint256) public vrfRandoms;
modifier onlyAdmin() {
require(adminAddress == msg.sender, '!admin');
_;
}
event SharesBought(
uint256 indexed marketId,
uint256 shares,
address buyer
);
event PrizeClaimed(
uint256 indexed marketId,
uint256 amount,
address buyer
);
/**
* Network: Kovan
* Oracle: 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8 (Chainlink Devrel
* Node)
* Job ID: d5270d1c311941d0b08bead21fea7747
* Fee: 0.1 LINK
*/
constructor() {
setPublicChainlinkToken();
oracle = 0x765aCc258f3a7b2D8d103D1A9310fc51b07D5425;
jobId = "2146a7c3927545e7a7fe2b40023670a8";
fee = 0.1 * 10 ** 18; // (Varies by network and job)
adminAddress = msg.sender;
}
/**
* Create a Chainlink request to retrieve API response, find the target
* data, then multiply by 1000000000000000000 (to remove decimal places from data).
*/
function requestPosition() public onlyAdmin() returns (bytes32 requestId)
{
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("path", "data,MRData,RaceTable,Races,0,Results,0,number");
// Multiply the result by 1000000000000000000 to remove decimals
int timesAmount = 10**18;
request.addInt("times", timesAmount);
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/**
* Receive the response in the form of uint256
*/
function fulfill(bytes32 _requestId, uint256 _drivernumber) public recordChainlinkFulfillment(_requestId)
{
marketsOpen = false;
drivernumber = _drivernumber;
isComplete = true;
}
// function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract
/*
*The prediction market part.
*
*/
struct MarketData {
string name;
uint256 driverNumber;
uint256 sharesSold;
bool payout;
bool created;
}
mapping(address => mapping( uint256 => uint256 ) ) public marketSharesOwned;
function createMarket(string memory _name, uint256 _driverNumber ) external onlyAdmin() {
marketData[_driverNumber] = MarketData(
_name,
_driverNumber,
0,
false,
true
);
}
function createMarket(string memory _name, uint256[] memory _driverNumbers ) external onlyAdmin() {
for ( uint256 i = 0; i < _driverNumbers.length; i++ ) {
marketData[_driverNumbers[i]] = MarketData(
_name,
_driverNumbers[i],
0,
false,
true
);
}
}
function marketExists(uint256 _marketId) public view returns (bool) {
return marketData[_marketId].created;
}
function getSharesSold (uint256 _marketId) external view returns(uint256) {
return marketData[_marketId].sharesSold;
}
function getMarketName (uint256 _marketId) external view returns(string memory) {
return marketData[_marketId].name;
}
function getDriverNumber (uint256 _marketId) external view returns(uint256) {
return marketData[_marketId].driverNumber;
}
function willPayout (uint256 _marketId) external view returns(bool) {
return marketData[_marketId].payout;
}
function getSharesOwned(uint256 _idMarket) external view returns (uint256) {
return marketSharesOwned[msg.sender][_idMarket];
}
function claim(address payable receiver, uint256 _marketId) external returns(bool success ,bytes memory returnData) {
require( marketExists(_marketId), 'Market does not exist' );
require( marketData[_marketId].payout, 'Market is not paying out' );
require( marketSharesOwned[receiver][_marketId] > 0, 'No shares owned' );
uint256 payout = ( 100 * marketSharesOwned[receiver][_marketId] * totalPrizePool / marketData[_marketId].sharesSold ) / 100;
claimedMap[receiver] = true;
marketSharesOwned[receiver][_marketId] = 0;
receiver.transfer( payout );
emit PrizeClaimed(_marketId,payout,msg.sender);
(success,returnData) = address(NFTContractAddress).call{gas: 1000000}(abi.encodeWithSignature("addToWhiteList(address)", msg.sender )); //not really sure this should be the return from this function
}
function claimAmount(address payable receiver, uint256 _marketId) external view returns(uint256) {
uint256 payout = ( 100 * marketSharesOwned[receiver][_marketId] * totalPrizePool / marketData[_marketId].sharesSold ) / 100;
return payout;
}
function canClaim() external view returns (bool) {
return marketSharesOwned[msg.sender][drivernumber] > 0 && marketData[drivernumber].payout;
}
function claimed(address claimer) external view returns (bool) {
return claimedMap[claimer];
}
uint baseRate = 200000000000000; // close to a dollar
uint rateAdjustment = 200000000000000;
function getSharePrice(uint256 _idMarket) public view returns (uint256) {
if ( totalSharesBought == 0 ) {
return baseRate;
}
uint plus = ( marketData[_idMarket].sharesSold * (10**2) ) / totalSharesBought;
uint256 price = baseRate + ( ( plus * rateAdjustment ) / 100 );
return price;
}
function buyShares(uint256 _idMarket, uint256 _numberOfTokens) payable external {
require( marketsOpen, 'Markets are closed!' );
require( msg.value == ( getSharePrice(_idMarket) * _numberOfTokens ), 'Insufficent value' );
require( marketExists(_idMarket), 'Market does not exist' );
marketData[_idMarket].sharesSold += _numberOfTokens;
marketSharesOwned[msg.sender][_idMarket] += _numberOfTokens;
totalSharesBought += _numberOfTokens;
addAccount(msg.sender);
emit PrizeClaimed(_idMarket,_numberOfTokens,msg.sender);
}
function addAccount(address buyer) private {
bool found = false;
for (uint i=0; i < accounts.length; i++) {
if (buyer == accounts[i]) {
found = true;
}
}
if ( ! found ) {
accounts.push(buyer);
}
}
/*
Admin and dev functions
*/
function claimAll(address payable reciever) public onlyAdmin() {
reciever.transfer( address(this).balance );
}
function devSetDriverNumber(uint256 _driver) public onlyAdmin() {
drivernumber = _driver;
marketData[drivernumber].payout = true;
}
function processResults () external onlyAdmin() {
require( drivernumber > 0, 'Market not ready to process!' );
marketData[drivernumber].payout = true;
(,bytes memory randomBytes) = address(VRFContractAddress).call{gas: 1000000}(abi.encodeWithSignature("getRandomNumber()", msg.sender ));
expand(abi.decode(randomBytes, (uint256)));
}
function expand(uint256 randomValue) private {
for (uint256 i = 0; i < accounts.length; i++) {
vrfRandoms[accounts[i]] = uint256(keccak256(abi.encode(randomValue, i))) % 10;
}
}
function closeMarkets() public onlyAdmin() returns (bool) {
marketsOpen = false;
totalPrizePool = address(this).balance;
return marketsOpen;
}
function openMarkets() public onlyAdmin() returns (bool) {
marketsOpen = true;
return marketsOpen;
}
function setNFTContractAddress(address contractAddress) external onlyAdmin() {
NFTContractAddress = contractAddress;
}
function testWhiteList(address contractAddress) external onlyAdmin() returns (bool success ,bytes memory returnData) {
(success,returnData) = address(contractAddress).call{gas: 1000000}(abi.encodeWithSignature("addToWhiteList(address)", msg.sender ));
}
}
| * Create a Chainlink request to retrieve API response, find the target data, then multiply by 1000000000000000000 (to remove decimal places from data)./ Multiply the result by 1000000000000000000 to remove decimals Sends the request | function requestPosition() public onlyAdmin() returns (bytes32 requestId)
{
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("path", "data,MRData,RaceTable,Races,0,Results,0,number");
int timesAmount = 10**18;
request.addInt("times", timesAmount);
return sendChainlinkRequestTo(oracle, request, fee);
}
| 1,763,205 | [
1,
1684,
279,
7824,
1232,
590,
358,
4614,
1491,
766,
16,
1104,
326,
1018,
501,
16,
1508,
10194,
635,
2130,
12648,
12648,
261,
869,
1206,
6970,
12576,
628,
501,
2934,
19,
5991,
1283,
326,
563,
635,
2130,
12648,
12648,
358,
1206,
15105,
2479,
87,
326,
590,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
590,
2555,
1435,
1071,
1338,
4446,
1435,
1135,
261,
3890,
1578,
14459,
13,
7010,
565,
288,
203,
3639,
7824,
1232,
18,
691,
3778,
590,
273,
1361,
3893,
1232,
691,
12,
4688,
548,
16,
1758,
12,
2211,
3631,
333,
18,
2706,
5935,
18,
9663,
1769,
203,
3639,
590,
18,
1289,
2932,
803,
3113,
315,
892,
16,
23464,
751,
16,
54,
623,
1388,
16,
54,
2307,
16,
20,
16,
3447,
16,
20,
16,
2696,
8863,
203,
540,
203,
3639,
509,
4124,
6275,
273,
1728,
636,
2643,
31,
203,
3639,
590,
18,
1289,
1702,
2932,
8293,
3113,
4124,
6275,
1769,
203,
540,
203,
3639,
327,
1366,
3893,
1232,
691,
774,
12,
280,
16066,
16,
590,
16,
14036,
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
]
|
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./interfaces/IWnDGame.sol";
import "./interfaces/IWnD.sol";
import "./interfaces/IGP.sol";
import "./interfaces/ITower.sol";
import "./interfaces/ISacrificialAlter.sol";
import "hardhat/console.sol";
contract Tower is ITower, Ownable, ReentrancyGuard, IERC721Receiver, Pausable {
// maximum rank for a Wizard/Dragon
uint8 public constant MAX_RANK = 8;
// struct to store a stake's token, owner, and earning values
struct Stake {
uint16 tokenId;
uint80 value;
address owner;
}
struct Stats {
uint16 numWizardsStaked;
uint16 numDragonsStaked;
uint16 totalRankStaked;
}
event TokenStaked(address owner, uint256 tokenId, uint256 value);
event WizardClaimed(uint256 tokenId, uint256 earned, bool unstaked);
event DragonClaimed(uint256 tokenId, uint256 earned, bool unstaked);
// reference to the WnD NFT contract
IWnD public wndNFT;
// reference to the WnD NFT contract
IWnDGame public wndGame;
// reference to the $GP contract for minting $GP earnings
IGP public gpToken;
// maps tokenId to stake
mapping(uint256 => Stake) public tower;
// maps rank to all Dragon staked with that rank
mapping(uint256 => Stake[]) public flight;
// tracks location of each Dragon in Flight
mapping(uint256 => uint256) public flightIndices;
// any rewards distributed when no dragons are staked
uint256 public unaccountedRewards = 0;
// amount of $GP due for each rank point staked
uint256 public gpPerRank = 0;
// wizards earn 12000 $GP per day
uint256 public constant DAILY_GP_RATE = 12000 ether;
// wizards must have 2 days worth of $GP to unstake or else they're still guarding the tower
uint256 public constant MINIMUM_TO_EXIT = 2 days;
// dragons take a 20% tax on all $GP claimed
uint256 public constant GP_CLAIM_TAX_PERCENTAGE = 20;
// there will only ever be (roughly) 2.4 billion $GP earned through staking
uint256 public constant MAXIMUM_GLOBAL_GP = 2880000000 ether;
uint256 public treasureChestTypeId;
// amount of $GP earned so far
uint256 public totalGPEarned;
// the last time $GP was claimed
uint256 public lastClaimTimestamp;
Stats public stats;
// emergency rescue to allow unstaking without any checks but without $GP
bool public rescueEnabled = false;
/**
*/
constructor() {
_pause();
}
/** CRITICAL TO SETUP */
modifier requireContractsSet() {
require(address(wndNFT) != address(0) && address(gpToken) != address(0)
&& address(wndGame) != address(0), "Contracts not set");
_;
}
function setContracts(address _wndNFT, address _gp, address _wndGame) external onlyOwner {
wndNFT = IWnD(_wndNFT);
gpToken = IGP(_gp);
wndGame = IWnDGame(_wndGame);
}
function setTreasureChestId(uint256 typeId) external onlyOwner {
treasureChestTypeId = typeId;
}
/** STAKING */
/**
* adds Wizards and Dragons to the Tower and Flight
* @param account the address of the staker
* @param tokenIds the IDs of the Wizards and Dragons to stake
*/
function addManyToTowerAndFlight(address account, uint16[] calldata tokenIds) external override nonReentrant {
require(tx.origin == _msgSender() || _msgSender() == address(wndGame), "Only EOA");
require(account == tx.origin, "account to sender mismatch");
for (uint i = 0; i < tokenIds.length; i++) {
if (_msgSender() != address(wndGame)) { // dont do this step if its a mint + stake
require(wndNFT.ownerOf(tokenIds[i]) == _msgSender(), "You don't own this token");
wndNFT.transferFrom(_msgSender(), address(this), tokenIds[i]);
} else if (tokenIds[i] == 0) {
continue; // there may be gaps in the array for stolen tokens
}
if (isWizard(tokenIds[i]))
_addWizardToTower(account, tokenIds[i]);
else
_addDragonToFlight(account, tokenIds[i]);
}
}
/**
* adds a single Wizard to the Tower
* @param account the address of the staker
* @param tokenId the ID of the Wizard to add to the Tower
*/
function _addWizardToTower(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {
tower[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
stats.numWizardsStaked += 1;
emit TokenStaked(account, tokenId, block.timestamp);
}
/**
* adds a single Dragon to the Flight
* @param account the address of the staker
* @param tokenId the ID of the Dragon to add to the Flight
*/
function _addDragonToFlight(address account, uint256 tokenId) internal {
uint8 rank = _rankForDragon(tokenId);
stats.totalRankStaked += rank; // Portion of earnings ranges from 8 to 5
flightIndices[tokenId] = flight[rank].length; // Store the location of the dragon in the Flight
flight[rank].push(Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(gpPerRank)
})); // Add the dragon to the Flight
stats.numDragonsStaked += 1;
emit TokenStaked(account, tokenId, gpPerRank);
}
/** CLAIMING / UNSTAKING */
/**
* realize $GP earnings and optionally unstake tokens from the Tower / Flight
* to unstake a Wizard it will require it has 2 days worth of $GP unclaimed
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
*/
function claimManyFromTowerAndFlight(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings nonReentrant {
require(tx.origin == _msgSender() || _msgSender() == address(wndGame), "Only EOA");
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (isWizard(tokenIds[i])) {
owed += _claimWizardFromTower(tokenIds[i], unstake);
}
else {
owed += _claimDragonFromFlight(tokenIds[i], unstake);
}
}
gpToken.updateOriginAccess();
if (owed == 0) {
return;
}
gpToken.mint(_msgSender(), owed);
}
/**
* realize $GP earnings for a single Wizard and optionally unstake it
* if not unstaking, pay a 20% tax to the staked Dragons
* if unstaking, there is a 50% chance all $GP is stolen
* @param tokenId the ID of the Wizards to claim earnings from
* @param unstake whether or not to unstake the Wizards
* @return owed - the amount of $GP earned
*/
function _claimWizardFromTower(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = tower[tokenId];
require(stake.owner == _msgSender(), "Don't own the given token");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "Still guarding the tower");
if (totalGPEarned < MAXIMUM_GLOBAL_GP) {
owed = (block.timestamp - stake.value) * DAILY_GP_RATE / 1 days;
} else if (stake.value > lastClaimTimestamp) {
owed = 0; // $GP production stopped already
} else {
owed = (lastClaimTimestamp - stake.value) * DAILY_GP_RATE / 1 days; // stop earning additional $GP if it's all been earned
}
if (unstake) {
if (random(tokenId) & 1 == 1) { // 50% chance of all $GP stolen
_payDragonTax(owed);
owed = 0;
}
delete tower[tokenId];
stats.numWizardsStaked -= 1;
// Always transfer last to guard against reentrance
wndNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Wizard
} else {
_payDragonTax(owed * GP_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked dragons
owed = owed * (100 - GP_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Wizard owner
tower[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}); // reset stake
}
emit WizardClaimed(tokenId, owed, unstake);
}
/**
* realize $GP earnings for a single Dragon and optionally unstake it
* Dragons earn $GP proportional to their rank
* @param tokenId the ID of the Dragon to claim earnings from
* @param unstake whether or not to unstake the Dragon
* @return owed - the amount of $GP earned
*/
function _claimDragonFromFlight(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(wndNFT.ownerOf(tokenId) == address(this), "Doesn't own token");
uint8 rank = _rankForDragon(tokenId);
Stake memory stake = flight[rank][flightIndices[tokenId]];
require(stake.owner == _msgSender(), "Doesn't own token");
owed = (rank) * (gpPerRank - stake.value); // Calculate portion of tokens based on Rank
if (unstake) {
stats.totalRankStaked -= rank; // Remove rank from total staked
stats.numDragonsStaked -= 1;
Stake memory lastStake = flight[rank][flight[rank].length - 1];
flight[rank][flightIndices[tokenId]] = lastStake; // Shuffle last Dragon to current position
flightIndices[lastStake.tokenId] = flightIndices[tokenId];
flight[rank].pop(); // Remove duplicate
delete flightIndices[tokenId]; // Delete old mapping
// Always remove last to guard against reentrance
wndNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Dragon
} else {
flight[rank][flightIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(gpPerRank)
}); // reset stake
}
emit DragonClaimed(tokenId, owed, unstake);
}
/**
* emergency unstake tokens
* @param tokenIds the IDs of the tokens to claim earnings from
*/
function rescue(uint256[] calldata tokenIds) external nonReentrant {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint8 rank;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isWizard(tokenId)) {
stake = tower[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete tower[tokenId];
stats.numWizardsStaked -= 1;
wndNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Wizards
emit WizardClaimed(tokenId, 0, true);
} else {
rank = _rankForDragon(tokenId);
stake = flight[rank][flightIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
stats.totalRankStaked -= rank; // Remove Rank from total staked
stats.numDragonsStaked -= 1;
lastStake = flight[rank][flight[rank].length - 1];
flight[rank][flightIndices[tokenId]] = lastStake; // Shuffle last Dragon to current position
flightIndices[lastStake.tokenId] = flightIndices[tokenId];
flight[rank].pop(); // Remove duplicate
delete flightIndices[tokenId]; // Delete old mapping
wndNFT.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Dragon
emit DragonClaimed(tokenId, 0, true);
}
}
}
/** ACCOUNTING */
/**
* add $GP to claimable pot for the Flight
* @param amount $GP to add to the pot
*/
function _payDragonTax(uint256 amount) internal {
if (stats.totalRankStaked == 0) { // if there's no staked dragons
unaccountedRewards += amount; // keep track of $GP due to dragons
return;
}
// makes sure to include any unaccounted $GP
gpPerRank += (amount + unaccountedRewards) / stats.totalRankStaked;
unaccountedRewards = 0;
}
/**
* tracks $GP earnings to ensure it stops once 2.4 billion is eclipsed
*/
modifier _updateEarnings() {
if (totalGPEarned < MAXIMUM_GLOBAL_GP) {
totalGPEarned +=
(block.timestamp - lastClaimTimestamp)
* stats.numWizardsStaked
* DAILY_GP_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
/** ADMIN */
/**
* allows owner to enable "rescue mode"
* simplifies accounting, prioritizes tokens out in emergency
*/
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
/**
* enables owner to pause / unpause contract
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** READ ONLY */
/**
* checks if a token is a Wizards
* @param tokenId the ID of the token to check
* @return wizard - whether or not a token is a Wizards
*/
function isWizard(uint256 tokenId) public view returns (bool wizard) {
(wizard, , , , , , , , , ) = wndNFT.tokenTraits(tokenId);
}
/**
* gets the rank score for a Dragon
* @param tokenId the ID of the Dragon to get the rank score for
* @return the rank score of the Dragon (5-8)
*/
function _rankForDragon(uint256 tokenId) internal view returns (uint8) {
( , , , , , , , , , uint8 rankIndex) = wndNFT.tokenTraits(tokenId);
return MAX_RANK - rankIndex; // rank index is 0-3
}
/**
* chooses a random Dragon thief when a newly minted token is stolen
* @param seed a random value to choose a Dragon from
* @return the owner of the randomly selected Dragon thief
*/
function randomDragonOwner(uint256 seed) external view override returns (address) {
if (stats.totalRankStaked == 0) {
return address(0x0);
}
uint256 bucket = (seed & 0xFFFFFFFF) % stats.totalRankStaked; // choose a value from 0 to total rank staked
uint256 cumulative;
seed >>= 32;
// loop through each bucket of Dragons with the same rank score
for (uint i = MAX_RANK - 3; i <= MAX_RANK; i++) {
cumulative += flight[i].length * i;
// if the value is not inside of that bucket, keep going
if (bucket >= cumulative) continue;
// get the address of a random Dragon with that rank score
return flight[i][seed % flight[i].length].owner;
}
return address(0x0);
}
/**
* generates a pseudorandom number
* @param seed a value ensure different outcomes for different sources in the same block
* @return a pseudorandom value
*/
function random(uint256 seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)));
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send to Tower directly");
return IERC721Receiver.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
/**
* @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 allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IWnDGame {
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IWnD is IERC721Enumerable {
// game data storage
struct WizardDragon {
bool isWizard;
uint8 body;
uint8 head;
uint8 spell;
uint8 eyes;
uint8 neck;
uint8 mouth;
uint8 wand;
uint8 tail;
uint8 rankIndex;
}
function minted() external returns (uint16);
function updateOriginAccess() external;
function mint(address recipient, uint256 seed) external;
function burn(uint256 tokenId) external;
function getMaxTokens() external view returns (uint256);
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (WizardDragon memory);
function tokenTraits(uint256 tokenId) external view returns (bool a, uint8 b, uint8 c, uint8 d, uint8 e, uint8 f, uint8 g, uint8 h, uint8 i, uint8 j);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IGP {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function updateOriginAccess() external;
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ITower {
function addManyToTowerAndFlight(address account, uint16[] calldata tokenIds) external;
function randomDragonOwner(uint256 seed) external view returns (address);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ISacrificialAlter {
function mint(uint256 typeId, uint16 qty, address recipient) external;
function burn(uint256 typeId, uint16 qty, address burnFrom) external;
function updateOriginAccess() external;
function balanceOf(address account, uint256 id) external returns (uint256);
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) 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.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 "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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);
} | Remove rank from total staked
| stats.totalRankStaked -= rank; | 10,005,444 | [
1,
3288,
6171,
628,
2078,
384,
9477,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1377,
3177,
18,
4963,
12925,
510,
9477,
3947,
6171,
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/1/0x083C085fd69A71C6EC60dd5Bd7D424c2C3702dC5/sources/contracts/DAOMember.sol | the status of ready to mint. the status of after member minted. the status set by community for security. can be active again. the status set by community or member reason for member quit. can be active again. | enum Status {
Pending,
Active,
Suspended,
Archived
}
string public baseURI;
address private signer;
mapping(uint256 => Status) public memberStatuses;
event SignerChanged(address operator, address from, address to);
event BaseURIChanged(
address operator,
string fromBaseURI,
string toBaseURI
);
event Minted(address from, address to, uint256 tokenId);
event StatusChanged(address operator, Status fromStatus, Status toStatus);
constructor(
address _signer,
string memory _baseURI
| 16,558,458 | [
1,
5787,
1267,
434,
5695,
358,
312,
474,
18,
326,
1267,
434,
1839,
3140,
312,
474,
329,
18,
326,
1267,
444,
635,
19833,
364,
4373,
18,
848,
506,
2695,
3382,
18,
326,
1267,
444,
635,
19833,
578,
3140,
3971,
364,
3140,
9706,
18,
848,
506,
2695,
3382,
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,
2792,
2685,
288,
203,
3639,
16034,
16,
203,
3639,
8857,
16,
203,
3639,
348,
22942,
16,
203,
3639,
16959,
2950,
203,
565,
289,
203,
203,
565,
533,
1071,
1026,
3098,
31,
203,
203,
565,
1758,
3238,
10363,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2685,
13,
1071,
3140,
15220,
31,
203,
203,
565,
871,
16763,
5033,
12,
2867,
3726,
16,
1758,
628,
16,
1758,
358,
1769,
203,
565,
871,
3360,
3098,
5033,
12,
203,
3639,
1758,
3726,
16,
203,
3639,
533,
628,
2171,
3098,
16,
203,
3639,
533,
358,
2171,
3098,
203,
565,
11272,
203,
565,
871,
490,
474,
329,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
1769,
203,
565,
871,
2685,
5033,
12,
2867,
3726,
16,
2685,
628,
1482,
16,
2685,
358,
1482,
1769,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
2977,
264,
16,
203,
3639,
533,
3778,
389,
1969,
3098,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x23fAcd05C010AbAdF678c158EA26759661Fa3242/sources/browser/hook.sol | buy price of plan ( level )
| uint128 buyPrice; | 655,141 | [
1,
70,
9835,
6205,
434,
4995,
261,
1801,
262,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
10392,
30143,
5147,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.4.22 <0.9.0;
//Experimental Weather Insurance contract
contract WxContract {
address oracle; //This is the address that will provide the measured temperature
address payable public insured;
address payable public insurer;
uint coverage;
uint temperature;
uint public measured_temperature = 0;
constructor(address payable _insured,address payable _insurer,uint _coverage,uint _temperature,address _oracle) payable {
insured = _insured;
insurer = _insurer;
coverage = _coverage;
temperature = _temperature;
oracle = _oracle;
}
function claim() public {
require((msg.sender==insured)||(msg.sender==insurer),"Not party to insurance contract");
require(measured_temperature != 0,"Temperature not yet measured");
if(measured_temperature <= temperature){
//Insurer gets premium + coverage
insurer.transfer(coverage);
selfdestruct(insurer);
}else{
//Insured gets funds
insured.transfer(coverage);
selfdestruct(insurer);
}
}
function setTemp(uint16 _temperature) public {
require(msg.sender==oracle,"Only oracle can set temperature");
measured_ temperature = _temperature;
}
}
contract InsuranceProvider {
//Creates simple weather insurance by pairing insurers and insurees
uint public constant CONTRACT_FEE = 0.01 ether; //Fee for creating the contract in ETH
uint public num_proposals = 0;
uint public total_fees = 0; //Total fees paid into provider
struct contractSetting{
address payable insured;
uint coverage; //In ETH
uint premium; //In ETH
uint16 temperature; //Kelvin
}
mapping(uint => contractSetting) public proposals;
address oracle; //Set this to address deploying provider
address payable owner; //Set to address deploying Provider
event newProposal(uint proposalID, uint16 _temperature, uint _coverage);
event newContract();
constructor(){
oracle = msg.sender;
owner = msg.sender;
}
function proposeContract(uint coverage, uint premium, uint16 temperature) public payable {
require(msg.value >= premium + CONTRACT_FEE);
num_proposals++;
proposals[num_proposals].insured = msg.sender;
proposals[num_proposals].coverage = coverage;
proposals[num_proposals].premium = premium;
proposals[num_proposals].temperature = temperature;
emit newProposal(num_proposals, temperature, coverage);
total_fees = total_fees + 0.01 ether;
}
function acceptContract(uint proposalid) public payable {
//Insurer accepts contract by paying coverage
require(msg.value >= proposals[proposalid].coverage);
WxContract _wxcontract = new WxContract {value:proposals[proposalid].coverage}(
proposals[proposalid].insured,
msg.sender,
proposals[proposalid].coverage,
proposals[proposalid].temperature,
oracle
);
emit newContract();
//Transfer premium to insurer
msg.sender.transfer(proposals[proposalid].premium);
}
function withdrawFees() public {
//Withdraw all Provider fees
require(msg.sender == owner,"Only the owner can withdraw fees");
owner.transfer(total_fees);
total_fees = 0;
}
} | This is the address that will provide the measured temperature
| address oracle; | 12,938,999 | [
1,
2503,
353,
326,
1758,
716,
903,
5615,
326,
22221,
12843,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
20865,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-25
*/
//*********************************************************************//
//*********************************************************************//
//
// d8888b. .d88b. d88888D d88888D .o88b. .d8b. d888888b d88888D
// 88 `8D .8P Y8. YP d8' YP d8' d8P Y8 d8' `8b `~~88~~' YP d8'
// 88oooY' 88 88 d8' d8' 8P 88ooo88 88 d8'
// 88~~~b. 88 88 d8' d8' 8b 88~~~88 88 d8'
// 88 8D `8b d8' d8' db d8' db Y8b d8 88 88 88 d8' db
// Y8888P' `Y88P' d88888P d88888P `Y88P' YP YP YP d88888P
//
//*********************************************************************//
//*********************************************************************//
//-------------DEPENDENCIES--------------------------//
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: SafeMath is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's + operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's - operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's * operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's / operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's % operator. This function uses a revert
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's - operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's / operator. Note: this function uses a
* revert opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's % operator. This function uses a revert
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if account is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, isContract will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on isContract to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's transfer: sends amount wei to
* recipient, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by transfer, making them unable to receive funds via
* transfer. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to recipient, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level call. A
* plain call is an unsafe replacement for a function call: use this
* function instead.
*
* If target reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode].
*
* Requirements:
*
* - target must be a contract.
* - calling target with data must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with
* errorMessage as a fallback revert reason when target reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but also transferring value wei to target.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least value.
* - the called Solidity function must be payable.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but
* with errorMessage as a fallback revert reason when target reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} tokenId token is transferred to this contract via {IERC721-safeTransferFrom}
* by operator from from, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with IERC721.onERC721Received.selector.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* interfaceId. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
*
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when tokenId token is transferred from from to to.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when owner enables approved to manage the tokenId token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when owner enables or disables (approved) operator to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in owner's account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the tokenId token.
*
* Requirements:
*
* - tokenId must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers tokenId token from from to to, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must exist and be owned by from.
* - If the caller is not from, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers tokenId token from from to to.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must be owned by from.
* - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to to to transfer tokenId token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - tokenId must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for tokenId token.
*
* Requirements:
*
* - tokenId must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove operator as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The operator cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the operator is allowed to manage all of the assets of owner.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers tokenId token from from to to.
*
* Requirements:
*
* - from cannot be the zero address.
* - to cannot be the zero address.
* - tokenId token must exist and be owned by from.
* - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by owner at a given index of its token list.
* Use along with {balanceOf} to enumerate all of owner's tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given index of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for tokenId token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a uint256 to its ASCII string decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a uint256 to its ASCII string hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a uint256 to its ASCII string hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from ReentrancyGuard will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single nonReentrant guard, functions marked as
* nonReentrant may not call one another. This can be worked around by making
* those functions private, and then adding external nonReentrant entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a nonReentrant function from another nonReentrant
* function is not supported. It is possible to prevent this from happening
* by making the nonReentrant function external, and making it call a
* private function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* onlyOwner, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* onlyOwner functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (newOwner).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (newOwner).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//-------------END DEPENDENCIES------------------------//
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.
*
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
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 Merkle 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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: Allowlist.sol
pragma solidity ^0.8.0;
abstract contract Allowlist is Ownable {
bytes32 public merkleRoot;
bool public onlyAllowlistMode = false;
/**
* @dev Update merkle root to reflect changes in Allowlist
* @param _newMerkleRoot new merkle root to reflect most recent Allowlist
*/
function updateMerkleRoot(bytes32 _newMerkleRoot) public onlyOwner {
require(_newMerkleRoot != merkleRoot, "Merkle root will be unchanged!");
merkleRoot = _newMerkleRoot;
}
/**
* @dev Check the proof of an address if valid for merkle root
* @param _to address to check for proof
* @param _merkleProof Proof of the address to validate against root and leaf
*/
function isAllowlisted(address _to, bytes32[] calldata _merkleProof) public view returns(bool) {
require(merkleRoot != 0, "Merkle root is not set!");
bytes32 leaf = keccak256(abi.encodePacked(_to));
return MerkleProof.verify(_merkleProof, merkleRoot, leaf);
}
function enableAllowlistOnlyMode() public onlyOwner {
onlyAllowlistMode = true;
}
function disableAllowlistOnlyMode() public onlyOwner {
onlyAllowlistMode = false;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex;
uint256 public immutable collectionSize;
uint256 public maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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
* maxBatchSize refers to how much a minter can mint at a time.
* collectionSize_ refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 1;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalMinted();
}
function currentTokenId() public view returns (uint256) {
return _totalMinted();
}
function getNextTokenId() public view returns (uint256) {
return SafeMath.add(_totalMinted(), 1);
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
unchecked {
return currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints quantity tokens and transfers them to to.
*
* Requirements:
*
* - there must be quantity tokens remaining unminted in the total collection.
* - to cannot be the zero address.
* - quantity cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers tokenId from from to to.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve to to operate on tokenId
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set owners to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
if (currentIndex == _startTokenId()) revert('No Tokens Minted Yet');
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when from and to are both non-zero.
* - from and to are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
abstract contract Ramppable {
address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1;
modifier isRampp() {
require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP");
_;
}
}
interface IERC20 {
function transfer(address _to, uint256 _amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
abstract contract Withdrawable is Ownable, Ramppable {
address[] public payableAddresses = [RAMPPADDRESS,0x96Aebd156601B898c90E142f2b0A5712c2aa7aeE,0xA99870cF35350ec454AD7EdE86b1089e344A199e];
uint256[] public payableFees = [5,90,5];
uint256 public payableAddressCount = 3;
function withdrawAll() public onlyOwner {
require(address(this).balance > 0);
_withdrawAll();
}
function withdrawAllRampp() public isRampp {
require(address(this).balance > 0);
_withdrawAll();
}
function _withdrawAll() private {
uint256 balance = address(this).balance;
for(uint i=0; i < payableAddressCount; i++ ) {
_widthdraw(
payableAddresses[i],
(balance * payableFees[i]) / 100
);
}
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
/**
* @dev Allow contract owner to withdraw ERC-20 balance from contract
* while still splitting royalty payments to all other team members.
* in the event ERC-20 tokens are paid to the contract.
* @param _tokenContract contract of ERC-20 token to withdraw
* @param _amount balance to withdraw according to balanceOf of ERC-20 token
*/
function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner {
require(_amount > 0);
IERC20 tokenContract = IERC20(_tokenContract);
require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens');
for(uint i=0; i < payableAddressCount; i++ ) {
tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100);
}
}
/**
* @dev Allows Rampp wallet to update its own reference as well as update
* the address for the Rampp-owed payment split. Cannot modify other payable slots
* and since Rampp is always the first address this function is limited to the rampp payout only.
* @param _newAddress updated Rampp Address
*/
function setRamppAddress(address _newAddress) public isRampp {
require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different");
RAMPPADDRESS = _newAddress;
payableAddresses[0] = _newAddress;
}
}
abstract contract RamppERC721A is
Ownable,
ERC721A,
Withdrawable,
ReentrancyGuard , Allowlist {
constructor(
string memory tokenName,
string memory tokenSymbol
) ERC721A(tokenName, tokenSymbol, 5, 9261 ) {}
using SafeMath for uint256;
uint8 public CONTRACT_VERSION = 2;
string public _baseTokenURI = "ipfs://QmZdk8bBKTK59ZNF1VVjoYpithwP4xGqnS9Ypp4rtvARN3/";
bool public mintingOpen = false;
bool public isRevealed = false;
uint256 public PRICE = 0.03 ether;
uint256 public MAX_WALLET_MINTS = 5;
mapping(address => uint256) private addressMints;
/////////////// Admin Mint Functions
/**
* @dev Mints a token to an address with a tokenURI.
* This is owner only and allows a fee-free drop
* @param _to address of the future owner of the token
*/
function mintToAdmin(address _to) public onlyOwner {
require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 9261");
_safeMint(_to, 1);
}
function mintManyAdmin(address[] memory _addresses, uint256 _addressCount) public onlyOwner {
for(uint i=0; i < _addressCount; i++ ) {
mintToAdmin(_addresses[i]);
}
}
/////////////// GENERIC MINT FUNCTIONS
/**
* @dev Mints a single token to an address.
* fee may or may not be required*
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public payable {
require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 9261");
require(mintingOpen == true && onlyAllowlistMode == false, "Public minting is not open right now!");
require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints");
require(msg.value == PRICE, "Value needs to be exactly the mint fee!");
_safeMint(_to, 1);
updateMintCount(_to, 1);
}
/**
* @dev Mints a token to an address with a tokenURI.
* fee may or may not be required*
* @param _to address of the future owner of the token
* @param _amount number of tokens to mint
*/
function mintToMultiple(address _to, uint256 _amount) public payable {
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(mintingOpen == true && onlyAllowlistMode == false, "Public minting is not open right now!");
require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 9261");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount);
updateMintCount(_to, _amount);
}
function openMinting() public onlyOwner {
mintingOpen = true;
}
function stopMinting() public onlyOwner {
mintingOpen = false;
}
///////////// ALLOWLIST MINTING FUNCTIONS
/**
* @dev Mints a token to an address with a tokenURI for allowlist.
* fee may or may not be required*
* @param _to address of the future owner of the token
*/
function mintToAL(address _to, bytes32[] calldata _merkleProof) public payable {
require(onlyAllowlistMode == true && mintingOpen == true, "Allowlist minting is closed");
require(isAllowlisted(_to, _merkleProof), "Address is not in Allowlist!");
require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 9261");
require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints");
require(msg.value == PRICE, "Value needs to be exactly the mint fee!");
_safeMint(_to, 1);
updateMintCount(_to, 1);
}
/**
* @dev Mints a token to an address with a tokenURI for allowlist.
* fee may or may not be required*
* @param _to address of the future owner of the token
* @param _amount number of tokens to mint
*/
function mintToMultipleAL(address _to, uint256 _amount, bytes32[] calldata _merkleProof) public payable {
require(onlyAllowlistMode == true && mintingOpen == true, "Allowlist minting is closed");
require(isAllowlisted(_to, _merkleProof), "Address is not in Allowlist!");
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 9261");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount);
updateMintCount(_to, _amount);
}
/**
* @dev Enable allowlist minting fully by enabling both flags
* This is a convenience function for the Rampp user
*/
function openAllowlistMint() public onlyOwner {
enableAllowlistOnlyMode();
mintingOpen = true;
}
/**
* @dev Close allowlist minting fully by disabling both flags
* This is a convenience function for the Rampp user
*/
function closeAllowlistMint() public onlyOwner {
disableAllowlistOnlyMode();
mintingOpen = false;
}
/**
* @dev Check if wallet over MAX_WALLET_MINTS
* @param _address address in question to check if minted count exceeds max
*/
function canMintAmount(address _address, uint256 _amount) public view returns(bool) {
require(_amount >= 1, "Amount must be greater than or equal to 1");
return SafeMath.add(addressMints[_address], _amount) <= MAX_WALLET_MINTS;
}
/**
* @dev Update an address that has minted to new minted amount
* @param _address address in question to check if minted count exceeds max
* @param _amount the quanitiy of tokens to be minted
*/
function updateMintCount(address _address, uint256 _amount) private {
require(_amount >= 1, "Amount must be greater than or equal to 1");
addressMints[_address] = SafeMath.add(addressMints[_address], _amount);
}
/**
* @dev Update the maximum amount of tokens that can be minted by a unique wallet
* @param _newWalletMax the new max of tokens a wallet can mint. Must be >= 1
*/
function setWalletMax(uint256 _newWalletMax) public onlyOwner {
require(_newWalletMax >= 1, "Max mints per wallet must be at least 1");
MAX_WALLET_MINTS = _newWalletMax;
}
/**
* @dev Allows owner to set Max mints per tx
* @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1
*/
function setMaxMint(uint256 _newMaxMint) public onlyOwner {
require(_newMaxMint >= 1, "Max mint must be at least 1");
maxBatchSize = _newMaxMint;
}
function setPrice(uint256 _feeInWei) public onlyOwner {
PRICE = _feeInWei;
}
function getPrice(uint256 _count) private view returns (uint256) {
return PRICE.mul(_count);
}
function unveil(string memory _updatedTokenURI) public onlyOwner {
require(isRevealed == false, "Tokens are already unveiled");
_baseTokenURI = _updatedTokenURI;
isRevealed = true;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) {
return ownershipOf(tokenId);
}
}
// File: contracts/BozzCatzContract.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract BozzCatzContract is RamppERC721A {
constructor() RamppERC721A("BozzCatz", "BOZZ"){}
function contractURI() public pure returns (string memory) {
return "https://us-central1-nft-rampp.cloudfunctions.net/app/4f906OBv80sxzVC1qHIT/contract-metadata";
}
}
//*********************************************************************//
//*********************************************************************//
// Rampp v2.0.1
//
// This smart contract was generated by rampp.xyz.
// Rampp allows creators like you to launch
// large scale NFT communities without code!
//
// Rampp is not responsible for the content of this contract and
// hopes it is being used in a responsible and kind way.
// Rampp is not associated or affiliated with this project.
// Twitter: @Rampp_ ---- rampp.xyz
//*********************************************************************//
//*********************************************************************// | * @dev Mints a token to an address with a tokenURI for allowlist. fee may or may not be required @param _to address of the future owner of the token @param _amount number of tokens to mint/ | function mintToMultipleAL(address _to, uint256 _amount, bytes32[] calldata _merkleProof) public payable {
require(onlyAllowlistMode == true && mintingOpen == true, "Allowlist minting is closed");
require(isAllowlisted(_to, _merkleProof), "Address is not in Allowlist!");
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 9261");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount);
updateMintCount(_to, _amount);
}
| 10,927,761 | [
1,
49,
28142,
279,
1147,
358,
392,
1758,
598,
279,
1147,
3098,
364,
1699,
1098,
18,
14036,
2026,
578,
2026,
486,
506,
1931,
225,
389,
869,
1758,
434,
326,
3563,
3410,
434,
326,
1147,
225,
389,
8949,
1300,
434,
2430,
358,
312,
474,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
774,
8438,
1013,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
16,
1731,
1578,
8526,
745,
892,
389,
6592,
15609,
20439,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
3700,
7009,
1098,
2309,
422,
638,
597,
312,
474,
310,
3678,
422,
638,
16,
315,
7009,
1098,
312,
474,
310,
353,
4375,
8863,
203,
3639,
2583,
12,
291,
7009,
18647,
24899,
869,
16,
389,
6592,
15609,
20439,
3631,
315,
1887,
353,
486,
316,
7852,
1098,
4442,
1769,
203,
3639,
2583,
24899,
8949,
1545,
404,
16,
315,
10136,
312,
474,
622,
4520,
404,
1147,
8863,
203,
3639,
2583,
24899,
8949,
1648,
943,
23304,
16,
315,
4515,
312,
474,
1898,
2353,
943,
312,
474,
1534,
2492,
8863,
203,
203,
3639,
2583,
12,
4169,
49,
474,
6275,
24899,
869,
16,
389,
8949,
3631,
315,
16936,
1758,
353,
1879,
326,
4207,
2935,
312,
28142,
8863,
203,
3639,
2583,
12,
2972,
1345,
548,
1435,
397,
389,
8949,
1648,
1849,
1225,
16,
315,
4515,
312,
474,
1879,
14467,
3523,
434,
2468,
5558,
21,
8863,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
25930,
24899,
8949,
3631,
315,
620,
5712,
1931,
312,
474,
14036,
364,
3844,
8863,
203,
3639,
389,
4626,
49,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
1089,
49,
474,
1380,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/137/0x763B931D1D3EFF96E7A8c1B76d4DCE1d476c5A48/sources/NEWMASTERCHEF/Masterchef.sol | View function to see pending MyTokens on frontend. | function pendingMyToken(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMyTokenPerShare = pool.accMyTokenPerShare;
if (
block.number > pool.lastRewardBlock &&
pool.lpSupply != 0 &&
totalAllocPoint > 0
) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 MyTokenReward = multiplier
.mul(MyTokenPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
if (MyToken.totalSupply().add(MyTokenReward) > MyToken.cap()) {
MyTokenReward = MyToken.cap().sub(MyToken.totalSupply());
}
accMyTokenPerShare = accMyTokenPerShare.add(
MyTokenReward.mul(1e18).div(pool.lpSupply)
);
}
return
user.amount.mul(accMyTokenPerShare).div(1e18).sub(user.rewardDebt);
}
| 4,710,966 | [
1,
1767,
445,
358,
2621,
4634,
8005,
5157,
603,
15442,
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,
445,
4634,
12062,
1345,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
12062,
1345,
2173,
9535,
273,
2845,
18,
8981,
12062,
1345,
2173,
9535,
31,
203,
3639,
309,
261,
203,
5411,
1203,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
203,
5411,
2845,
18,
9953,
3088,
1283,
480,
374,
597,
203,
5411,
2078,
8763,
2148,
405,
374,
203,
3639,
262,
288,
203,
5411,
2254,
5034,
15027,
273,
31863,
5742,
12,
203,
7734,
2845,
18,
2722,
17631,
1060,
1768,
16,
203,
7734,
1203,
18,
2696,
203,
5411,
11272,
203,
5411,
2254,
5034,
8005,
1345,
17631,
1060,
273,
15027,
203,
7734,
263,
16411,
12,
12062,
1345,
2173,
1768,
13,
203,
7734,
263,
16411,
12,
6011,
18,
9853,
2148,
13,
203,
7734,
263,
2892,
12,
4963,
8763,
2148,
1769,
203,
5411,
309,
261,
12062,
1345,
18,
4963,
3088,
1283,
7675,
1289,
12,
12062,
1345,
17631,
1060,
13,
405,
8005,
1345,
18,
5909,
10756,
288,
203,
7734,
8005,
1345,
17631,
1060,
273,
8005,
1345,
18,
5909,
7675,
1717,
12,
12062,
1345,
18,
4963,
3088,
1283,
10663,
203,
5411,
289,
203,
5411,
4078,
12062,
1345,
2173,
9535,
273,
4078,
12062,
1345,
2173,
9535,
18,
1289,
12,
203,
7734,
8005,
1345,
17631,
1060,
18,
16411,
12,
21,
2
]
|
./full_match/80001/0x77F2353860D1EFc1D956b1AC317E2E1D9D342775/sources/src/common/UnorderedForwarder.sol | @dev Refunds up to `msg.value` leftover ETH at the end of the call. | modifier refundsAttachedEth() {
_;
uint256 remainingBalance = msg.value > address(this).balance ? address(this).balance : msg.value;
if (remainingBalance > 0) {
payable(msg.sender).transfer(remainingBalance);
}
}
| 5,645,295 | [
1,
1957,
19156,
731,
358,
1375,
3576,
18,
1132,
68,
29709,
512,
2455,
622,
326,
679,
434,
326,
745,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
16255,
87,
14890,
41,
451,
1435,
288,
203,
3639,
389,
31,
203,
3639,
2254,
5034,
4463,
13937,
273,
1234,
18,
1132,
405,
1758,
12,
2211,
2934,
12296,
692,
1758,
12,
2211,
2934,
12296,
294,
1234,
18,
1132,
31,
203,
3639,
309,
261,
17956,
13937,
405,
374,
13,
288,
203,
5411,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
12,
17956,
13937,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
pragma experimental ABIEncoderV2;
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(address(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, address(this), sig);
}
}
}
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 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);
_;
}
}
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
}
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
}
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
if (totalBorrowsETH == 0) return uint256(0);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
// Pack the struct data
(uint[4] memory numData, address[6] memory cAddresses, bytes memory callData)
= _packData(_createInfo, _exchangeData);
bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
function _packData(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) {
numData = [
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
cAddresses = [
_createInfo.cCollAddress,
_createInfo.cBorrowAddress,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
callData = exchangeData.callData;
}
}
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
}
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CreamSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the cream position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
contract DFSExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract DFSPrices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers,
bytes[] memory _additionalData
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
}
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscriptions {
function unsubscribe() external virtual ;
}
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
abstract contract TokenInterface {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
}
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
contract MCDCreateTaker {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
contract MCDSaverProxyHelper is DSMath {
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
}
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getAccountBalances(
Account.Info memory account
) public view virtual returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function setOperators(
OperatorArg[] memory args
) public virtual;
function getNumMarkets() public view virtual returns (uint256);
function getMarketTokenAddress(uint256 marketId)
public
view
virtual
returns (address);
}
library Account {
// ============ Enums ============
/*
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum Status {
Normal,
Liquid,
Vapor
}
// ============ Structs ============
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
// The complete storage for any account
struct Storage {
mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
// ============ Library Functions ============
function equals(
Info memory a,
Info memory b
)
internal
pure
returns (bool)
{
return a.owner == b.owner && a.number == b.number;
}
}
library Actions {
// ============ Constants ============
bytes32 constant FILE = "Actions";
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {
OnePrimary,
TwoPrimary,
PrimaryAndSecondary
}
enum MarketLayout {
ZeroMarkets,
OneMarket,
TwoMarkets
}
// ============ Structs ============
/*
* Arguments that are passed to Solo in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
// ============ Action Types ============
/*
* Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply.
*/
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
/*
* Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount
* previously supplied.
*/
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
/*
* Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
* The amount field applies to accountOne.
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
/*
* Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
* applies to the makerMarket.
*/
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
* to the takerMarket.
*/
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Trades balances between two accounts using any external contract that implements the
* AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
* which it is trading on-behalf-of). The amount field applies to the makerAccount and the
* inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
* quote a change for the makerAccount in the outputMarket (or will disallow the trade).
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
/*
* Each account must maintain a certain margin-ratio (specified globally). If the account falls
* below this margin-ratio, it can be liquidated by any other account. This allows anyone else
* (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
* exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
* by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
* account also sets a flag on the account that the account is being liquidated. This allows
* anyone to continue liquidating the account until there are no more borrows being taken by the
* liquidating account. Liquidators do not have to liquidate the entire account all at once but
* can liquidate as much as they choose. The liquidating flag allows liquidators to continue
* liquidating the account even if it becomes collateralized through partial liquidation or
* price movement.
*/
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Similar to liquidate, but vaporAccounts are accounts that have only negative balances
* remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in
* exchange for a collateral asset (heldMarket) at a favorable spread. However, since the
* liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens.
*/
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Passes arbitrary bytes of data to an external contract that implements the Callee interface.
* Does not change any asset amounts. This function may be useful for setting certain variables
* on layer-two contracts for certain accounts without having to make a separate Ethereum
* transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
* from an operator of the particular account.
*/
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
// ============ Helper Functions ============
function getMarketLayout(
ActionType actionType
)
internal
pure
returns (MarketLayout)
{
if (
actionType == Actions.ActionType.Deposit
|| actionType == Actions.ActionType.Withdraw
|| actionType == Actions.ActionType.Transfer
) {
return MarketLayout.OneMarket;
}
else if (actionType == Actions.ActionType.Call) {
return MarketLayout.ZeroMarkets;
}
return MarketLayout.TwoMarkets;
}
function getAccountLayout(
ActionType actionType
)
internal
pure
returns (AccountLayout)
{
if (
actionType == Actions.ActionType.Transfer
|| actionType == Actions.ActionType.Trade
) {
return AccountLayout.TwoPrimary;
} else if (
actionType == Actions.ActionType.Liquidate
|| actionType == Actions.ActionType.Vaporize
) {
return AccountLayout.PrimaryAndSecondary;
}
return AccountLayout.OnePrimary;
}
// ============ Parsing Functions ============
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
{
assert(args.actionType == ActionType.Deposit);
return DepositArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
from: args.otherAddress
});
}
function parseWithdrawArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (WithdrawArgs memory)
{
assert(args.actionType == ActionType.Withdraw);
return WithdrawArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
to: args.otherAddress
});
}
function parseTransferArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TransferArgs memory)
{
assert(args.actionType == ActionType.Transfer);
return TransferArgs({
amount: args.amount,
accountOne: accounts[args.accountId],
accountTwo: accounts[args.otherAccountId],
market: args.primaryMarketId
});
}
function parseBuyArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (BuyArgs memory)
{
assert(args.actionType == ActionType.Buy);
return BuyArgs({
amount: args.amount,
account: accounts[args.accountId],
makerMarket: args.primaryMarketId,
takerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseSellArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (SellArgs memory)
{
assert(args.actionType == ActionType.Sell);
return SellArgs({
amount: args.amount,
account: accounts[args.accountId],
takerMarket: args.primaryMarketId,
makerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseTradeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TradeArgs memory)
{
assert(args.actionType == ActionType.Trade);
return TradeArgs({
amount: args.amount,
takerAccount: accounts[args.accountId],
makerAccount: accounts[args.otherAccountId],
inputMarket: args.primaryMarketId,
outputMarket: args.secondaryMarketId,
autoTrader: args.otherAddress,
tradeData: args.data
});
}
function parseLiquidateArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (LiquidateArgs memory)
{
assert(args.actionType == ActionType.Liquidate);
return LiquidateArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
liquidAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseVaporizeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (VaporizeArgs memory)
{
assert(args.actionType == ActionType.Vaporize);
return VaporizeArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
vaporAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseCallArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (CallArgs memory)
{
assert(args.actionType == ActionType.Call);
return CallArgs({
account: accounts[args.accountId],
callee: args.otherAddress,
data: args.data
});
}
}
library Math {
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Math";
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint128"
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint96"
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint32"
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
library Types {
using Math for uint256;
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ Par (Principal Amount) ============
// Total borrow and supply values for a market
struct TotalPar {
uint128 borrow;
uint128 supply;
}
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
function zeroWei()
internal
pure
returns (Wei memory)
{
return Wei({
sign: false,
value: 0
});
}
function sub(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
return add(a, negative(b));
}
function add(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
Wei memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value);
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value);
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value);
}
}
return result;
}
function equals(
Wei memory a,
Wei memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Wei memory a
)
internal
pure
returns (Wei memory)
{
return Wei({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Wei memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Wei memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Wei memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 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(ERC20 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(ERC20 token, bytes memory data) private {
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");
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for variable rate and 2 for fixed rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
if (originationFee > 0) {
ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee);
}
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 19;
uint public BOOST_GAS_TOKEN = 19;
uint public MAX_GAS_PRICE = 200000000000; // 200 gwei
uint public REPAY_GAS_COST = 2500000;
uint public BOOST_GAS_COST = 2500000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address user,
address proxy
)
= abi.decode(data, (address,address,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
}
// pull tokens from user to proxy
ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x7b856af5753a9f80968EA002641E69AdF1d795aB;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve AaveImport to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
contract CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint) {
uint compBalance = 0;
for(uint i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) {
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta);
}
function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) {
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta);
}
}
}
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CompoundImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, 0);
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay compound debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the cream protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the cream protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the cream protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the cream market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the cream market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CreamLoanInfo is CreamSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches cream prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches cream collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay cream debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return address(this).balance;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (_exData.srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
}
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.offchainData.callData, 36, _exData.destAmount);
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
if (success) {
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1800000;
uint public BOOST_GAS_COST = 1800000;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
closeCDP(closeData, exchangeData, user);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user
) internal {
paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = _closeData.daiAmount;
(, daiSwaped) = _buy(_exchangeData);
}
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
manager.frob(_cdpId, -toPositiveInt(_amount), 0);
manager.flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = manager.urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDCloseTaker is MCDSaverProxyHelper {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
manager.urns(_closeData.cdpId),
manager.urns(_closeData.cdpId),
manager.ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId));
}
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public constant manager = Manager(MANAGER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(_cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(_cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(manager.urns(_cdpId));
uint maxAmount = getMaxDebt(_cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
manager.move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
manager.ilks(_cdpId),
manager.urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
manager.frob(_cdpId, -toPositiveInt(frobAmount), 0);
manager.flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = manager.urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) {
address urn = manager.urns(_cdpId);
ilk = manager.ilks(_cdpId);
(collateral, debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
price = getPrice(ilk);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (feeAmount > _amount / 10) {
feeAmount = _amount / 10;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
return feeAmount;
}
return 0;
}
}
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (isEthJoinAddr(_joinAddr)
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth {
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
if (paramData.swapType == 1) { // COLL_SWAP
exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) { // DEBT_SWAP
exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy);
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)));
} else { // NO_SWAP just send tokens to proxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr));
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(uint _amount, uint _fee, bytes memory _params)
internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) {
(
uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x
address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper
uint8[3] memory enumData, // fromProtocol, toProtocol, swapType
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address));
bytes memory proxyData1;
bytes memory proxyData2;
uint openDebtAmount = (_amount + _fee);
if (enumData[0] == 0) { // MAKER FROM
proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]);
} else if(enumData[0] == 1) { // COMPOUND FROM
if (enumData[2] == 2) { // DEBT_SWAP
proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]);
} else {
proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]);
}
}
if (enumData[1] == 0) { // MAKER TO
proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount);
} else if(enumData[1] == 1) { // COMPOUND TO
if (enumData[2] == 2) { // DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]);
} else {
proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: addrData[2],
protocol1: enumData[0],
protocol2: enumData[1],
swapType: enumData[2]
});
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: addrData[4],
destAddr: addrData[5],
srcAmount: numData[4],
destAmount: numData[5],
minPrice: numData[6],
wrapper: addrData[7],
exchangeAddr: addrData[6],
callData: callData,
price0x: numData[7]
});
}
function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxyInterface proxy = DSProxyInterface(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
(
uint[8] memory numData,
address[8] memory addrData,
uint8[3] memory enumData,
bytes memory callData
)
= _packData(_loanShift, _exchangeData);
// encode data
bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return CTokenInterface(_address).underlying();
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function logEvent(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
function _packData(
LoanShiftData memory _loanShift,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) {
numData = [
_loanShift.collAmount,
_loanShift.debtAmount,
_loanShift.id1,
_loanShift.id2,
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
addrData = [
_loanShift.addrLoan1,
_loanShift.addrLoan2,
_loanShift.debtAddr1,
_loanShift.debtAddr2,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
enumData = [
uint8(_loanShift.fromProtocol),
uint8(_loanShift.toProtocol),
uint8(_loanShift.swapType)
];
callData = exchangeData.callData;
}
}
contract CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
contract McdShifter is MCDSaverProxy {
using SafeERC20 for ERC20;
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(_cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawCollateral(_cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(_cdpId, _joinAddr, collAmount);
// draw debt
drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
}
contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
// swap
(, destAmount) = _sell(_data);
destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr);
// swap
(, destAmount) = _sell(_data);
} else {
_data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr);
destAmount = _data.srcAmount;
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
(, uint sellAmount) = _sell(exchangeData);
getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
(
uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x
address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[4],address[6],bytes,address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
cAddresses[0], cAddresses[1], (_amount + _fee));
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: cAddresses[2],
destAddr: cAddresses[3],
srcAmount: numData[0],
destAmount: numData[1],
minPrice: numData[2],
wrapper: cAddresses[5],
exchangeAddr: cAddresses[4],
callData: callData,
price0x: numData[3]
});
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: cAddresses[0],
cDebtAddr: cAddresses[1]
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxy proxy = DSProxy(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.srcAmount = collAmount;
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId));
uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
bytes32 ilk = manager.ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(_saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
| Note: We are not using careful math here as we're performing a division that cannot fail | function truncate(Exp memory exp) pure internal returns (uint) {
return exp.mantissa / expScale;
}
| 7,333,109 | [
1,
8067,
30,
1660,
854,
486,
1450,
26850,
4233,
2674,
487,
732,
4565,
14928,
279,
16536,
716,
2780,
2321,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
10310,
12,
2966,
3778,
1329,
13,
16618,
2713,
1135,
261,
11890,
13,
288,
203,
203,
203,
3639,
327,
1329,
18,
81,
970,
21269,
342,
1329,
5587,
31,
203,
203,
565,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0x53802157E559B0596846a599824Db6D7ca9b81EB/sources/MockUFragments.sol | Methods to mock data on the chain | contract MockUFragments is Mock {
uint256 private _supply;
function storeSupply(uint256 supply)
public
{
_supply = supply;
}
function rebase(uint256 epoch, int256 supplyDelta)
public
returns (uint256)
{
emit FunctionCalled("UFragments", "rebase", msg.sender);
uint256[] memory uintVals = new uint256[](1);
uintVals[0] = epoch;
int256[] memory intVals = new int256[](1);
intVals[0] = supplyDelta;
emit FunctionArguments(uintVals, intVals);
return uint256(int256(_supply) + int256(supplyDelta));
}
function totalSupply()
public
view
returns (uint256)
{
return _supply;
}
} | 8,751,489 | [
1,
4712,
358,
5416,
501,
603,
326,
2687,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
7867,
57,
27588,
353,
7867,
288,
203,
565,
2254,
5034,
3238,
389,
2859,
1283,
31,
203,
203,
565,
445,
1707,
3088,
1283,
12,
11890,
5034,
14467,
13,
203,
3639,
1071,
203,
203,
565,
288,
203,
3639,
389,
2859,
1283,
273,
14467,
31,
203,
565,
289,
203,
203,
565,
445,
283,
1969,
12,
11890,
5034,
7632,
16,
509,
5034,
14467,
9242,
13,
203,
3639,
1071,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
3626,
4284,
8185,
2932,
57,
27588,
3113,
315,
266,
1969,
3113,
1234,
18,
15330,
1769,
203,
3639,
2254,
5034,
8526,
3778,
2254,
13169,
273,
394,
2254,
5034,
8526,
12,
21,
1769,
203,
3639,
2254,
13169,
63,
20,
65,
273,
7632,
31,
203,
3639,
509,
5034,
8526,
3778,
509,
13169,
273,
394,
509,
5034,
8526,
12,
21,
1769,
203,
3639,
509,
13169,
63,
20,
65,
273,
14467,
9242,
31,
203,
3639,
3626,
4284,
4628,
12,
11890,
13169,
16,
509,
13169,
1769,
203,
3639,
327,
2254,
5034,
12,
474,
5034,
24899,
2859,
1283,
13,
397,
509,
5034,
12,
2859,
1283,
9242,
10019,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
389,
2859,
1283,
31,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: BSD-4-Clause
pragma solidity 0.8.3;
import "./IOddzLiquidityPoolManager.sol";
import "../Libs/DateTimeLibrary.sol";
import "../Swap/IDexManager.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
contract OddzLiquidityPoolManager is AccessControl, IOddzLiquidityPoolManager, ERC20("Oddz USD LP token", "oUSD") {
using Math for uint256;
using Address for address;
using SafeERC20 for IERC20;
/**
* @dev reqBalance represents minimum required balance out of 10
* Range between 6 and 10
* e.g. 8 represents 80% of the balance
*/
uint8 public reqBalance = 8;
/**
* @dev Liquidity specific data definitions
*/
LockedLiquidity[] public lockedLiquidity;
IERC20 public token;
/**
* @dev Liquidity lock and distribution data definitions
*/
mapping(uint256 => bool) public allowedMaxExpiration;
mapping(uint256 => uint256) public periodMapper;
mapping(bytes32 => IOddzLiquidityPool[]) public poolMapper;
mapping(bytes32 => bool) public uniquePoolMapper;
/**
* @dev Active pool count
*/
mapping(IOddzLiquidityPool => uint256) public override poolExposure;
/**
* @dev Disabled pools
*/
mapping(IOddzLiquidityPool => bool) public disabledPools;
// user address -> date of transfer
mapping(address => uint256) public lastPoolTransfer;
/**
* @dev Premium specific data definitions
*/
uint256 public premiumLockupDuration = 14 days;
uint256 public moveLockupDuration = 7 days;
/**
* @dev DEX manager
*/
IDexManager public dexManager;
address public strategyManager;
/**
* @dev Access control specific data definitions
*/
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
bytes32 public constant TIMELOCKER_ROLE = keccak256("TIMELOCKER_ROLE");
modifier onlyOwner(address _address) {
require(hasRole(DEFAULT_ADMIN_ROLE, _address), "LP Error: caller has no access to the method");
_;
}
modifier onlyManager(address _address) {
require(hasRole(MANAGER_ROLE, _address), "LP Error: caller has no access to the method");
_;
}
modifier onlyTimeLocker(address _address) {
require(hasRole(TIMELOCKER_ROLE, _address), "LP Error: caller has no access to the method");
_;
}
modifier validLiquidty(uint256 _id) {
LockedLiquidity storage ll = lockedLiquidity[_id];
require(ll._locked, "LP Error: liquidity has already been unlocked");
_;
}
modifier reqBalanceValidRange(uint8 _reqBalance) {
require(_reqBalance >= 6 && _reqBalance <= 10, "LP Error: required balance valid range [6 - 10]");
_;
}
modifier validMaxExpiration(uint256 _maxExpiration) {
require(allowedMaxExpiration[_maxExpiration] == true, "LP Error: invalid maximum expiration");
_;
}
modifier validCaller(address _provider) {
require(msg.sender == _provider || msg.sender == strategyManager, "LP Error: invalid caller");
_;
}
constructor(IERC20 _token, IDexManager _dexManager) {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(TIMELOCKER_ROLE, msg.sender);
_setRoleAdmin(TIMELOCKER_ROLE, TIMELOCKER_ROLE);
token = _token;
dexManager = _dexManager;
addAllowedMaxExpiration(1);
addAllowedMaxExpiration(2);
addAllowedMaxExpiration(7);
addAllowedMaxExpiration(14);
addAllowedMaxExpiration(30);
mapPeriod(1, 1);
mapPeriod(2, 2);
mapPeriod(3, 7);
mapPeriod(4, 7);
mapPeriod(5, 7);
mapPeriod(6, 7);
mapPeriod(7, 7);
mapPeriod(8, 14);
mapPeriod(9, 14);
mapPeriod(10, 14);
mapPeriod(11, 14);
mapPeriod(12, 14);
mapPeriod(13, 14);
mapPeriod(14, 14);
mapPeriod(15, 30);
mapPeriod(16, 30);
mapPeriod(17, 30);
mapPeriod(18, 30);
mapPeriod(19, 30);
mapPeriod(20, 30);
mapPeriod(21, 30);
mapPeriod(22, 30);
mapPeriod(23, 30);
mapPeriod(24, 30);
mapPeriod(25, 30);
mapPeriod(26, 30);
mapPeriod(27, 30);
mapPeriod(28, 30);
mapPeriod(29, 30);
mapPeriod(30, 30);
}
function addLiquidity(
address _provider,
IOddzLiquidityPool _pool,
uint256 _amount
) external override validCaller(_provider) returns (uint256 mint) {
require(poolExposure[_pool] > 0, "LP Error: Invalid pool");
mint = _amount;
require(mint > 0, "LP Error: Amount is too small");
uint256 eligiblePremium = _pool.collectPremium(_provider, premiumLockupDuration);
if (eligiblePremium > 0) token.safeTransfer(_provider, eligiblePremium);
_pool.addLiquidity(_amount, _provider);
_mint(_provider, mint);
token.safeTransferFrom(_provider, address(this), _amount);
}
function removeLiquidity(
address _provider,
IOddzLiquidityPool _pool,
uint256 _amount
) external override validCaller(_provider) {
require(poolExposure[_pool] > 0, "LP Error: Invalid pool");
require(_amount <= balanceOf(_provider), "LP Error: Amount exceeds oUSD balance");
uint256 eligiblePremium = _pool.collectPremium(_provider, premiumLockupDuration);
token.safeTransfer(
_provider,
_removeLiquidity(_provider, _pool, _amount, premiumLockupDuration) + eligiblePremium
);
_burn(_provider, _amount);
}
function _removeLiquidity(
address _provider,
IOddzLiquidityPool _pool,
uint256 _amount,
uint256 premiumLockPeriod
) private returns (uint256 transferAmount) {
uint256 validateBalance;
if (disabledPools[_pool]) validateBalance = _pool.availableBalance() * 10;
else validateBalance = _pool.availableBalance() * reqBalance;
require(_amount * 10 <= validateBalance, "LP Error: Not enough funds in the pool. Please lower the amount.");
require(_amount > 0, "LP Error: Amount is too small");
transferAmount = _pool.removeLiquidity(_amount, _provider, premiumLockPeriod);
}
function lockLiquidity(
uint256 _id,
LiquidityParams memory _liquidityParams,
uint256 _premium
) external override onlyManager(msg.sender) {
require(_id == lockedLiquidity.length, "LP Error: Invalid id");
(address[] memory pools, uint256[] memory poolBalances) = getSortedEligiblePools(_liquidityParams);
require(pools.length > 0, "LP Error: No pool balance");
uint8 count = 0;
uint256 totalAmount = _liquidityParams._amount;
uint256 base = totalAmount / pools.length;
uint256[] memory share = new uint256[](pools.length);
while (count < pools.length) {
if (base > poolBalances[count]) share[count] = poolBalances[count];
else share[count] = base;
IOddzLiquidityPool(pools[count]).lockLiquidity(share[count]);
totalAmount -= share[count];
if (totalAmount > 0) base = totalAmount / (pools.length - (count + 1));
count++;
}
lockedLiquidity.push(LockedLiquidity(_liquidityParams._amount, _premium, true, pools, share));
}
function unlockLiquidity(uint256 _id) external override onlyManager(msg.sender) validLiquidty(_id) {
LockedLiquidity storage ll = lockedLiquidity[_id];
for (uint8 i = 0; i < ll._pools.length; i++) {
IOddzLiquidityPool(ll._pools[i]).unlockLiquidity(ll._share[i]);
IOddzLiquidityPool(ll._pools[i]).unlockPremium(_id, (ll._premium * ll._share[i]) / ll._amount);
}
ll._locked = false;
}
function send(
uint256 _id,
address _account,
uint256 _amount
) external override onlyManager(msg.sender) validLiquidty(_id) {
(, uint256 transferAmount) = _updateAndFetchLockedLiquidity(_id, _account, _amount);
// Transfer Funds
token.safeTransfer(_account, transferAmount);
}
function sendUA(
uint256 _id,
address _account,
uint256 _amount,
bytes32 _underlying,
bytes32 _strike,
uint32 _deadline,
uint16 _minAmountsOut
) public override onlyManager(msg.sender) validLiquidty(_id) {
(, uint256 transferAmount) = _updateAndFetchLockedLiquidity(_id, _account, _amount);
address exchange = dexManager.getExchange(_underlying, _strike);
// Transfer Funds
token.safeTransfer(exchange, transferAmount);
// block.timestamp + deadline --> deadline from the current block
dexManager.swap(
_strike,
_underlying,
exchange,
_account,
transferAmount,
block.timestamp + _deadline,
_minAmountsOut
);
}
/**
* @notice Move liquidity between pools
* @param _poolTransfer source and destination pools with amount of transfer
*/
function move(address _provider, PoolTransfer memory _poolTransfer) external override validCaller(_provider) {
require(
lastPoolTransfer[_provider] == 0 || (lastPoolTransfer[_provider] + moveLockupDuration) < block.timestamp,
"LP Error: Pool transfer not allowed"
);
lastPoolTransfer[_provider] = block.timestamp;
int256 totalTransfer = 0;
for (uint256 i = 0; i < _poolTransfer._source.length; i++) {
require(
(poolExposure[_poolTransfer._source[i]] > 0) || disabledPools[_poolTransfer._source[i]],
"LP Error: Invalid pool"
);
_removeLiquidity(_provider, _poolTransfer._source[i], _poolTransfer._sAmount[i], moveLockupDuration);
totalTransfer += int256(_poolTransfer._sAmount[i]);
}
for (uint256 i = 0; i < _poolTransfer._destination.length; i++) {
require(poolExposure[_poolTransfer._destination[i]] > 0, "LP Error: Invalid pool");
_poolTransfer._destination[i].addLiquidity(_poolTransfer._dAmount[i], _provider);
totalTransfer -= int256(_poolTransfer._dAmount[i]);
}
require(totalTransfer == 0, "LP Error: invalid transfer amount");
}
/**
* @notice withdraw porfits from the pool
* @param _pool liquidity pool address
*/
function withdrawProfits(IOddzLiquidityPool _pool) external {
require(poolExposure[_pool] > 0, "LP Error: Invalid pool");
uint256 premium = _pool.collectPremium(msg.sender, premiumLockupDuration);
require(premium > 0, "LP Error: No premium allocated");
token.safeTransfer(msg.sender, premium);
}
/**
* @notice update and returns locked liquidity
* @param _lid Id of LockedLiquidity that should be unlocked
* @param _account Provider account address
* @param _amount Funds that should be sent
*/
function _updateAndFetchLockedLiquidity(
uint256 _lid,
address _account,
uint256 _amount
) private returns (uint256 lockedPremium, uint256 transferAmount) {
LockedLiquidity storage ll = lockedLiquidity[_lid];
require(_account != address(0), "LP Error: Invalid address");
ll._locked = false;
lockedPremium = ll._premium;
transferAmount = _amount;
if (transferAmount > ll._amount) transferAmount = ll._amount;
for (uint8 i = 0; i < ll._pools.length; i++) {
IOddzLiquidityPool(ll._pools[i]).unlockLiquidity(ll._share[i]);
IOddzLiquidityPool(ll._pools[i]).exercisePremium(
_lid,
(lockedPremium * ll._share[i]) / ll._amount,
(transferAmount * ll._share[i]) / ll._amount
);
}
}
/**
* @notice return sorted eligible pools
* @param _liquidityParams Lock liquidity params
* @return pools sorted pools based on ascending order of available liquidity
* @return poolBalance sorted in ascending order of available liquidity
*/
function getSortedEligiblePools(LiquidityParams memory _liquidityParams)
public
view
returns (address[] memory pools, uint256[] memory poolBalance)
{
// if _expiration is 86401 i.e. 1 day 1 second, then max 1 day expiration pool will not be eligible
IOddzLiquidityPool[] memory allPools =
poolMapper[
keccak256(
abi.encode(
_liquidityParams._pair,
_liquidityParams._type,
_liquidityParams._model,
periodMapper[getActiveDayTimestamp(_liquidityParams._expiration) / 1 days]
)
)
];
uint256 count = 0;
for (uint8 i = 0; i < allPools.length; i++) {
if (allPools[i].availableBalance() > 0) {
count++;
}
}
poolBalance = new uint256[](count);
pools = new address[](count);
uint256 j = 0;
uint256 balance = 0;
for (uint256 i = 0; i < allPools.length; i++) {
if (allPools[i].availableBalance() > 0) {
pools[j] = address(allPools[i]);
poolBalance[j] = allPools[i].availableBalance();
balance += poolBalance[j];
j++;
}
}
(poolBalance, pools) = _sort(poolBalance, pools);
require(balance > _liquidityParams._amount, "LP Error: Amount is too large");
}
/**
* @notice Insertion sort based on pool balance since atmost 6 eligible pools
* @param balance list of liquidity
* @param pools list of pools with reference to balance
* @return sorted balance list in ascending order
* @return sorted pool list in ascending order of balance list
*/
function _sort(uint256[] memory balance, address[] memory pools)
private
pure
returns (uint256[] memory, address[] memory)
{
// Higher deployment cost but betters execution cost
int256 j;
uint256 unsignedJ;
uint256 unsignedJplus1;
uint256 key;
address val;
for (uint256 i = 1; i < balance.length; i++) {
key = balance[i];
val = pools[i];
j = int256(i - 1);
unsignedJ = uint256(j);
while ((j >= 0) && (balance[unsignedJ] > key)) {
unsignedJplus1 = unsignedJ + 1;
balance[unsignedJplus1] = balance[unsignedJ];
pools[unsignedJplus1] = pools[unsignedJ];
j--;
unsignedJ = uint256(j);
}
unsignedJplus1 = uint256(j + 1);
balance[unsignedJplus1] = key;
pools[unsignedJplus1] = val;
}
return (balance, pools);
}
/**
* @notice Add/update allowed max expiration
* @param _maxExpiration maximum expiration time of option
*/
function addAllowedMaxExpiration(uint256 _maxExpiration) public onlyOwner(msg.sender) {
allowedMaxExpiration[_maxExpiration] = true;
}
/**
* @notice sets the manager for the liqudity pool contract
* @param _address manager contract address
* Note: This can be called only by the owner
*/
function setManager(address _address) external {
require(_address != address(0) && _address.isContract(), "LP Error: Invalid manager address");
grantRole(MANAGER_ROLE, _address);
}
/**
* @notice removes the manager for the liqudity pool contract for valid managers
* @param _address manager contract address
* Note: This can be called only by the owner
*/
function removeManager(address _address) external {
revokeRole(MANAGER_ROLE, _address);
}
/**
* @notice sets the timelocker for the liqudity pool contract
* @param _address timelocker address
* Note: This can be called only by the owner
*/
function setTimeLocker(address _address) external {
require(_address != address(0), "LP Error: Invalid timelocker address");
grantRole(TIMELOCKER_ROLE, _address);
}
/**
* @notice removes the timelocker for the liqudity pool contract
* @param _address timelocker contract address
* Note: This can be called only by the owner
*/
function removeTimeLocker(address _address) external {
revokeRole(TIMELOCKER_ROLE, _address);
}
/**
* @notice sets required balance
* @param _reqBalance required balance between 6 and 9
* Note: This can be called only by the owner
*/
function setReqBalance(uint8 _reqBalance) external onlyTimeLocker(msg.sender) reqBalanceValidRange(_reqBalance) {
reqBalance = _reqBalance;
}
/**
* @notice map period
* @param _source source period
* @param _dest destimation period
* Note: This can be called only by the owner
*/
function mapPeriod(uint256 _source, uint256 _dest) public validMaxExpiration(_dest) onlyTimeLocker(msg.sender) {
periodMapper[_source] = _dest;
}
/**
* @notice Map pools for an option parameters
* @param _pair Asset pair address
* @param _type Option type
* @param _model Option premium model
* @param _period option period exposure
* @param _pools eligible pools based on above params
* Note: This can be called only by the owner
*/
function mapPool(
address _pair,
IOddzOption.OptionType _type,
bytes32 _model,
uint256 _period,
IOddzLiquidityPool[] memory _pools
) public onlyTimeLocker(msg.sender) {
require(_pools.length <= 10, "LP Error: pools length should be <= 10");
// delete all the existing pool mapping
IOddzLiquidityPool[] storage aPools = poolMapper[keccak256(abi.encode(_pair, _type, _model, _period))];
for (uint256 i = 0; i < aPools.length; i++) {
delete uniquePoolMapper[keccak256(abi.encode(_pair, _type, _model, _period, aPools[i]))];
poolExposure[aPools[i]] -= 1;
if (poolExposure[aPools[i]] == 0) disabledPools[aPools[i]] = true;
}
delete poolMapper[keccak256(abi.encode(_pair, _type, _model, _period))];
// add unique pool mapping
bytes32 uPool;
for (uint256 i = 0; i < _pools.length; i++) {
uPool = keccak256(abi.encode(_pair, _type, _model, _period, _pools[i]));
if (!uniquePoolMapper[uPool]) {
poolMapper[keccak256(abi.encode(_pair, _type, _model, _period))].push(_pools[i]);
uniquePoolMapper[uPool] = true;
poolExposure[_pools[i]] += 1;
disabledPools[_pools[i]] = false;
}
}
}
/**
* @notice get active day based on user input timestamp
* @param _timestamp epoch time
*/
function getActiveDayTimestamp(uint256 _timestamp) internal pure returns (uint256 activationDate) {
// activation date should be next day 00 hours if _timestamp % 86400 is greater than 0
if ((_timestamp % 1 days) > 0) _timestamp = _timestamp + 1 days;
(uint256 year, uint256 month, uint256 day) = DateTimeLibrary.timestampToDate(_timestamp);
activationDate = DateTimeLibrary.timestampFromDate(year, month, day);
}
/**
* @notice updates premium lockup duration
* @param _premiumLockupDuration premium lockup duration
*/
function updatePremiumLockupDuration(uint256 _premiumLockupDuration) public onlyTimeLocker(msg.sender) {
require(
_premiumLockupDuration >= 1 days && _premiumLockupDuration <= 30 days,
"LP Error: invalid premium lockup duration"
);
premiumLockupDuration = _premiumLockupDuration;
}
/**
* @notice updates move lockup duration
* @param _moveLockupDuration move lockup duration
*/
function updateMoveLockupDuration(uint256 _moveLockupDuration) public onlyTimeLocker(msg.sender) {
require(
_moveLockupDuration >= 3 days && _moveLockupDuration <= 30 days,
"LP Error: invalid move lockup duration"
);
moveLockupDuration = _moveLockupDuration;
}
function setStrategyManager(address _strategyManager) public onlyOwner(msg.sender) {
require(_strategyManager.isContract(), "LP Error: invalid strategy manager");
strategyManager = _strategyManager;
}
}
| * @notice return sorted eligible pools @param _liquidityParams Lock liquidity params @return pools sorted pools based on ascending order of available liquidity @return poolBalance sorted in ascending order of available liquidity/ if _expiration is 86401 i.e. 1 day 1 second, then max 1 day expiration pool will not be eligible | function getSortedEligiblePools(LiquidityParams memory _liquidityParams)
public
view
returns (address[] memory pools, uint256[] memory poolBalance)
{
IOddzLiquidityPool[] memory allPools =
poolMapper[
keccak256(
abi.encode(
_liquidityParams._pair,
_liquidityParams._type,
_liquidityParams._model,
periodMapper[getActiveDayTimestamp(_liquidityParams._expiration) / 1 days]
)
)
];
uint256 count = 0;
for (uint8 i = 0; i < allPools.length; i++) {
if (allPools[i].availableBalance() > 0) {
count++;
}
}
poolBalance = new uint256[](count);
pools = new address[](count);
uint256 j = 0;
uint256 balance = 0;
for (uint256 i = 0; i < allPools.length; i++) {
if (allPools[i].availableBalance() > 0) {
pools[j] = address(allPools[i]);
poolBalance[j] = allPools[i].availableBalance();
balance += poolBalance[j];
j++;
}
}
(poolBalance, pools) = _sort(poolBalance, pools);
require(balance > _liquidityParams._amount, "LP Error: Amount is too large");
}
| 1,042,700 | [
1,
2463,
3115,
21351,
16000,
225,
389,
549,
372,
24237,
1370,
3488,
4501,
372,
24237,
859,
327,
16000,
3115,
16000,
2511,
603,
13976,
1353,
434,
2319,
4501,
372,
24237,
327,
2845,
13937,
3115,
316,
13976,
1353,
434,
2319,
4501,
372,
24237,
19,
309,
389,
19519,
353,
19663,
1611,
277,
18,
73,
18,
404,
2548,
404,
2205,
16,
1508,
943,
404,
2548,
7686,
2845,
903,
486,
506,
21351,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
15175,
329,
4958,
16057,
16639,
12,
48,
18988,
24237,
1370,
3778,
389,
549,
372,
24237,
1370,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
8526,
3778,
16000,
16,
2254,
5034,
8526,
3778,
2845,
13937,
13,
203,
565,
288,
203,
3639,
1665,
449,
94,
48,
18988,
24237,
2864,
8526,
3778,
777,
16639,
273,
203,
5411,
2845,
4597,
63,
203,
7734,
417,
24410,
581,
5034,
12,
203,
10792,
24126,
18,
3015,
12,
203,
13491,
389,
549,
372,
24237,
1370,
6315,
6017,
16,
203,
13491,
389,
549,
372,
24237,
1370,
6315,
723,
16,
203,
13491,
389,
549,
372,
24237,
1370,
6315,
2284,
16,
203,
13491,
3879,
4597,
63,
588,
3896,
4245,
4921,
24899,
549,
372,
24237,
1370,
6315,
19519,
13,
342,
404,
4681,
65,
203,
10792,
262,
203,
7734,
262,
203,
5411,
308,
31,
203,
3639,
2254,
5034,
1056,
273,
374,
31,
203,
3639,
364,
261,
11890,
28,
277,
273,
374,
31,
277,
411,
777,
16639,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
454,
16639,
63,
77,
8009,
5699,
13937,
1435,
405,
374,
13,
288,
203,
7734,
1056,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
2845,
13937,
273,
394,
2254,
5034,
8526,
12,
1883,
1769,
203,
3639,
16000,
273,
394,
1758,
8526,
12,
1883,
1769,
203,
3639,
2254,
5034,
525,
273,
374,
31,
203,
3639,
2254,
5034,
11013,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
777,
16639,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
2
]
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20 _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title Contracts that should not own Contracts
* @author Remco Bloemen <remco@2π.com>
* @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner
* of this contract to reclaim ownership of the contracts.
*/
contract HasNoContracts is Ownable {
/**
* @dev Reclaim ownership of Ownable contracts
* @param _contractAddr The address of the Ownable to be reclaimed.
*/
function reclaimContract(address _contractAddr) external onlyOwner {
Ownable contractInst = Ownable(_contractAddr);
contractInst.transferOwnership(owner);
}
}
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20;
/**
* @dev Reclaim all ERC20 compatible tokens
* @param _token ERC20 The address of the token contract
*/
function reclaimToken(ERC20 _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
/**
* Automated buy back BOB tokens
*/
contract BobBuyback is Claimable, HasNoContracts, CanReclaimToken, Destructible {
using SafeMath for uint256;
ERC20 public token; //Address of BOB token contract
uint256 public maxGasPrice; //Highest gas price allowed for buyback transaction
uint256 public maxTxValue; //Highest amount of BOB sent in one transaction
uint256 public roundStartTime; //Timestamp when buyback starts (timestamp of the first block where buyback allowed)
uint256 public rate; //1 ETH = rate BOB
event Buyback(address indexed from, uint256 amountBob, uint256 amountEther);
constructor(ERC20 _token, uint256 _maxGasPrice, uint256 _maxTxValue) public {
token = _token;
maxGasPrice = _maxGasPrice;
maxTxValue = _maxTxValue;
roundStartTime = 0;
rate = 0;
}
/**
* @notice Somebody may call this to sell his tokens
* @param _amount How much tokens to sell
* Call to token.approve() required before calling this function
*/
function buyback(uint256 _amount) external {
require(tx.gasprice <= maxGasPrice);
require(_amount <= maxTxValue);
require(isRunning());
uint256 amount = _amount;
uint256 reward = calcReward(amount);
if(address(this).balance < reward) {
//If not enough money to fill request, handle it partially
reward = address(this).balance;
amount = reward.mul(rate);
}
require(token.transferFrom(msg.sender, address(this), amount));
msg.sender.transfer(reward);
emit Buyback(msg.sender, amount, reward);
}
/**
* @notice Calculates how much ETH somebody can receive for selling amount BOB
* @param amount How much tokens to sell
*/
function calcReward(uint256 amount) view public returns(uint256) {
if(rate == 0) return 0; //Handle situation when no Buyback is planned
return amount.div(rate); //This operation may result in rounding. Which is fine here (rounded amount < rate / 10**18)
}
/**
* @notice Calculates how much BOB tokens this contract can buy (during current buyback round)
*/
function calcTokensAvailableToBuyback() view public returns(uint256) {
return address(this).balance.mul(rate);
}
/**
* @notice Checks if Buyback round is running
*/
function isRunning() view public returns(bool) {
return (rate > 0) && (now >= roundStartTime) && (address(this).balance > 0);
}
/**
* @notice Changes buyback parameters
* @param _maxGasPrice Max gas price one ca use to sell is tokens.
* @param _maxTxValue Max amount of tokens to sell in one transaction
*/
function setup(uint256 _maxGasPrice, uint256 _maxTxValue) onlyOwner external {
maxGasPrice = _maxGasPrice;
maxTxValue = _maxTxValue;
}
/**
* @notice Starts buyback at specified time, with specified rate
* @param _roundStartTime Time when Buyback round starts
* @param _rate Rate of current Buyback round (1 ETH = rate BOB). Zero means no buyback is planned.
*/
function startBuyback(uint256 _roundStartTime, uint256 _rate) onlyOwner external payable {
require(_roundStartTime > now);
roundStartTime = _roundStartTime;
rate = _rate; //Rate is not required to be > 0
}
/**
* @notice Claim all BOB tokens stored on the contract and send them to owner
*/
function claimTokens() onlyOwner external {
require(token.transfer(owner, token.balanceOf(address(this))));
}
/**
* @notice Claim some of tokens stored on the contract
* @param amount How much tokens to claim
* @param beneficiary Who to send this tokens
*/
function claimTokens(uint256 amount, address beneficiary) onlyOwner external {
require(token.transfer(beneficiary, amount));
}
/**
* @notice Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() onlyOwner external {
owner.transfer(address(this).balance);
}
} | * @title Contracts that should be able to recover tokens @author SylTi @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. This will prevent any accidental loss of tokens./ | contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20;
function reclaimToken(ERC20 _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
| 1,644,753 | [
1,
20723,
716,
1410,
506,
7752,
358,
5910,
2430,
225,
16455,
80,
56,
77,
225,
1220,
1699,
279,
6835,
358,
5910,
1281,
4232,
39,
3462,
1147,
5079,
316,
279,
6835,
635,
906,
74,
20245,
326,
11013,
358,
326,
6835,
3410,
18,
1220,
903,
5309,
1281,
25961,
287,
8324,
434,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4480,
426,
14784,
1345,
353,
14223,
6914,
288,
203,
225,
1450,
14060,
654,
39,
3462,
364,
4232,
39,
3462,
31,
203,
203,
225,
445,
283,
14784,
1345,
12,
654,
39,
3462,
389,
2316,
13,
3903,
1338,
5541,
288,
203,
565,
2254,
5034,
11013,
273,
389,
2316,
18,
12296,
951,
12,
2211,
1769,
203,
565,
389,
2316,
18,
4626,
5912,
12,
8443,
16,
11013,
1769,
203,
225,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.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) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ALPHA {
using SafeMath for uint;
string public name; // ERC20 标准
string public symbol; // ERC20 标准
uint256 public decimals; // ERC20 标准,decimals 可以有的小数点个数,最小的代币单位。18 是建议的默认值
uint256 public totalSupply; // ERC20 标准 总供应量
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
constructor(uint256 initialSupply, string memory tokenName, string memory tokenSymbol, uint256 _decimals) public {
totalSupply = initialSupply * 10 ** _decimals; // 供应的份额,份额跟最小的代币单位有关,份额 = 币数 * 10 ** decimals。
balanceOf[msg.sender] = totalSupply; // 创建者拥有所有的代币
name = tokenName; // 代币名称
symbol = tokenSymbol; // 代币符号
decimals = _decimals;
}
function _transfer(address _from, address _to, uint _value) internal {//检测了_to 是否为空地址,但未检测地址_to 和_from 是否为同地址
require(_to != address(0)&& _from != _to);
require(balanceOf[_from] >= _value);
require(balanceOf[_to].add(_value) > balanceOf[_to]);
uint previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
function transfer(address _to, uint256 _value) public {
// require(_to != address(0) && _to != _from);
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {//显示的返回了 true,检测地址_to 和_from 是否为同地址,检测地址_from 是否为空地址
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public//不存在交易顺序依赖
returns (bool success) {
require(_spender != address(0));
require((_value == 0) || (allowance[msg.sender][_spender] == 0));
allowance[msg.sender][_spender] = _value;
return true;
}
} | 供应的份额,份额跟最小的代币单位有关,份额 = 币数 * 10 ** decimals。
| totalSupply = initialSupply * 10 ** _decimals; | 14,556,872 | [
1,
165,
127,
254,
166,
123,
247,
168,
253,
231,
165,
124,
126,
170,
100,
256,
176,
125,
239,
165,
124,
126,
170,
100,
256,
169,
120,
258,
167,
255,
227,
166,
113,
242,
168,
253,
231,
165,
124,
101,
166,
121,
228,
166,
240,
248,
165,
126,
240,
167,
255,
236,
166,
232,
116,
176,
125,
239,
165,
124,
126,
170,
100,
256,
273,
225,
166,
121,
228,
167,
248,
113,
225,
1728,
225,
15105,
164,
227,
229,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
2078,
3088,
1283,
273,
2172,
3088,
1283,
380,
1728,
2826,
389,
31734,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "./SafeOwnable.sol";
import "./HasManagers.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
/**
* Domain access control is defined here. It involves some roles being defined,
* some lists and lookups detailing default permissions, and a hierarchy that
* is enforced privately across 3 defined roles in access-control traits:
* general management, per-TLD management, and domain registrant.
*/
abstract contract HasDomainsAccessControl is SafeOwnable, HasManagers, AccessControlEnumerable {
/**
* Managers in this role will have permissions (inside a specific TLD they
* are authorized to) to perform the following actions:
* - Add a new domain (or recover a released domain, under their responsibility).
* - Release a domain they are responsible for.
* - Transfer a domain they are responsible for (the target must not be address(0)
* and also they must be in either specific-TLD registrant in the same TLD,
* or any-TLD registrant).
* Every manager / admin will belong to either a specific TLD or belong to the
* default list, and have this role. In the former case, typically one or more TLDs
* will be assigned to them.
*
* An entry relating (tld, address) => {add, release, transfer} may modify the
* permissions the address has inside this tld. By default, a user in this role
* will have no permissions over a given TLD unless the TLD has an entry for it,
* being the entry the one which enables the action by setting it to true.
*
* However, if the address also is enabled into the defaultDomainRegistrants set
* then the default permissions when lacking an entry for a given TLD, is to have
* permissions to do any of the 3 actions in the TLD.
*
* The TLD configuration, for the involved domain, may however have their own
* flags {add, release, transfer} in false (they default in true), thus blocking
* the required action despite the address being among the default registrants.
* When this happens, only the contract owner or an address in the tld manager
* role (described way below) can handle them.
*/
bytes32 public domainRegistrantRole;
/**
* Tells whether a particular address belongs to the default domain registrants
* set or not. To add an entry, assign it to true. To remove an entry, assign it
* to false. Entries are not definitely removed, ever, but they may be disabled.
* In order to be added to this set, an entry must exist as a manager entry from
* the managers trait.
*/
mapping(address => bool) public defaultDomainRegistrants;
/**
* Tells the whole list of addresses eventually added to the defaultDomainRegistrants
* mapping (even if they were removed later). Meant for enumeration.
*/
address[] public defaultDomainRegistrantsList;
/**
* Returns the length of the defaultDomainRegistrantsList. Meant for enumeration.
*/
function defaultDomainRegistrantsCount() public view returns (uint256) {
return defaultDomainRegistrantsList.length;
}
/**
* Managers in this role can handle their TLD completely, including:
* - The three actions of domainRegistrantRole, over their own domains.
* This is because they will also have this role: domainRegistrantRole.
* - The same three actions over domains they are not responsible of, but
* others are, except when the other one also belongs to tldManagerRole.
* They are not restricted by the per-TLD restrictions, and they ignore
* their own entry in the TLD related to their domainRegistrantRole, if
* they ever have / had one.
* - The ability to change the said per-TLD restrictions.
* - The ability to add addresses (provided they have the domainRegistrantRole)
* to the TLD or TLDs they manage, or change their per-address permissions.
*/
bytes32 public tldManagerRole;
/**
* Tells whether a particular address belongs to the default TLD managers
* or not. To add an entry, assign it to true. To remove an entry, assign
* it to false. Entries are not definitely removed, ever, but they may be
* disabled. In order to be added to this set, an entry must exist as a
* manager entry from the managers trait.
*/
mapping(address => bool) defaultTLDManagers;
/**
* Tells the whole list of addresses eventually added to the defaultTLDManagers
* mapping (even if they were removed later). Meant for enumeration.
*/
address[] public defaultTLDManagersList;
/**
* Returns the length of the defaultTLDManagersList. Meant for enumeration.
*/
function defaultTLDManagersCount() public view returns (uint256) {
return defaultTLDManagersList.length;
}
/**
* Manager in this role will also include the tldManagerRole and also the
* domainRegistrantRole (notice how this role name says "tlds", in plural).
* Aside from the other said permissions, they are not restricted by other
* users' roles. This role is typically intended for really trusted users.
* They can CREATE a TLD, not just change their permissions or set registrants
* into it / modify their per-address permissions.
*
* They have direct access to ALL of the TLDs, in contrast to the previous
* two roles, and they can add addresses (provided they have the tldManagerRole)
* as managers to certain TLDs, or as default TLDs managers. Also, they can
* add addresses (provided they have the domainRegistrantRole) as default
* domain registrants (i.e. for all the TLDs).
*
* The only thing they CANNOT do, is to make new addresses become this role,
* or existing addresses lose this role. That is reserved solely to the owner
* of this contract, and such owner has all the permissions in this role and
* the others, with no limitation of any type.
*/
bytes32 public tldsManagerRole;
constructor() {
domainRegistrantRole = keccak256(abi.encodePacked("Access Role", "Domain Registrant"));
tldManagerRole = keccak256(abi.encodePacked("Access Role", "TLD Manager"));
tldsManagerRole = keccak256(abi.encodePacked("Access Role", "TLDs Manager"));
}
// Notes: Only query functions that ask for permissions will be coded here. Also,
// some abstract methods will be added -which interact with more data- which
// will be overridden later.
/**
* Tells whether the account is a TLDs manager (i.e. a global, trusted user, who
* can do anything on registered TLDs or even create one).
*/
function isTLDsManager(address who) public view returns (bool) {
return who != address(0) && managers[who].enabled && hasRole(tldsManagerRole, who);
}
/**
* Tells whether the account is a specific TLD manager (i.e. a default TLD manager
* for any TLD, or a registered TLD manager for a specific TLD).
*/
function isTLDManager(bytes32 tldHash, address who) public view returns (bool) {
return who != address(0) && managers[who].enabled && hasRole(tldManagerRole, who) &&
(defaultTLDManagers[who] || _managesTheTLD(tldHash, who));
}
/**
* Tells whether the account is registered as a manager related to a specific TLD hash.
* To this point, it is known that the address is not 0x0 and it HAS the tld manager role.
* Override it to specify the particular behaviour.
*/
function _managesTheTLD(bytes32 tldHash, address who) internal view virtual returns (bool);
/**
* Tells whether the account is registered as a domain registrant to a specific TLD hash.
* The check will involve, first, an explicit permission check (which asks for specific
* flags allowing/disallowing the account to add, release or transfer a domain).
*/
function isDomainRegistrant(
bytes32 tldHash, address who,
bool requireAdd, bool requireRelease, bool requireTransfer
) public view returns (bool) {
if (who != address(0) && managers[who].enabled && hasRole(domainRegistrantRole, who)) {
// 1. We rely on the address having an explicit permission in the TLD setting. If an
// explicit permission is set, then we check that the required flags are true in
// the permissions, if any is required.
(bool explicit, bool canAdd, bool canRelease, bool canTransfer) = hasExplicitTLDPermission(tldHash, who);
if (explicit) {
return (canAdd && !requireAdd) && (canRelease || !requireRelease) && (canTransfer || !requireTransfer);
}
// 2. Otherwise, we rely on the address belonging to the defaultDomainRegistrants.
return defaultDomainRegistrants[who];
} else {
return false;
}
}
/**
* Tells whether an address is explicitly registered into a TLD. If it has an explicit
* setting, then the 3 flags must also be returned as the result value, with the first
* value being true. Otherwise, the first value must be false, and the 3 other result
* values don't matter.
*/
function hasExplicitTLDPermission(
bytes32 tldHash, address who
) public view virtual returns (bool explicit, bool canAdd, bool canRelease, bool canTransfer);
/**
* Methods with this modifier revert for the 0x0 address. Applies in particular to the
* following six grant/revoke methods.
*/
modifier requireNonZeroAddress(address who) {
require(who != address(0), "Cannot grant to, or revoke to, address 0x0 any role");
_;
}
/**
* Grants the TLDs Management Role to a non-zero address.
*/
function _grantTLDsManagementRole(address who) internal requireNonZeroAddress(who) {
_grantRole(tldsManagerRole, who);
}
/**
* Revokes the TLDs Management Role to a non-zero address.
*/
function _revokeTLDsManagementRole(address who) internal requireNonZeroAddress(who) {
_revokeRole(tldsManagerRole, who);
}
/**
* Grants the TLD Management Role to a non-zero address.
*/
function _grantTLDManagementRole(address who) internal requireNonZeroAddress(who) {
_grantRole(tldManagerRole, who);
}
/**
* Revokes the TLD Management Role to a non-zero address.
*/
function _revokeTLDManagementRole(address who) internal requireNonZeroAddress(who) {
_revokeRole(tldManagerRole, who);
}
/**
* Grants the Domain Registrant Role to a non-zero address.
*/
function _grantDomainRegistrarRole(address who) internal requireNonZeroAddress(who) {
_grantRole(domainRegistrantRole, who);
}
/**
* Revokes the Domain Registrant Role to a non-zero address.
*/
function _revokeDomainRegistrarRole(address who) internal requireNonZeroAddress(who) {
_revokeRole(domainRegistrantRole, who);
}
}
| * Revokes the Domain Registrant Role to a non-zero address./ | function _revokeDomainRegistrarRole(address who) internal requireNonZeroAddress(who) {
_revokeRole(domainRegistrantRole, who);
}
| 12,953,048 | [
1,
10070,
601,
281,
326,
6648,
2526,
3337,
970,
6204,
358,
279,
1661,
17,
7124,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
9083,
3056,
3748,
30855,
2996,
12,
2867,
10354,
13,
2713,
2583,
3989,
7170,
1887,
12,
3350,
83,
13,
288,
203,
3639,
389,
9083,
3056,
2996,
12,
4308,
20175,
970,
2996,
16,
10354,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/44787/0xf67aa6F4d4DCB3C0aef1886AC8d15761B3811901/sources/contracts/ToucanCarbonOffsetsEscrow.sol | @notice Create a new detokenization request. @dev Only a TCO2 contract can call this function. Additionally, the escrow contract must have been approved to transfer the amount of TCO2 to detokenize. @param user The user that is requesting the detokenization. @param amount The amount of TCO2 to detokenize. @param batchTokenIds The ids of the batches to detokenize. Bump request id | function createDetokenizationRequest(
address user,
uint256 amount,
uint256[] calldata batchTokenIds
) external virtual override onlyTCO2 returns (uint256) {
uint256 requestId = requestIdCounter;
unchecked {
++requestId;
}
requestIdCounter = requestId;
user,
amount,
RequestType.Detokenization,
RequestStatus.Pending,
batchTokenIds
);
user,
address(this),
amount
);
return requestId;
}
| 13,254,286 | [
1,
1684,
279,
394,
3023,
969,
1588,
590,
18,
225,
5098,
279,
399,
3865,
22,
6835,
848,
745,
333,
445,
18,
26775,
16,
326,
2904,
492,
6835,
1297,
1240,
2118,
20412,
358,
7412,
326,
3844,
434,
399,
3865,
22,
358,
3023,
969,
554,
18,
225,
729,
1021,
729,
716,
353,
18709,
326,
3023,
969,
1588,
18,
225,
3844,
1021,
3844,
434,
399,
3865,
22,
358,
3023,
969,
554,
18,
225,
2581,
1345,
2673,
1021,
3258,
434,
326,
13166,
358,
3023,
969,
554,
18,
605,
2801,
590,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
752,
4986,
969,
1588,
691,
12,
203,
3639,
1758,
729,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
2581,
1345,
2673,
203,
565,
262,
3903,
5024,
3849,
1338,
56,
3865,
22,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
14459,
273,
14459,
4789,
31,
203,
3639,
22893,
288,
203,
5411,
965,
2293,
548,
31,
203,
3639,
289,
203,
3639,
14459,
4789,
273,
14459,
31,
203,
203,
5411,
729,
16,
203,
5411,
3844,
16,
203,
5411,
1567,
559,
18,
4986,
969,
1588,
16,
203,
5411,
1567,
1482,
18,
8579,
16,
203,
5411,
2581,
1345,
2673,
203,
3639,
11272,
203,
203,
5411,
729,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
3844,
203,
3639,
11272,
203,
203,
3639,
327,
14459,
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
]
|
pragma solidity >= 0.4.24;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
address private app;
struct Airline {
uint id;
string name;
bool approved;
bool active;
uint balance;
uint reserved;
uint needed_votes;
uint gained_votes;
}
uint private airline_counter = 0;
mapping(address => Airline) airlines;
mapping(address => mapping(address => bool)) voters_record;
struct Passenger {
address passenger_address;
uint balance;
}
mapping(address => Passenger) passengers;
uint private policies_counter = 0;
struct Insurance {
address holder;
address airline_address;
uint32 flight_id;
uint32 departure_time;
uint cost;
bool claimed;
}
mapping(address => mapping(uint32 => mapping(uint32 => bool))) reservelog;
mapping(uint => Insurance) insurances;
struct Flight {
address airline_address;
uint32 flight_id;
uint32 departure_time;
bool registred;
uint32 status;
}
//airline address => flight no => departure => status
mapping(address => mapping(uint32 => mapping(uint32 => uint32))) flights;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AirlineRegistered(address _address, uint id, string name);
event AirlineApproved(address _address, uint id, string name);
event AirlineActivated(address _address, uint id, string name);
event InsuranceBought(uint policy, address holder,address airline,uint32 flight_id, uint32 depature_time, uint price);
event InsuranceClaimed(uint policy, address holder,address airline,uint32 flight_id, uint32 depature_time, uint amount);
event BalanceWithdraw(address holder, uint amount);
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
//enhance the contract protection post deployment to only recive from App
modifier fromAppAdress()
{
require(app == address(0) || msg.sender == app, "Caller is not the linked application");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(address _from,
string _name,
address _address
)
external
requireIsOperational
fromAppAdress
{
require((airlines[_address].approved == false), "Already registred");
uint _id = airline_counter;
if (airline_counter == 0) {
Airline memory item = Airline(_id, _name, true, false, 0,0,0,0);
airline_counter++;
airlines[_address] = item;
emit AirlineRegistered(_address, _id, _name);
emit AirlineApproved(_address, _id, _name);
} else if (airline_counter > 0 && airline_counter < 4) {
require((airlines[_from].approved == true && airlines[_from].active == true), "This transaction must be done by from an account of an approved and active airline");
Airline memory item2 = Airline(_id, _name, true, false, 0,0,1,1);
airline_counter++;
airlines[_address] = item2;
emit AirlineRegistered(_address, _id, _name);
emit AirlineApproved(_address, _id, _name);
} else if (airline_counter >= 4) {
//require(airlines[msg.sender].approved == true, "This transaction must be done by from an account of an approvedd airline");
require(_address == _from, "Must apply from same account");
uint _needed = ((airline_counter / 2 ) + ( airline_counter % 2 ));
Airline memory item3 = Airline(_id, _name, false, false, 0, 0,_needed,0);
airline_counter++;
airlines[_address] = item3;
emit AirlineRegistered(_address, _id, _name);
}
}
function AirlineStatus
(address _address)
external view
requireIsOperational
fromAppAdress
returns (bool status)
{
return airlines[_address].approved && airlines[_address].active;
}
function approveAirline
(address _from,
address _address)
external
requireIsOperational
fromAppAdress
{
require(airlines[_address].approved == false, "This Airline already got approved");
require(airlines[_from].approved == true && airlines[_from].active == true, "This transaction must be done by from an account of an approvedd airline");
require(voters_record[_address][_from] == false, "This account already approved this airline");
airlines[_address].gained_votes++;
voters_record[_address][_from] = true;
if (airlines[_address].gained_votes == airlines[_address].needed_votes) {
airlines[_address].approved = true;
emit AirlineApproved(_address, airlines[_address].id, airlines[_address].name);
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(address _from,
address _airline_address,
uint32 _flight_id,
uint32 _departure_time
)
external
payable
requireIsOperational
fromAppAdress
{
//1000000000000000000
require(flights[_airline_address][_flight_id][_departure_time] == 0, "This flight already have confirmed status");
require(reservelog[_airline_address][_flight_id][_departure_time] == false, "This account already bought an insurance for this flight");
require(msg.value <= 1000000000000000000, "Cannot buy insurance for more than 1 ether (1000000000000000000 wei)");
require(msg.value > 0, "The price must be higher than 0 wei");
require(((uint(msg.value) * uint(3)) / uint(2)) <= (airlines[_airline_address].balance - airlines[_airline_address].reserved), "The request Airline is sold out of insurances");
Insurance memory item = Insurance(_from,_airline_address, _flight_id, _departure_time, msg.value, false);
uint count = policies_counter;
insurances[count] = item;
policies_counter++;
reservelog[_airline_address][_flight_id][_departure_time] = true;
airlines[_airline_address].reserved = airlines[_airline_address].reserved + ((uint(msg.value) * uint(3)) / uint(2));
airlines[_airline_address].balance = airlines[_airline_address].balance + msg.value;
emit InsuranceBought(count,_from,_airline_address,_flight_id,_departure_time,msg.value);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(address _from,
uint _policy
)
external
requireIsOperational
fromAppAdress
{
require(insurances[_policy].claimed == false, "Policy Already Claimed");
require(insurances[_policy].holder == _from, "Requester is not the Policy Owner");
require(flights[insurances[_policy].airline_address][insurances[_policy].flight_id][insurances[_policy].departure_time] == 20,"The current flight status is not delayed duo to airline failure");
require((airlines[insurances[_policy].airline_address].balance >= ((uint(insurances[_policy].cost) * uint(3)) / uint(2)) && (airlines[insurances[_policy].airline_address].reserved >= ((uint(insurances[_policy].cost) * uint(3)) / uint(2)))),"The airline cannot provide insurance payment at the moment");
insurances[_policy].claimed = true;
airlines[insurances[_policy].airline_address].balance = airlines[insurances[_policy].airline_address].balance - ((uint(insurances[_policy].cost) * uint(3)) / uint(2));
airlines[insurances[_policy].airline_address].reserved = airlines[insurances[_policy].airline_address].reserved - ((uint(insurances[_policy].cost) * uint(3)) / uint(2));
passengers[_from].balance = passengers[_from].balance + ((uint(insurances[_policy].cost) * uint(3)) / uint(2));
emit InsuranceClaimed(_policy,insurances[_policy].holder,insurances[_policy].airline_address,insurances[_policy].flight_id,insurances[_policy].departure_time,((uint(insurances[_policy].cost) * uint(3)) / uint(2)));
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(address _from)
external
requireIsOperational
fromAppAdress
{
require(passengers[_from].balance > 0,"The account balance is currently empty");
uint sum = passengers[_from].balance;
passengers[_from].balance = 0;
address temp = _from;
temp.transfer(sum);
emit BalanceWithdraw(temp,sum);
}
/**
* @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 _from
)
external
payable
requireIsOperational
fromAppAdress
{
require(airlines[_from].approved == true, "funding transaction must be done by from an account of an approved airline");
require(msg.value >= 10000000000000000000, "The Value must be 10 ether more");
//1000000000000000000
airlines[_from].balance = msg.value;
airlines[_from].active = true;
emit AirlineActivated(_from, airlines[_from].id, airlines[_from].name);
}
function setAppAddress (address _app) public requireContractOwner {
app = _app;
}
//airline address => flight no => departure => status
function setFlightStatus (address _airline_address,
uint32 _flight_id,
uint32 _departure_time,
uint32 _status)
external
requireIsOperational
fromAppAdress
{
//sec
flights[_airline_address][_flight_id][_departure_time] = _status;
}
function getFlightStatus (address _airline_address,
uint32 _flight_id,
uint32 _departure_time)
external
view
requireIsOperational
returns (uint32 status)
{
//sec
return flights[_airline_address][_flight_id][_departure_time];
}
/*
function getAirlineInfo (address _address) external requireIsOperational
returns (){
}
*/
/*
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
*/
/**
* @dev Fallback function for funding smart contract.
*
*/
function() public payable
{
//fund();
}
}
| airline address => flight no => departure => status | mapping(address => mapping(uint32 => mapping(uint32 => uint32))) flights;
| 15,844,838 | [
1,
1826,
1369,
1758,
516,
25187,
1158,
516,
26000,
594,
516,
1267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
1578,
516,
2874,
12,
11890,
1578,
516,
2254,
1578,
20349,
1183,
10730,
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
]
|
./partial_match/1/0xba80b75009Ca4E5b94D97DBd9b5A550edb510C08/sources/DAXCoin.sol | Solidity only automatically asserts when dividing by 0 | function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
| 4,154,365 | [
1,
25044,
560,
1338,
6635,
26124,
1347,
3739,
10415,
635,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
282,
445,
3739,
12,
11890,
279,
16,
2254,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
12,
11890,
13,
288,
203,
4202,
2583,
12,
70,
405,
374,
16,
9324,
1769,
203,
4202,
2254,
276,
273,
279,
342,
324,
31,
203,
203,
4202,
327,
276,
31,
203,
282,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Ethertote - TeamEth time-locked smart contract
//
// The following contract offers peace of mind to investors as the
// Eth that will go to the members of the Ethertote team
// will be time-locked whereby a maximum of 25% of the Eth can be withdrawn
// from the smart contract every 3 months, starting from December 1st 2018
//
// Withdraw functions can only be called when the current timestamp is
// greater than the time specified in each functions
// ----------------------------------------------------------------------------
pragma solidity 0.4.24;
///////////////////////////////////////////////////////////////////////////////
// SafeMath Library
///////////////////////////////////////////////////////////////////////////////
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
///////////////////////////////////////////////////////////////////////////////
// Main contract
//////////////////////////////////////////////////////////////////////////////
contract TeamEth {
using SafeMath for uint256;
address public thisContractAddress;
address public admin;
// the first team withdrawal can be made after:
// GMT: Saturday, 1 December 2018 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate1 = 1543622400;
// the second team withdrawal can be made after:
// GMT: Friday, 1 March 2019 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate2 = 1551398400;
// the third team withdrawal can be made after:
// GMT: Saturday, 1 June 2019 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate3 = 1559347200;
// the final team withdrawal can be made after:
// GMT: Sunday, 1 September 2019 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate4 = 1567296000;
// time of the contract creation
uint256 public createdAt;
// amount of eth that will be claimed
uint public ethToBeClaimed;
// ensure the function is only called once
bool public claimAmountSet;
// percentage that the team can withdraw Eth
// it can naturally be inferred that quarter4 will also be 25%
uint public percentageQuarter1 = 25;
uint public percentageQuarter2 = 25;
uint public percentageQuarter3 = 25;
// 100%
uint public hundredPercent = 100;
// calculating the number used as the divider
uint public quarter1 = hundredPercent.div(percentageQuarter1);
uint public quarter2 = hundredPercent.div(percentageQuarter2);
uint public quarter3 = hundredPercent.div(percentageQuarter3);
bool public withdraw_1Completed;
bool public withdraw_2Completed;
bool public withdraw_3Completed;
event Received(address from, uint256 amount);
event Withdrew(address to, uint256 amount);
modifier onlyAdmin {
require(msg.sender == admin);
_;
}
constructor () public {
admin = msg.sender;
thisContractAddress = address(this);
createdAt = now;
}
// fallback to store all the ether sent to this address
function() payable public {
}
function thisContractBalance() public view returns(uint) {
return address(this).balance;
}
function setEthToBeClaimed() onlyAdmin public {
require(claimAmountSet == false);
ethToBeClaimed = address(this).balance;
claimAmountSet = true;
}
// team withdrawal after specified time
function withdraw_1() onlyAdmin public {
require(ethToBeClaimed > 0);
require(withdraw_1Completed == false);
// ensure current time is later than time set
require(now >= unlockDate1);
// now allow a percentage of the balance to be claimed
admin.transfer(ethToBeClaimed.div(quarter1));
emit Withdrew(admin, ethToBeClaimed.div(quarter1)); // 25%
withdraw_1Completed = true;
}
// team withdrawal after specified time
function withdraw_2() onlyAdmin public {
require(ethToBeClaimed > 0);
require(withdraw_2Completed == false);
// ensure current time is later than time set
require(now >= unlockDate2);
// now allow a percentage of the balance to be claimed
admin.transfer(ethToBeClaimed.div(quarter2));
emit Withdrew(admin, ethToBeClaimed.div(quarter2)); // 25%
withdraw_2Completed = true;
}
// team withdrawal after specified time
function withdraw_3() onlyAdmin public {
require(ethToBeClaimed > 0);
require(withdraw_3Completed == false);
// ensure current time is later than time set
require(now >= unlockDate3);
// now allow a percentage of the balance to be claimed
admin.transfer(ethToBeClaimed.div(quarter3));
emit Withdrew(admin, ethToBeClaimed.div(quarter3)); // 25%
withdraw_3Completed = true;
}
// team withdrawal after specified time
function withdraw_4() onlyAdmin public {
// ensure current time is later than time set
require(now >= unlockDate4);
// now allow all remaining balance to be claimed
admin.transfer(address(this).balance);
emit Withdrew(admin, address(this).balance); // all remaining balance
}
} | team withdrawal after specified time ensure current time is later than time set now allow all remaining balance to be claimed | function withdraw_4() onlyAdmin public {
require(now >= unlockDate4);
admin.transfer(address(this).balance);
}
| 2,346,197 | [
1,
10035,
598,
9446,
287,
1839,
1269,
813,
3387,
783,
813,
353,
5137,
2353,
813,
444,
2037,
1699,
777,
4463,
11013,
358,
506,
7516,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
67,
24,
1435,
1338,
4446,
1071,
288,
203,
4202,
2583,
12,
3338,
1545,
7186,
1626,
24,
1769,
203,
4202,
3981,
18,
13866,
12,
2867,
12,
2211,
2934,
12296,
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
]
|
pragma solidity ^0.5.0;
import "./zeppelin/token/ERC777/ERC777.sol";
interface ReversibleICO {
function getParticipantReservedTokens(address) external view returns (uint256);
}
contract ReversibleICOToken is ERC777 {
ReversibleICO public rICO;
bool public frozen; // default: false
bool public initialized; // default: false
// addresses
address public deployingAddress;
address public tokenGenesisAddress; // Receives the initial amount and can set the migration address, as well as the rICO, if not set initially
address public migrationAddress; // The contract address which will handle the token migration
address public freezerAddress; // should be same as freezer address in rICO
address public rescuerAddress; // should be same as rescuerAddress address in rICO
/*
* Events
*/
event SetRICOaddress(address indexed rICOAddress);
event SetMigrationAddress(address indexed migrationAddress);
event Frozen(address indexed freezerAddress);
event Unfrozen(address indexed freezerAddress);
event RemovedFreezer(address indexed freezerAddress);
event ChangedRICO(address indexed rICOAddress, address indexed rescuerAddress);
// ------------------------------------------------------------------------------------------------
constructor(
string memory name,
string memory symbol,
address[] memory _defaultOperators
)
ERC777(name, symbol, _defaultOperators)
public
{
deployingAddress = msg.sender;
}
// Init the rICO token and attach it to the rICO
function init(
address _ricoAddress,
address _freezerAddress,
address _rescuerAddress,
address _tokenGenesisAddress,
uint256 _initialSupply
)
public
isNotInitialized
onlyDeployingAddress
{
require(_freezerAddress != address(0), "_freezerAddress cannot be 0x");
require(_rescuerAddress != address(0), "_rescuerAddress cannot be 0x");
require(_tokenGenesisAddress != address(0), "_tokenGenesisAddress cannot be 0x");
tokenGenesisAddress = _tokenGenesisAddress;
freezerAddress = _freezerAddress;
rescuerAddress = _rescuerAddress;
_mint(_tokenGenesisAddress, _tokenGenesisAddress, _initialSupply, "", "");
if(_ricoAddress != address(0)) {
rICO = ReversibleICO(_ricoAddress);
emit SetRICOaddress(_ricoAddress);
}
initialized = true;
}
function setRICOaddress(address _ricoAddress)
public
onlyTokenGenesisAddress
{
require(address(rICO) == address(0), "rICO address already set!");
require(_ricoAddress != address(0), "rICO address cannot be 0x.");
rICO = ReversibleICO(_ricoAddress);
emit SetRICOaddress(_ricoAddress);
}
// *** Migration process
function setMigrationAddress(address _migrationAddress)
public
onlyTokenGenesisAddress
{
migrationAddress = _migrationAddress;
emit SetMigrationAddress(migrationAddress);
}
// *** SECURITY functions
function removeFreezer()
public
onlyFreezerAddress
isNotFrozen
{
freezerAddress = address(0);
emit RemovedFreezer(freezerAddress);
}
function freeze() public onlyFreezerAddress {
frozen = true;
emit Frozen(freezerAddress);
}
function unfreeze() public onlyFreezerAddress {
frozen = false;
emit Unfrozen(freezerAddress);
}
// The rICO address can only be changed when the contract is frozen
function changeRICO(address _newRicoAddress)
public
onlyRescuerAddress
isFrozen
{
rICO = ReversibleICO(_newRicoAddress);
emit ChangedRICO(_newRicoAddress, rescuerAddress);
}
// *** Public functions
function getLockedBalance(address _owner) public view returns(uint256) {
// only check the locked balance, if a rICO is set
if(address(rICO) != address(0)) {
return rICO.getParticipantReservedTokens(_owner);
} else {
return 0;
}
}
function getUnlockedBalance(address _owner) public view returns(uint256) {
uint256 balance = balanceOf(_owner);
// only check the locked balance, if a rICO is set
if(address(rICO) != address(0)) {
uint256 locked = rICO.getParticipantReservedTokens(_owner);
if(balance > 0 && locked > 0) {
if(balance >= locked) {
return balance.sub(locked);
} else {
return 0;
}
}
}
return balance;
}
// *** Internal functions
// We need to override send / transfer methods in order to only allow transfers within RICO unlocked calculations
// The rico address can receive any amount for withdraw functionality
function _move(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes memory _userData,
bytes memory _operatorData
)
internal
isNotFrozen
isInitialized
{
// If tokens are send to the rICO, OR tokens are sent to the migration contract allow transfers of the total balance
if(
_to == address(rICO) ||
_to == migrationAddress
) {
// full balance can be sent back to rico or migration address
require(_amount <= balanceOf(_from), "Sending failed: Insufficient funds");
} else {
// for every other address limit to unlocked balance
require(_amount <= getUnlockedBalance(_from), "Sending failed: Insufficient funds");
}
ERC777._move(_operator, _from, _to, _amount, _userData, _operatorData);
}
// We override burn as well. So users can not burn locked tokens.
function _burn(
address _operator,
address _from,
uint256 _amount,
bytes memory _data,
bytes memory _operatorData
)
internal
isNotFrozen
isInitialized
{
require(_amount <= getUnlockedBalance(_from), "Burning failed: Insufficient funds");
ERC777._burn(_operator, _from, _amount, _data, _operatorData);
}
// *** Modifiers
/**
* @notice Checks if the sender is the deployer.
*/
modifier onlyDeployingAddress() {
require(msg.sender == deployingAddress, "Only the deployer can call this method.");
_;
}
/**
* @notice Checks if the sender is the tokenGenesisAddress.
*/
modifier onlyTokenGenesisAddress() {
require(msg.sender == tokenGenesisAddress, "Only the tokenGenesisAddress can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyFreezerAddress() {
require(msg.sender == freezerAddress, "Only the freezer address can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyRescuerAddress() {
require(msg.sender == rescuerAddress, "Only the rescuer address can call this method.");
_;
}
/**
* @notice Requires the contract to have been initialized.
*/
modifier isInitialized() {
require(initialized == true, "Contract must be initialized.");
_;
}
/**
* @notice Requires the contract to NOT have been initialized,
*/
modifier isNotInitialized() {
require(initialized == false, "Contract is already initialized.");
_;
}
/**
* @notice @dev Requires the contract to be frozen.
*/
modifier isFrozen() {
require(frozen == true, "Token contract not frozen.");
_;
}
/**
* @notice @dev Requires the contract not to be frozen.
*/
modifier isNotFrozen() {
require(frozen == false, "Token contract is frozen!");
_;
}
}
| * @notice Checks if the sender is the freezer controller address./ | modifier onlyRescuerAddress() {
require(msg.sender == rescuerAddress, "Only the rescuer address can call this method.");
_;
}
| 5,508,831 | [
1,
4081,
309,
326,
5793,
353,
326,
4843,
24355,
2596,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
607,
71,
6211,
1887,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
400,
71,
6211,
1887,
16,
315,
3386,
326,
400,
71,
6211,
1758,
848,
745,
333,
707,
1199,
1769,
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
]
|
./full_match/137/0xc414f3bc6234d2BcFDC158a1f8666C7fbE3Ba562/sources/contracts/HopeChef.sol | Withdraw without caring about rewards. EMERGENCY ONLY. | function emergencyWithdraw(uint256 _pid) external lock checkHalving {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
uint256 _sentAmount = _amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[_pid];
if (address(_rewarder) != address(0)) {
_rewarder.onHopeReward(_pid, msg.sender, msg.sender, 0, 0);
}
if (reserveFund != address(0) && now < unfrozenDepositTime(_pid, msg.sender)) {
uint256 _earlyWithdrawFee = poolEarlyWithdrawFee[_pid];
if (_earlyWithdrawFee > 0) {
_earlyWithdrawFee = _amount.mul(_earlyWithdrawFee).div(10000);
_sentAmount = _sentAmount.sub(_earlyWithdrawFee);
pool.lpToken.safeTransfer(reserveFund, _earlyWithdrawFee);
emit WithdrawFee(msg.sender, _pid, _amount, _earlyWithdrawFee);
}
}
pool.lpToken.safeTransfer(address(msg.sender), _sentAmount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
| 4,748,941 | [
1,
1190,
9446,
2887,
5926,
310,
2973,
283,
6397,
18,
7141,
654,
16652,
16068,
20747,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
801,
24530,
1190,
9446,
12,
11890,
5034,
389,
6610,
13,
3903,
2176,
866,
44,
287,
6282,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
2254,
5034,
389,
8949,
273,
729,
18,
8949,
31,
203,
3639,
2254,
5034,
389,
7569,
6275,
273,
389,
8949,
31,
203,
3639,
729,
18,
8949,
273,
374,
31,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
374,
31,
203,
3639,
15908,
359,
297,
765,
389,
266,
20099,
273,
283,
20099,
63,
67,
6610,
15533,
203,
3639,
309,
261,
2867,
24899,
266,
20099,
13,
480,
1758,
12,
20,
3719,
288,
203,
5411,
389,
266,
20099,
18,
265,
44,
1306,
17631,
1060,
24899,
6610,
16,
1234,
18,
15330,
16,
1234,
18,
15330,
16,
374,
16,
374,
1769,
203,
3639,
289,
203,
3639,
309,
261,
455,
6527,
42,
1074,
480,
1758,
12,
20,
13,
597,
2037,
411,
640,
28138,
758,
1724,
950,
24899,
6610,
16,
1234,
18,
15330,
3719,
288,
203,
5411,
2254,
5034,
389,
2091,
715,
1190,
9446,
14667,
273,
2845,
41,
20279,
1190,
9446,
14667,
63,
67,
6610,
15533,
203,
5411,
309,
261,
67,
2091,
715,
1190,
9446,
14667,
405,
374,
13,
288,
203,
7734,
389,
2091,
715,
1190,
9446,
14667,
273,
389,
8949,
18,
16411,
24899,
2091,
715,
1190,
9446,
14667,
2934,
2892,
12,
23899,
1769,
203,
7734,
389,
7569,
6275,
273,
389,
7569,
6275,
18,
1717,
24899,
2091,
715,
1190,
9446,
14667,
1769,
2
]
|
./full_match/5/0xB197968854E2A9Ce3961d5BeF1b39c82233590D9/sources/contracts/thirdweb-wallet/AccountAdmin.sol | @notice Returns the account associated with a particular signer-accountId pair. | function getAccount(address _signer, bytes32 _accountId) external view returns (address) {
bytes32 pair = keccak256(abi.encode(_signer, _accountId));
return pairHashToAccount[pair];
}
| 1,883,209 | [
1,
1356,
326,
2236,
3627,
598,
279,
6826,
10363,
17,
25701,
3082,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
23393,
12,
2867,
389,
2977,
264,
16,
1731,
1578,
389,
25701,
13,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
1731,
1578,
3082,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
2977,
264,
16,
389,
25701,
10019,
203,
3639,
327,
3082,
2310,
774,
3032,
63,
6017,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-04-11
*/
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @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;
}
// File contracts/PLASMA.sol
pragma solidity ^0.8.0;
pragma solidity ^0.8.0;
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Pair {
function sync() external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
}
pragma solidity ^0.8.0;
contract MrFusion {
constructor() {}
}
contract Reactor {
using SafeMath for uint256;
IUniswapV2Router02 public immutable _uniswapV2Router;
PLASMA private _tokenContract;
constructor(PLASMA tokenContract, IUniswapV2Router02 uniswapV2Router) {
_tokenContract = tokenContract;
_uniswapV2Router = uniswapV2Router;
}
receive() external payable {}
function rebalance() external returns (uint256 rebal) {
swapEthForTokens(address(this).balance);
}
function swapEthForTokens(uint256 EthAmount) private {
address[] memory uniswapPairPath = new address[](2);
uniswapPairPath[0] = _uniswapV2Router.WETH();
uniswapPairPath[1] = address(_tokenContract);
_uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: EthAmount
}(0, uniswapPairPath, address(this), block.timestamp);
}
}
contract TimeCircuts {
using SafeMath for uint256;
IUniswapV2Router02 public immutable _uniswapV2Router;
PLASMA private _tokenContract;
constructor(PLASMA tokenContract, IUniswapV2Router02 uniswapV2Router) {
_tokenContract = tokenContract;
_uniswapV2Router = uniswapV2Router;
}
function swapTokens(address pairTokenAddress, uint256 tokenAmount)
external
{
uint256 initialPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this));
swapTokensForTokens(pairTokenAddress, tokenAmount);
uint256 newPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this)).sub(
initialPairTokenBalance
);
IERC20(pairTokenAddress).transfer(
address(_tokenContract),
newPairTokenBalance
);
}
function swapTokensForTokens(address pairTokenAddress, uint256 tokenAmount)
private
{
address[] memory path = new address[](2);
path[0] = address(_tokenContract);
path[1] = pairTokenAddress;
_tokenContract.approve(address(_uniswapV2Router), tokenAmount);
// make the swap
_uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of pair token
path,
address(this),
block.timestamp
);
}
}
contract PLASMA is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
IUniswapV2Router02 public immutable _uniswapV2Router;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
address public _anomalieAddress;
address public _mrFusion;
uint256 public _initialMrFusionLockAmount;
uint256 public _initialFluxAmount;
address public _uniswapETHPool;
address public _fluxCapacitor;
address public _orbs;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 6000000e18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 public _tFeeTotal;
uint256 public _tBurnTotal;
string private _name = "PLASMA";
string private _symbol = "PLASMA";
uint8 private _decimals = 18;
uint256 public _feeDecimals = 1;
uint256 public _taxFee;
uint256 public _lockFee;
uint256 public _maxTxAmount = 100000e18;
uint256 public _minTokensBeforeSwap = 1000e18;
uint256 public _minInterestForReward = 10e18;
uint256 private _autoSwapCallerFee = 200e18;
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled;
bool public tradingEnabled;
bool public clearenceCheckEnabled;
address private currentPairTokenAddress;
address private currentPoolAddress;
uint256 private _liquidityRemoveFee = 2;
uint256 private _fusionCallerFee = 5;
uint256 private _minTokenForfusion = 1000e18;
uint256 private _lastfusion;
uint256 private _fusionInterval = 1 hours;
uint256 private _fluxCapacitorFee = 10;
uint256 private _powerFee = 5;
event Loged(address indexed madScientist, uint256 amount);
event Unloged(address indexed madScientist, uint256 amount);
event FeeDecimalsUpdated(uint256 taxFeeDecimals);
event TaxFeeUpdated(uint256 taxFee);
event LockFeeUpdated(uint256 lockFee);
event MaxTxAmountUpdated(uint256 maxTxAmount);
event WhitelistUpdated(address indexed pairTokenAddress);
event TradingEnabled();
event ClearenceCheckEnabledUpdated(bool enabled);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
address indexed pairTokenAddress,
uint256 tokensSwapped,
uint256 pairTokenReceived,
uint256 tokensIntoLiqudity
);
event Rebalance(uint256 tokenBurnt);
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event AutoSwapCallerFeeUpdated(uint256 autoSwapCallerFee);
event MinInterestForRewardUpdated(uint256 minInterestForReward);
event LiquidityRemoveFeeUpdated(uint256 liquidityRemoveFee);
event fusionCallerFeeUpdated(uint256 rebalnaceCallerFee);
event MinTokenForfusionUpdated(uint256 minRebalanceAmount);
event fusionIntervalUpdated(uint256 rebalanceInterval);
event AnomaliesAddressUpdated(address anomalies);
event PowerFeeUpdated(uint256 powerFee);
event fluxCapacitorUpdated(address fluxCapacitor);
event fluxCapacitorFeeUpdated(uint256 fluxCapacitorFee);
event orbsUpdated(address orbs);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
Reactor public reactor;
TimeCircuts public timeCircuts;
constructor(
IUniswapV2Router02 uniswapV2Router,
uint256 initialMrFusionLockAmount
) {
_lastfusion = block.timestamp;
_uniswapV2Router = uniswapV2Router;
_mrFusion = address(new MrFusion());
_initialMrFusionLockAmount = initialMrFusionLockAmount;
reactor = new Reactor(this, uniswapV2Router);
timeCircuts = new TimeCircuts(this, uniswapV2Router);
currentPoolAddress = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
currentPairTokenAddress = uniswapV2Router.WETH();
_uniswapETHPool = currentPoolAddress;
updateSwapAndLiquifyEnabled(false);
_rOwned[_msgSender()] = reflectionFromToken(
_tTotal.sub(_initialMrFusionLockAmount),
false
);
_rOwned[_mrFusion] = reflectionFromToken(
_initialMrFusionLockAmount,
false
);
emit Transfer(
address(0),
_msgSender(),
_tTotal.sub(_initialMrFusionLockAmount)
);
emit Transfer(address(0), _mrFusion, _initialMrFusionLockAmount);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
"PLASMA: Excluded addresses cannot call this function"
);
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount)
public
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"PLASMA: Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(
account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,
"PLASMA: We can not exclude Uniswap router."
);
require(
account != address(this),
"PLASMA: We can not exclude contract self."
);
require(
account != _mrFusion,
"PLASMA: We can not exclude reweard wallet."
);
require(!_isExcluded[account], "PLASMA: 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], "PLASMA: Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "PLASMA: approve from the zero address");
require(spender != address(0), "PLASMA: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "PLASMA: transfer from the zero address");
require(
recipient != address(0),
"PLASMA: transfer to the zero address"
);
require(
amount > 0,
"PLASMA: Transfer amount must be greater than zero"
);
if (sender != owner() && recipient != owner() && !inSwapAndLiquify) {
require(
amount <= _maxTxAmount,
"PLASMA: Transfer amount exceeds the maxTxAmount."
);
if (
(_msgSender() == currentPoolAddress ||
_msgSender() == address(_uniswapV2Router)) &&
!tradingEnabled
) require(false, "PLASMA: trading is disabled.");
}
if (!inSwapAndLiquify) {
uint256 lockedBalanceForPool = balanceOf(address(this));
bool overMinTokenBalance =
lockedBalanceForPool >= _minTokensBeforeSwap;
if (
overMinTokenBalance &&
msg.sender != currentPoolAddress &&
swapAndLiquifyEnabled
) {
if (currentPairTokenAddress == _uniswapV2Router.WETH())
swapAndLiquifyForEth(lockedBalanceForPool);
else
swapAndLiquifyForTokens(
currentPairTokenAddress,
lockedBalanceForPool
);
}
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
receive() external payable {}
function swapAndLiquifyForEth(uint256 lockedBalanceForPool)
private
lockTheSwap
{
// split the contract balance except swapCallerFee into halves
uint256 lockedForSwap = lockedBalanceForPool.sub(_autoSwapCallerFee);
uint256 half = lockedForSwap.div(2);
uint256 otherHalf = lockedForSwap.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidityForEth(otherHalf, newBalance);
emit SwapAndLiquify(
_uniswapV2Router.WETH(),
half,
newBalance,
otherHalf
);
_transfer(address(this), tx.origin, _autoSwapCallerFee);
_sendRewardInterestToPool();
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _uniswapV2Router.WETH();
_approve(address(this), address(_uniswapV2Router), tokenAmount);
// make the swap
_uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidityForEth(uint256 tokenAmount, uint256 ethAmount)
private
{
// approve token transfer to cover all possible scenarios
_approve(address(this), address(_uniswapV2Router), tokenAmount);
// add the liquidity
_uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapAndLiquifyForTokens(
address pairTokenAddress,
uint256 lockedBalanceForPool
) private lockTheSwap {
// split the contract balance except swapCallerFee into halves
uint256 lockedForSwap = lockedBalanceForPool.sub(_autoSwapCallerFee);
uint256 half = lockedForSwap.div(2);
uint256 otherHalf = lockedForSwap.sub(half);
_transfer(address(this), address(timeCircuts), half);
uint256 initialPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this));
// swap tokens for pairToken
timeCircuts.swapTokens(pairTokenAddress, half);
uint256 newPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this)).sub(
initialPairTokenBalance
);
// add liquidity to uniswap
addLiquidityForTokens(pairTokenAddress, otherHalf, newPairTokenBalance);
emit SwapAndLiquify(
pairTokenAddress,
half,
newPairTokenBalance,
otherHalf
);
_transfer(address(this), tx.origin, _autoSwapCallerFee);
_sendRewardInterestToPool();
}
function addLiquidityForTokens(
address pairTokenAddress,
uint256 tokenAmount,
uint256 pairTokenAmount
) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(_uniswapV2Router), tokenAmount);
IERC20(pairTokenAddress).approve(
address(_uniswapV2Router),
pairTokenAmount
);
// add the liquidity
_uniswapV2Router.addLiquidity(
address(this),
pairTokenAddress,
tokenAmount,
pairTokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function fusion() public lockTheSwap {
if (clearenceCheckEnabled == true) {
require(
IERC1155(_orbs).balanceOf(msg.sender, 3) >= 1,
"PLASMA: one much be holding the PLASMA orb to yeild such power"
);
require(
block.timestamp > _lastfusion + _fusionInterval,
"PLASMA: Too Soon."
);
fusionPartTwo();
} else if (clearenceCheckEnabled == false) {
require(
balanceOf(_msgSender()) >= _minTokenForfusion,
"PLASMA: Access denied, need more PLASMA to fusion "
);
require(
block.timestamp > _lastfusion + _fusionInterval,
"PLASMA: Too Soon."
);
fusionPartTwo();
}
}
function fusionPartTwo() public lockTheSwap {
_lastfusion = block.timestamp;
uint256 amountToRemove =
IERC20(_uniswapETHPool)
.balanceOf(address(this))
.mul(_liquidityRemoveFee)
.div(100);
removeLiquidityETH(amountToRemove);
reactor.rebalance();
uint256 tNewTokenBalance = balanceOf(address(reactor));
uint256 tRewardForCaller =
tNewTokenBalance.mul(_fusionCallerFee).div(100);
uint256 tRemaining = tNewTokenBalance.sub(tRewardForCaller);
uint256 toAnomalie = tRemaining.mul(_powerFee).div(100);
addAnomalie(toAnomalie);
uint256 aftPower = tRemaining.sub(toAnomalie);
uint256 flux = aftPower.mul(_fluxCapacitorFee).div(100);
addFlux(flux);
uint256 tBurn = aftPower.sub(flux);
uint256 currentRate = _getRate();
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[_msgSender()] = _rOwned[_msgSender()].add(
tRewardForCaller.mul(currentRate)
);
_rOwned[address(reactor)] = 0;
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
_rTotal = _rTotal.sub(rBurn);
emit Transfer(address(reactor), address(_anomalieAddress), toAnomalie);
emit Transfer(address(reactor), _msgSender(), tRewardForCaller);
emit Transfer(address(reactor), address(0), tBurn);
emit Rebalance(tBurn);
}
function addFlux(uint256 flux) private {
uint256 currentRate = _getRate();
_rOwned[_fluxCapacitor] = _rOwned[_fluxCapacitor].add(
flux.mul(currentRate)
);
emit Transfer(address(reactor), _fluxCapacitor, flux);
}
function addAnomalie(uint256 toAnomalie) private {
uint256 currentRate = _getRate();
_rOwned[_anomalieAddress] = _rOwned[_anomalieAddress].add(
toAnomalie.mul(currentRate)
);
emit Transfer(address(reactor), _anomalieAddress, toAnomalie);
}
function removeLiquidityETH(uint256 lpAmount)
private
returns (uint256 ETHAmount)
{
IERC20(_uniswapETHPool).approve(address(_uniswapV2Router), lpAmount);
(ETHAmount) = _uniswapV2Router
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this),
lpAmount,
0,
0,
address(reactor),
block.timestamp
);
}
function _sendRewardInterestToPool() private {
uint256 tRewardInterest =
balanceOf(_mrFusion).sub(_initialMrFusionLockAmount);
if (tRewardInterest > _minInterestForReward) {
uint256 rRewardInterest =
reflectionFromToken(tRewardInterest, false);
_rOwned[currentPoolAddress] = _rOwned[currentPoolAddress].add(
rRewardInterest
);
_rOwned[_mrFusion] = _rOwned[_mrFusion].sub(rRewardInterest);
emit Transfer(_mrFusion, currentPoolAddress, tRewardInterest);
IUniswapV2Pair(currentPoolAddress).sync();
}
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_tOwned[recipient] = _tOwned[recipient].add(tAmount);
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_tOwned[recipient] = _tOwned[recipient].add(tAmount);
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLock) =
_getTValues(tAmount, _taxFee, _lockFee, _feeDecimals);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tLock, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLock);
}
function _getTValues(
uint256 tAmount,
uint256 taxFee,
uint256 lockFee,
uint256 feeDecimals
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(taxFee).div(10**(feeDecimals + 2));
uint256 tLockFee = tAmount.mul(lockFee).div(10**(feeDecimals + 2));
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLockFee);
return (tTransferAmount, tFee, tLockFee);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLock,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLock = tLock.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLock);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() public view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function calculateFee(
uint256 _amount,
uint256 _feeDeci,
uint256 _percentage
) public pure returns (uint256 amount) {
amount = _amount.mul(_percentage).div(10**(uint256(_feeDeci) + 2));
}
function _getCurrentSupply() public view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_rOwned[_excluded[i]] > rSupply ||
_tOwned[_excluded[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function getCurrentPoolAddress() public view returns (address) {
return currentPoolAddress;
}
function getCurrentPairTokenAddress() public view returns (address) {
return currentPairTokenAddress;
}
function getLiquidityRemoveFee() public view returns (uint256) {
return _liquidityRemoveFee;
}
function getfusionCallerFee() public view returns (uint256) {
return _fusionCallerFee;
}
function getMinTokenForfusion() public view returns (uint256) {
return _minTokenForfusion;
}
function getLastfusion() public view returns (uint256) {
return _lastfusion;
}
function getfusionInterval() public view returns (uint256) {
return _fusionInterval;
}
function getFluxCapacitorAddress() public view returns (address) {
return _fluxCapacitor;
}
function _setFeeDecimals(uint256 feeDecimals) external onlyOwner() {
require(
feeDecimals >= 0 && feeDecimals <= 2,
"PLASMA: fee decimals should be in 0 - 2"
);
_feeDecimals = feeDecimals;
emit FeeDecimalsUpdated(feeDecimals);
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(
taxFee >= 0 && taxFee <= 10 * 10**_feeDecimals,
"PLASMA: taxFee should be in 0 - 10"
);
_taxFee = taxFee;
emit TaxFeeUpdated(taxFee);
}
function _setLockFee(uint256 lockFee) external onlyOwner() {
require(
lockFee >= 0 && lockFee <= 10 * 10**_feeDecimals,
"PLASMA: lockFee should be in 0 - 10"
);
_lockFee = lockFee;
emit LockFeeUpdated(lockFee);
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(
maxTxAmount >= 50000e18,
"PLASMA: maxTxAmount should be greater than 50000e18"
);
_maxTxAmount = maxTxAmount;
emit MaxTxAmountUpdated(maxTxAmount);
}
function _setMinTokensBeforeSwap(uint256 minTokensBeforeSwap)
external
onlyOwner()
{
require(
minTokensBeforeSwap >= 1e18 && minTokensBeforeSwap <= 25000e18,
"PLASMA: minTokenBeforeSwap should be in 1e18 - 25000e18"
);
require(
minTokensBeforeSwap > _autoSwapCallerFee,
"PLASMA: minTokenBeforeSwap should be greater than autoSwapCallerFee"
);
_minTokensBeforeSwap = minTokensBeforeSwap;
emit MinTokensBeforeSwapUpdated(minTokensBeforeSwap);
}
function _setAutoSwapCallerFee(uint256 autoSwapCallerFee)
external
onlyOwner()
{
require(
autoSwapCallerFee >= 1e18,
"PLASMA: autoSwapCallerFee should be greater than 1e18"
);
_autoSwapCallerFee = autoSwapCallerFee;
emit AutoSwapCallerFeeUpdated(autoSwapCallerFee);
}
function _setMinInterestForReward(uint256 minInterestForReward)
external
onlyOwner()
{
_minInterestForReward = minInterestForReward;
emit MinInterestForRewardUpdated(minInterestForReward);
}
function _setLiquidityRemoveFee(uint256 liquidityRemoveFee)
external
onlyOwner()
{
require(
liquidityRemoveFee >= 1 && liquidityRemoveFee <= 10,
"PLASMA: liquidityRemoveFee should be in 1 - 10"
);
_liquidityRemoveFee = liquidityRemoveFee;
emit LiquidityRemoveFeeUpdated(liquidityRemoveFee);
}
function _setfusionCallerFee(uint256 fusionCallerFee) external onlyOwner() {
require(
fusionCallerFee >= 1 && fusionCallerFee <= 15,
"PLASMA: fusionCallerFee should be in 1 - 15"
);
_fusionCallerFee = fusionCallerFee;
emit fusionCallerFeeUpdated(fusionCallerFee);
}
function _setMinTokenForfusion(uint256 minTokenForfusion)
external
onlyOwner()
{
_minTokenForfusion = minTokenForfusion;
emit MinTokenForfusionUpdated(minTokenForfusion);
}
function _setfusionInterval(uint256 fusionInterval) external onlyOwner() {
_fusionInterval = fusionInterval;
emit fusionIntervalUpdated(fusionInterval);
}
function _setfluxCapacitorAddress(address fluxCapacitor)
external
onlyOwner()
{
_fluxCapacitor = fluxCapacitor;
emit fluxCapacitorUpdated(fluxCapacitor);
}
function _setOrbsAddress(address orbs) external onlyOwner() {
_orbs = orbs;
emit orbsUpdated(orbs);
}
function _setFluxCapacitorFee(uint256 fluxCapacitorFee)
external
onlyOwner()
{
_fluxCapacitorFee = fluxCapacitorFee;
emit fluxCapacitorFeeUpdated(fluxCapacitorFee);
}
function _setPowerFee(uint256 powerFee) external onlyOwner() {
_powerFee = powerFee;
emit PowerFeeUpdated(powerFee);
}
function _setAnomalies(address payable anomalieAddress)
external
onlyOwner()
{
_anomalieAddress = anomalieAddress;
emit AnomaliesAddressUpdated(anomalieAddress);
}
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function _updateWhitelist(address poolAddress, address pairTokenAddress)
public
onlyOwner()
{
require(poolAddress != address(0), "PLASMA: Pool address is zero.");
require(
pairTokenAddress != address(0),
"PLASMA: Pair token address is zero."
);
require(
pairTokenAddress != address(this),
"PLASMA: Pair token address self address."
);
require(
pairTokenAddress != currentPairTokenAddress,
"PLASMA: Pair token address is same as current one."
);
currentPoolAddress = poolAddress;
currentPairTokenAddress = pairTokenAddress;
emit WhitelistUpdated(pairTokenAddress);
}
function _enableTrading() external onlyOwner() {
tradingEnabled = true;
TradingEnabled();
}
function _enableClearenceCheck(bool _enabled) public onlyOwner {
clearenceCheckEnabled = true;
emit ClearenceCheckEnabledUpdated(_enabled);
}
}
// File contracts/Flux.sol
pragma solidity ^0.8.0;
// Adapted from SushiSwap's MasterChef contract
pragma solidity ^0.8.0;
// Adapted from SushiSwap's MasterChef contract
contract FluxCapacitor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 stakableToken; // Address of staking token contract.
uint256 allocPoint; // How many PLASMA to distribute per block.
uint256 lastRewardBlock;
uint256 accPlasmaPerShare; // Accumulated PLASMA per share, times 100. See below.
}
// Plasma Address
PLASMA public plasma;
// Amount of PLASMA allocated to pool per block
uint256 plasmaPerBlock;
// Bonus end block.
uint256 public bonusEndBlock;
// Bonus multiplier for the OGs
uint256 public constant BONUS_MULTIPLIER = 10;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocatuion points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// start block
uint256 public startBlock;
// Make sure this is not a duplicate pool
mapping(IERC20 => bool) public supportedToken;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
PLASMA _plasma,
uint256 _plasmaPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
plasma = _plasma;
plasmaPerBlock = _plasmaPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token or LP to the pool. Can only be called by the owner.
// DO NOT add the same LP or token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _stakableToken,
bool _withUpdate
) public onlyOwner {
// Each stakable token can only be added once.
require(!supportedToken[_stakableToken], "add: duplicate token");
supportedToken[_stakableToken] = true;
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
stakableToken: _stakableToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accPlasmaPerShare: 0
})
);
}
// Update the given pool's PLASMA allocation pointpercentage. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return
bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending PLASMA on frontend.
function pendingPLASMA(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPlasmaPerShare = pool.accPlasmaPerShare;
uint256 stakedSupply = pool.stakableToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && stakedSupply != 0) {
uint256 multiplier =
getMultiplier(pool.lastRewardBlock, block.number);
uint256 PLASMAReward =
multiplier.mul(plasmaPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
accPlasmaPerShare = accPlasmaPerShare.add(
PLASMAReward.mul(1e12).div(stakedSupply)
);
}
return
user.amount.mul(accPlasmaPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 stakedSupply = pool.stakableToken.balanceOf(address(this));
if (stakedSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 PLASMAReward =
multiplier.mul(plasmaPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
pool.accPlasmaPerShare = pool.accPlasmaPerShare.add(
PLASMAReward.mul(1e12).div(stakedSupply)
);
pool.lastRewardBlock = block.number;
}
// Claim all if no amount specified, or Deposit new LP/SAS.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
// this is claim
if (user.amount > 0) {
uint256 pending =
user.amount.mul(pool.accPlasmaPerShare).div(1e12).sub(
user.rewardDebt
);
if (pending > 0) {
safePLASMAtransfer(msg.sender, pending);
}
} /// Deposit
if (_amount > 0) {
uint256 beforeAmount = pool.stakableToken.balanceOf(address(this));
pool.stakableToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
uint256 _addAmt =
pool.stakableToken.balanceOf(address(this)).sub(beforeAmount);
user.amount = user.amount.add(_addAmt);
}
user.rewardDebt = user.amount.mul(pool.accPlasmaPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw or Claim Plasma/LP/SaS tokens from FluxCampacitor.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending =
user.amount.mul(pool.accPlasmaPerShare).div(1e12).sub(
user.rewardDebt
); // Claim first all that is pending
if (pending > 0) {
safePLASMAtransfer(msg.sender, pending);
}
if (_amount > 0) {
// Remove stake
user.amount = user.amount.sub(_amount);
pool.stakableToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accPlasmaPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.stakableToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe PLASMA transfer function, just in case if rounding error causes pool to not have enough PLASMA.
function safePLASMAtransfer(address _to, uint256 _amount) internal {
uint256 PLASMABal = plasma.balanceOf(address(this));
if (_amount > PLASMABal) {
plasma.transfer(_to, PLASMABal);
} else {
plasma.transfer(_to, _amount);
}
}
function updatePlasmaPerBlock(uint256 _plasmaPerBlock)
external
onlyOwner
returns (bool)
{
plasmaPerBlock = _plasmaPerBlock;
return true;
}
function getPlasmaBalance() external view returns (uint256) {
uint256 plasmaBalance = plasma.balanceOf(address(this));
return plasmaBalance;
}
function getStakedLiq(uint256 _pid, address)
external
view
returns (uint256)
{
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 stakedLiq = user.amount;
return stakedLiq;
}
} | Accumulated PLASMA per share, times 100. See below.
| uint256 accPlasmaPerShare; | 15,140,063 | [
1,
8973,
5283,
690,
25564,
55,
5535,
1534,
7433,
16,
4124,
2130,
18,
2164,
5712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
4078,
1749,
345,
2540,
2173,
9535,
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
]
|
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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;
}
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(address pair)
internal
view
returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
/**
* @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;
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
}
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Require
* @author dYdX
*
* Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
*/
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad
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 Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad
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.
*/
contract IOracle {
function setup() public;
function capture() public returns (Decimal.D256 memory, bool);
function pair() external view returns (address);
}
/*
Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad
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.
*/
contract IUSDC {
function isBlacklisted(address _account) external view returns (bool);
}
/*
Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad
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.
*/
library Constants {
/* Chain */
uint256 private constant CHAIN_ID = 1; // Mainnet
/* Bootstrapping */
uint256 private constant BOOTSTRAPPING_PERIOD = 150; // 150 epochs
uint256 private constant BOOTSTRAPPING_PRICE = 154e16; // 1.54 USDC (targeting 4.5% inflation)
/* Oracle */
address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
uint256 private constant ORACLE_RESERVE_MINIMUM = 1e10; // 10,000 USDC
/* Bonding */
uint256 private constant INITIAL_STAKE_MULTIPLE = 1e6; // 100 DSD -> 100M DSDS
/* Epoch */
struct EpochStrategy {
uint256 offset;
uint256 start;
uint256 period;
}
uint256 private constant EPOCH_OFFSET = 0;
uint256 private constant EPOCH_START = 1606348800;
uint256 private constant EPOCH_PERIOD = 7200;
/* Governance */
uint256 private constant GOVERNANCE_PERIOD = 36;
uint256 private constant GOVERNANCE_QUORUM = 20e16; // 20%
uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5%
uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66%
uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs
/* DAO */
uint256 private constant ADVANCE_INCENTIVE_PREMIUM = 125e16; // pay out 25% more than tx fee value
uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 36; // 36 epochs fluid
/* Pool */
uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 12; // 12 epochs fluid
/* Market */
uint256 private constant COUPON_EXPIRATION = 360;
uint256 private constant DEBT_RATIO_CAP = 35e16; // 35%
uint256 private constant INITIAL_COUPON_REDEMPTION_PENALTY = 50e16; // 50%
uint256 private constant COUPON_REDEMPTION_PENALTY_DECAY = 3600; // 1 hour
/* Regulator */
uint256 private constant SUPPLY_CHANGE_LIMIT = 2e16; // 2%
uint256 private constant SUPPLY_CHANGE_DIVISOR = 25e18; // 25 > Max expansion at 1.5
uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 3e16; // 3%
uint256 private constant COUPON_SUPPLY_CHANGE_DIVISOR = 1666e16; // 16.66 > Max expansion at ~1.5
uint256 private constant NEGATIVE_SUPPLY_CHANGE_DIVISOR = 5e18; // 5 > Max negative expansion at 0.9
uint256 private constant ORACLE_POOL_RATIO = 40; // 40%
uint256 private constant TREASURY_RATIO = 3; // 3%
/* Deployed */
address private constant DAO_ADDRESS = address(0x6Bf977ED1A09214E6209F4EA5f525261f1A2690a);
address private constant DOLLAR_ADDRESS = address(0xBD2F0Cd039E0BFcf88901C98c0bFAc5ab27566e3);
address private constant PAIR_ADDRESS = address(0x26d8151e631608570F3c28bec769C3AfEE0d73a3); // SushiSwap pair
address private constant TREASURY_ADDRESS = address(0xC7DA8087b8BA11f0892f1B0BFacfD44C116B303e);
/**
* Getters
*/
function getUsdcAddress() internal pure returns (address) {
return USDC;
}
function getOracleReserveMinimum() internal pure returns (uint256) {
return ORACLE_RESERVE_MINIMUM;
}
function getEpochStrategy() internal pure returns (EpochStrategy memory) {
return EpochStrategy({ offset: EPOCH_OFFSET, start: EPOCH_START, period: EPOCH_PERIOD });
}
function getInitialStakeMultiple() internal pure returns (uint256) {
return INITIAL_STAKE_MULTIPLE;
}
function getBootstrappingPeriod() internal pure returns (uint256) {
return BOOTSTRAPPING_PERIOD;
}
function getBootstrappingPrice() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: BOOTSTRAPPING_PRICE });
}
function getGovernancePeriod() internal pure returns (uint256) {
return GOVERNANCE_PERIOD;
}
function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: GOVERNANCE_QUORUM });
}
function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: GOVERNANCE_PROPOSAL_THRESHOLD });
}
function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: GOVERNANCE_SUPER_MAJORITY });
}
function getGovernanceEmergencyDelay() internal pure returns (uint256) {
return GOVERNANCE_EMERGENCY_DELAY;
}
function getAdvanceIncentivePremium() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: ADVANCE_INCENTIVE_PREMIUM });
}
function getDAOExitLockupEpochs() internal pure returns (uint256) {
return DAO_EXIT_LOCKUP_EPOCHS;
}
function getPoolExitLockupEpochs() internal pure returns (uint256) {
return POOL_EXIT_LOCKUP_EPOCHS;
}
function getCouponExpiration() internal pure returns (uint256) {
return COUPON_EXPIRATION;
}
function getDebtRatioCap() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: DEBT_RATIO_CAP });
}
function getInitialCouponRedemptionPenalty() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: INITIAL_COUPON_REDEMPTION_PENALTY });
}
function getCouponRedemptionPenaltyDecay() internal pure returns (uint256) {
return COUPON_REDEMPTION_PENALTY_DECAY;
}
function getSupplyChangeLimit() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: SUPPLY_CHANGE_LIMIT });
}
function getSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: SUPPLY_CHANGE_DIVISOR });
}
function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_LIMIT });
}
function getCouponSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_DIVISOR });
}
function getNegativeSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({ value: NEGATIVE_SUPPLY_CHANGE_DIVISOR });
}
function getOraclePoolRatio() internal pure returns (uint256) {
return ORACLE_POOL_RATIO;
}
function getTreasuryRatio() internal pure returns (uint256) {
return TREASURY_RATIO;
}
function getChainId() internal pure returns (uint256) {
return CHAIN_ID;
}
function getDaoAddress() internal pure returns (address) {
return DAO_ADDRESS;
}
function getDollarAddress() internal pure returns (address) {
return DOLLAR_ADDRESS;
}
function getPairAddress() internal pure returns (address) {
return PAIR_ADDRESS;
}
function getTreasuryAddress() internal pure returns (address) {
return TREASURY_ADDRESS;
}
}
/*
Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad
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.
*/
contract Oracle is IOracle {
using Decimal for Decimal.D256;
bytes32 private constant FILE = "Oracle";
address private constant SUSHISWAP_FACTORY = address(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac); // Sushi Factory Address
bool internal _initialized;
IUniswapV2Pair internal _pair;
uint256 internal _index;
uint256 internal _cumulative;
uint32 internal _timestamp;
uint256 internal _reserve;
function setup() public onlyDao {
_pair = IUniswapV2Pair(IUniswapV2Factory(SUSHISWAP_FACTORY).getPair(Constants.getDollarAddress(), usdc()));
(address token0, address token1) = (_pair.token0(), _pair.token1());
_index = Constants.getDollarAddress() == token0 ? 0 : 1;
Require.that(_index == 0 || Constants.getDollarAddress() == token1, FILE, "DSD not found");
}
/**
* Trades/Liquidity: (1) Initializes reserve and blockTimestampLast (can calculate a price)
* (2) Has non-zero cumulative prices
*
* Steps: (1) Captures a reference blockTimestampLast
* (2) First reported value
*/
function capture() public onlyDao returns (Decimal.D256 memory, bool) {
if (_initialized) {
return updateOracle();
} else {
initializeOracle();
return (Decimal.one(), false);
}
}
function initializeOracle() private {
IUniswapV2Pair pair = _pair;
uint256 priceCumulative = _index == 0 ? pair.price0CumulativeLast() : pair.price1CumulativeLast();
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = pair.getReserves();
if (reserve0 != 0 && reserve1 != 0 && blockTimestampLast != 0) {
_cumulative = priceCumulative;
_timestamp = blockTimestampLast;
_initialized = true;
_reserve = _index == 0 ? reserve1 : reserve0; // get counter's reserve
}
}
function updateOracle() private returns (Decimal.D256 memory, bool) {
Decimal.D256 memory price = updatePrice();
uint256 lastReserve = updateReserve();
bool isBlacklisted = IUSDC(usdc()).isBlacklisted(address(_pair));
bool valid = true;
if (lastReserve < Constants.getOracleReserveMinimum()) {
valid = false;
}
if (_reserve < Constants.getOracleReserveMinimum()) {
valid = false;
}
if (isBlacklisted) {
valid = false;
}
return (price, valid);
}
function updatePrice() private returns (Decimal.D256 memory) {
(uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_pair));
uint32 timeElapsed = blockTimestamp - _timestamp; // overflow is desired
uint256 priceCumulative = _index == 0 ? price0Cumulative : price1Cumulative;
Decimal.D256 memory price = Decimal.ratio((priceCumulative - _cumulative) / timeElapsed, 2**112);
_timestamp = blockTimestamp;
_cumulative = priceCumulative;
return price.mul(1e12);
}
function updateReserve() private returns (uint256) {
uint256 lastReserve = _reserve;
(uint112 reserve0, uint112 reserve1, ) = _pair.getReserves();
_reserve = _index == 0 ? reserve1 : reserve0; // get counter's reserve
return lastReserve;
}
function usdc() internal view returns (address) {
return Constants.getUsdcAddress();
}
function pair() external view returns (address) {
return address(_pair);
}
function reserve() external view returns (uint256) {
return _reserve;
}
modifier onlyDao() {
Require.that(msg.sender == Constants.getDaoAddress(), FILE, "Not DAO");
_;
}
} | overflow is desired
| uint32 timeElapsed = blockTimestamp - _timestamp; | 547,983 | [
1,
11512,
353,
6049,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
1578,
813,
28827,
273,
1203,
4921,
300,
389,
5508,
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
]
|
./full_match/137/0x1EE74Ae391C6cA3395Af47d57a36aFC42A507F9F/sources/project_/FanPass.sol | Check max mint limit
| require(tokenData.currentTokenId < tokenData.maxMintLimit, "Exceeded maximum mint limit"); | 4,698,015 | [
1,
1564,
943,
312,
474,
1800,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
2316,
751,
18,
2972,
1345,
548,
411,
1147,
751,
18,
1896,
49,
474,
3039,
16,
315,
10069,
4207,
312,
474,
1800,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.17;
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;
}
}
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
}
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;
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
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"
);
(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");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
contract LPTokenWrapper is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public BSKTETHLPToken = IERC20(0x1d470e0e3DFfbbA05E4F56541416a69574675889); // Uniswap V2 - Approve and Transfer BSKT-ETH-LP Token for stake
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) nonReentrant public {
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
BSKTETHLPToken.safeTransferFrom(_msgSender(), address(this), amount); // must required approved token
}
function withdraw(uint256 amount) nonReentrant public {
_totalSupply = _totalSupply.sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].sub(amount);
BSKTETHLPToken.safeTransfer(_msgSender(), amount);
}
}
contract BsktEthLPPool is LPTokenWrapper {
IERC20 public BSKTREWARD = IERC20(0xC03841B5135600312707d39Eb2aF0D2aD5d51A91); // Basket token address, distribute token as reward
uint256 public constant duration = 100 days; //-----| Pool Duration |-----
uint256 public starttime = 0; //-----| Pool will start once notify the reward |-----
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
bool firstNotify;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
mapping(address => bool) public minimumBsktStakingEntry;
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event Rewarded(address indexed from, address indexed to, uint256 value);
modifier checkStart() {
require(
block.timestamp >= starttime,
"Error:Pool not started yet."
);
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
// Utility function to calculate
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
// Reward rate
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
// Check earned reward till now
function earned(address account) public view returns (uint256) {
return balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// Stake UNI-V2-LP ( ETH-BSKT Pair ) token
function stake(uint256 amount) public updateReward(_msgSender()) checkStart {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(_msgSender(), amount);
}
// withdraw UNI-V2-LP ( ETH-BSKT Pair ) token
function withdraw(uint256 amount)
public
updateReward(_msgSender())
{
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(_msgSender(), amount);
}
// Withdraw staked lp token and earned reward immediately
function exit() external {
withdraw(balanceOf(_msgSender()));
getReward();
}
// Withdraw earned reward
function getReward() public nonReentrant updateReward(_msgSender()){
uint256 reward = earned(_msgSender());
if (reward > 0) {
rewards[_msgSender()] = 0;
BSKTREWARD.safeTransfer(_msgSender(), reward);
emit Rewarded(address(this), _msgSender(), reward);
}
}
// Notify reward set for duration
function notifyRewardRate(uint256 _reward) public updateReward(address(0)) onlyOwner{
require(!firstNotify, "Error : Notify rewards allowed once only");
rewardRate = _reward.div(duration);
lastUpdateTime = block.timestamp;
starttime = block.timestamp;
periodFinish = block.timestamp.add(duration);
firstNotify = true;
}
} | Basket token address, distribute token as reward
| IERC20 public BSKTREWARD = IERC20(0xC03841B5135600312707d39Eb2aF0D2aD5d51A91); | 11,925,327 | [
1,
11324,
1147,
1758,
16,
25722,
1147,
487,
19890,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
467,
654,
39,
3462,
1071,
605,
11129,
56,
862,
21343,
273,
467,
654,
39,
3462,
12,
20,
14626,
4630,
5193,
21,
38,
25,
3437,
4313,
25425,
2138,
7301,
27,
72,
5520,
41,
70,
22,
69,
42,
20,
40,
22,
69,
40,
25,
72,
10593,
37,
12416,
1769,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC721A.sol";
contract NASAOG is ERC721A, AccessControl, ReentrancyGuard, Ownable {
using Strings for uint256;
using SafeERC20 for IERC20;
/* STORAGE BEGINS */
// Pause Variables
bool public WLPaused; // solhint-disable-line
bool public EthMintPaused; // solhint-disable-line
uint256 public currentMinted;
uint256 public mintableSupply;
uint256 public ethMintPrice;
uint256 public currMerkleIndex;
// mapping from WL index -> merkleRoot;
mapping(uint256 => bytes32) private merkleRoots;
// mapping from WL index -> address -> number claimed
mapping(uint256 => mapping(address => uint256)) private claimedMapping;
string private _tokenURI;
bytes32 public WL_ADMIN = keccak256("WHITELIST_ADMIN"); // solhint-disable-line
/* STORAGE ENDS */
constructor() ERC721A("NASA OG", "NASAOG") {
WLPaused = true;
EthMintPaused = true;
mintableSupply = 1000;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(WL_ADMIN, msg.sender);
}
/**
* @dev returns the supportsInterfaceIds for `ERC721` and `AccessControl`
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721A, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/* WITHDRAWAL FUNCTIONS */
/**
* @dev Allows to withdraw the Ether in contract
* @param _amount - the amount being withdrawn
*/
function withdrawEth(uint256 _amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
nonReentrant
{
if (_amount > address(this).balance) {
revert NotEnoughBalance(_amount, address(this).balance);
}
payable(msg.sender).transfer(_amount);
}
/* MERKLE AIRDROP FUNCTIONS */
/**
* @dev public view function to get the merkleRoot at a current merkle index
* @param rootIndex - the index in the series of merkle trees that is being returned
* @return the merkle root at the given `rootIndex`
*/
function getMerkleRoot(uint256 rootIndex) public view returns (bytes32) {
return merkleRoots[rootIndex];
}
/**
* @dev Sets the next merkle Root and invalidates the previous root
* @param merkleRoot - The new merkleRoot
*/
function setNextMerkleRoot(bytes32 merkleRoot) external adminOrWL {
if (merkleRoot == 0) {
revert InvalidMerkleRoot();
}
// This will invalidate the previous merkle from being claimed
currMerkleIndex += 1;
merkleRoots[currMerkleIndex] = merkleRoot;
WLPaused = false;
}
/**
* @dev constructs the intended leaft to validate
*/
function _leaf(address account, uint256 redeemableAmount)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account, redeemableAmount));
}
/**
* @dev verifies the leaf and proof against the current valid merkleIndex
*/
function _verifyMerkle(bytes32 leaf, bytes32[] memory proof)
internal
view
returns (bool)
{
return MerkleProof.verify(proof, merkleRoots[currMerkleIndex], leaf);
}
/* MINTING FUNCTIONS */
/**
* @dev mints with merkleRoot whitelisting
*/
function mintWithMerkle(
uint256 redeemableAmount,
uint256 redeemAmount,
bytes32[] calldata proof
) external whenWLActive nonReentrant {
address redeemer = msg.sender;
if (!_verifyMerkle(_leaf(redeemer, redeemableAmount), proof)) {
revert InvalidRedeemer();
}
uint256 claimedSoFar = claimedMapping[currMerkleIndex][redeemer];
// if the claimedAmountSoFar + the amount intended to redeem is larger than amount available, throw
// if redeem amount + current minted > total supply, throw
if (
(mintableSupply != 0 &&
currentMinted + redeemAmount > mintableSupply) ||
(claimedSoFar + redeemAmount > redeemableAmount)
) {
revert NotEnoughRedeemsAvailable();
}
claimedMapping[currMerkleIndex][redeemer] += redeemAmount;
_mintNASAOG(redeemer, redeemAmount);
}
/**
* @dev mints an NFT payable in Eth
*/
function mintWithEth(uint256 redeemAmount)
external
payable
whenEthMintActive
nonReentrant
{
address to = msg.sender;
if (msg.value != ethMintPrice * redeemAmount) {
revert InsufficentEth();
}
// This short circuit check will save gas on _mintNASAOG
if (
mintableSupply != 0 && currentMinted + redeemAmount > mintableSupply
) {
revert SupplyUnavailable();
}
_mintNASAOG(to, redeemAmount);
}
/**
* @dev internal function for minting NASA OG
*/
function _mintNASAOG(address to, uint256 amount) internal {
currentMinted += amount;
_safeMint(to, amount);
}
/* VIEW FUNCTIONS */
/**
* @dev returns the tokenURI if exists
*/
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
if (_exists(tokenId)) {
return _tokenURI;
}
return "";
}
/**
* @dev returns the mintedCount of a minter against a merkleIndex
*/
function getMintedAmounts(uint256 merkleIndex, address minter)
public
view
returns (uint256)
{
return claimedMapping[merkleIndex][minter];
}
/* ADMIN FUNCTIONS */
/**
* @dev Override parameters
*/
function adminOverride(uint256 _mintableSupply, string memory _newTokenURI)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
if (_mintableSupply != 0 && _mintableSupply < currentMinted) {
revert InvalidmintableSupplyAdmin();
}
mintableSupply = _mintableSupply;
_tokenURI = _newTokenURI;
}
/**
* @dev Override parameters
*/
function adminOverridePrices(uint256 _ethMintPrice)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
ethMintPrice = _ethMintPrice;
}
/**
* @dev toggle pause for merkle
*/
function toggleWLPause() external adminOrWL {
if (WLPaused) {
emit WLActiveEvent();
} else {
emit WLPausedEvent();
}
WLPaused = !WLPaused;
}
/**
* @dev toggle pause for eth mint
*/
function toggleEthMintPause() external onlyRole(DEFAULT_ADMIN_ROLE) {
if (EthMintPaused) {
emit EthMintActiveEvent();
} else {
emit EthMintPausedEvent();
}
EthMintPaused = !EthMintPaused;
}
/**
* @dev modifier for WL
*/
modifier whenWLActive() {
if (WLPaused) {
revert WLPausedError();
}
_;
}
/**
* @dev modifier for eth mint
*/
modifier whenEthMintActive() {
if (EthMintPaused) {
revert EthMintPausedError();
}
_;
}
/**
* @dev Check if there is DEFAULT_ADMIN_ROLE or WL_ADMIN role, otherwise revert
*/
modifier adminOrWL() {
if (
!(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) ||
hasRole(WL_ADMIN, msg.sender))
) {
revert InvalidRole();
}
_;
}
error WLPausedError();
error EthMintPausedError();
error SupplyUnavailable();
error InsufficentEth();
error InvalidMerkleRoot();
error InvalidRedeemer();
error NotEnoughRedeemsAvailable();
error InvalidmintableSupplyAdmin();
error InvalidRole();
error NotEnoughBalance(uint256 amount, uint256 balance);
/* EVENTS BEGIN */
event WLPausedEvent();
event WLActiveEvent();
event EthMintPausedEvent();
event EthMintActiveEvent();
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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 override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 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 "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// 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;
/**
* @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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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);
} | This will invalidate the previous merkle from being claimed | currMerkleIndex += 1;
| 244,567 | [
1,
2503,
903,
11587,
326,
2416,
30235,
628,
3832,
7516,
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,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
4306,
8478,
15609,
1016,
1011,
404,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Fundraiser donations
/// @author kwight
/// @notice This contract allows register charities to receive donations for campaigns.
contract Fundraisers is Ownable {
mapping(address => Charity) private charityRegistry;
address[] private charities;
Program[] private programs;
Donation[] private donations;
enum ProgramStatus {
Active,
Cancelled,
Complete
}
struct Charity {
string name;
uint256 index;
}
struct Program {
string title;
ProgramStatus status;
address charity;
}
struct Donation {
address doner;
uint256 programId;
uint256 amount;
}
/// @notice Emit an event when a charity is registered.
/// @param charityAddress Address of the registered charity.
/// @param name Name of the charity.
event CharityRegistered(address charityAddress, string name);
/// @notice Emit an event when a charity is removed by the owner.
/// @param charityAddress Address of the removed charity.
event CharityRemoved(address charityAddress);
/// @notice Emit an event when a charity registers a program.
/// @param programId Index in the programs array.
/// @param charityAddress Address of the charity doing the registering.
event ProgramRegistered(uint256 programId, address charityAddress);
/// @notice Emit an event when a charity cancels a program.
/// @param programId Index in the programs array.
/// @param charityAddress Address of the charity doing the cancelling.
event ProgramCancelled(uint256 programId, address charityAddress);
/// @notice Emit an event when a charity marks a program as completed.
/// @param programId Index in the programs array.
/// @param charityAddress Address of the charity marking the completion.
event ProgramCompleted(uint256 programId, address charityAddress);
/// @notice Emit an event when a donation is received.
/// @param amount Amount of the donation (in wei).
/// @param charityAddress Address of the charity receiving the funds.
/// @param programId Index in the programs array.
/// @param doner Address of the doner.
event DonationReceived(
uint256 amount,
address charityAddress,
uint256 programId,
address doner
);
modifier isOwnerOrCharity(address charityAddress) {
require(
msg.sender == owner() || msg.sender == charityAddress,
"unauthorized"
);
_;
}
modifier onlyCharity() {
require(isRegisteredCharity(msg.sender) == true, "unauthorized");
_;
}
/// @notice Verify a given address is a registered charity.
/// @param charityAddress Address being verified.
/// @return True if registered, false otherwise.
function isRegisteredCharity(address charityAddress)
public
view
returns (bool)
{
if (charities.length == 0) return false;
return (charities[charityRegistry[charityAddress].index] ==
charityAddress);
}
/// @notice Register a charity.
/// @param charityAddress Address of the charity to be registered.
/// @param name Name of the charity.
function registerCharity(address charityAddress, string memory name)
public
onlyOwner
{
require(
isRegisteredCharity(charityAddress) == false,
"charity already exists"
);
charities.push(charityAddress);
charityRegistry[charityAddress].name = name;
charityRegistry[charityAddress].index = charities.length - 1;
emit CharityRegistered(charityAddress, name);
}
/// @notice Remove a charity.
/// @param charityAddress Address of the charity to be removed.
function removeCharity(address charityAddress)
public
isOwnerOrCharity(charityAddress)
{
require(
isRegisteredCharity(charityAddress) == true,
"charity does not exist"
);
uint256 toRemove = charityRegistry[charityAddress].index;
address toMove = charities[charities.length - 1];
charityRegistry[toMove].index = toRemove;
charities[toRemove] = toMove;
charities.pop();
emit CharityRemoved(charityAddress);
}
/// @notice Get stored data for the given charity.
/// @param charityAddress Address of the charity requested.
/// @return Charity struct instance.
function getCharity(address charityAddress)
public
view
returns (Charity memory)
{
require(
isRegisteredCharity(charityAddress) == true,
"charity does not exist"
);
return charityRegistry[charityAddress];
}
/// @notice Get data for all registered charities.
/// @return Array of Charity struct instances.
function getCharities() public view returns (address[] memory) {
return charities;
}
/// @notice Get data for all registered programs.
/// @return Array of Program struct instances.
function getPrograms() public view returns (Program[] memory) {
return programs;
}
/// @notice Register a program.
/// @param title The name of the program.
function registerProgram(string memory title) public onlyCharity {
programs.push(
Program({
title: title,
status: ProgramStatus.Active,
charity: msg.sender
})
);
emit ProgramRegistered(programs.length - 1, msg.sender);
}
/// @notice Cancel an active program.
/// @param programId Index of the program to be cancelled.
function cancelProgram(uint256 programId) public onlyCharity {
require(programs.length > programId, "program does not exist");
require(programs[programId].charity == msg.sender, "unauthorized");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
programs[programId].status = ProgramStatus.Cancelled;
emit ProgramCancelled(programId, msg.sender);
}
/// @notice Mark an active program as complete.
/// @param programId Index of the program to be marked complete.
function completeProgram(uint256 programId) public onlyCharity {
require(programs.length > programId, "program does not exist");
require(programs[programId].charity == msg.sender, "unauthorized");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
programs[programId].status = ProgramStatus.Complete;
emit ProgramCompleted(programId, msg.sender);
}
/// @notice Donate ether to a charity's program.
/// @param programId Index of the program "receiving" the donation.
function donate(uint256 programId) public payable {
require(programs.length > programId, "program does not exist");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
Program memory receivingProgram = programs[programId];
donations.push(
Donation({
doner: msg.sender,
programId: programId,
amount: msg.value
})
);
(bool sent, ) = receivingProgram.charity.call{value: msg.value}("");
require(sent, "ether not sent to charity");
emit DonationReceived(
msg.value,
receivingProgram.charity,
programId,
msg.sender
);
}
/// @notice Get data for all donations.
/// @return Array of Donation struct instances.
function getDonations() public view returns (Donation[] memory) {
return donations;
}
}
| @title Fundraiser donations @author kwight @notice This contract allows register charities to receive donations for campaigns. | contract Fundraisers is Ownable {
mapping(address => Charity) private charityRegistry;
address[] private charities;
Program[] private programs;
Donation[] private donations;
pragma solidity 0.8.9;
enum ProgramStatus {
Active,
Cancelled,
Complete
}
struct Charity {
string name;
uint256 index;
}
struct Program {
string title;
ProgramStatus status;
address charity;
}
struct Donation {
address doner;
uint256 programId;
uint256 amount;
}
uint256 amount,
address charityAddress,
uint256 programId,
address doner
);
event CharityRegistered(address charityAddress, string name);
event CharityRemoved(address charityAddress);
event ProgramRegistered(uint256 programId, address charityAddress);
event ProgramCancelled(uint256 programId, address charityAddress);
event ProgramCompleted(uint256 programId, address charityAddress);
event DonationReceived(
modifier isOwnerOrCharity(address charityAddress) {
require(
msg.sender == owner() || msg.sender == charityAddress,
"unauthorized"
);
_;
}
modifier onlyCharity() {
require(isRegisteredCharity(msg.sender) == true, "unauthorized");
_;
}
function isRegisteredCharity(address charityAddress)
public
view
returns (bool)
{
if (charities.length == 0) return false;
return (charities[charityRegistry[charityAddress].index] ==
charityAddress);
}
function registerCharity(address charityAddress, string memory name)
public
onlyOwner
{
require(
isRegisteredCharity(charityAddress) == false,
"charity already exists"
);
charities.push(charityAddress);
charityRegistry[charityAddress].name = name;
charityRegistry[charityAddress].index = charities.length - 1;
emit CharityRegistered(charityAddress, name);
}
function removeCharity(address charityAddress)
public
isOwnerOrCharity(charityAddress)
{
require(
isRegisteredCharity(charityAddress) == true,
"charity does not exist"
);
uint256 toRemove = charityRegistry[charityAddress].index;
address toMove = charities[charities.length - 1];
charityRegistry[toMove].index = toRemove;
charities[toRemove] = toMove;
charities.pop();
emit CharityRemoved(charityAddress);
}
function getCharity(address charityAddress)
public
view
returns (Charity memory)
{
require(
isRegisteredCharity(charityAddress) == true,
"charity does not exist"
);
return charityRegistry[charityAddress];
}
function getCharities() public view returns (address[] memory) {
return charities;
}
function getPrograms() public view returns (Program[] memory) {
return programs;
}
function registerProgram(string memory title) public onlyCharity {
programs.push(
Program({
title: title,
status: ProgramStatus.Active,
charity: msg.sender
})
);
emit ProgramRegistered(programs.length - 1, msg.sender);
}
function registerProgram(string memory title) public onlyCharity {
programs.push(
Program({
title: title,
status: ProgramStatus.Active,
charity: msg.sender
})
);
emit ProgramRegistered(programs.length - 1, msg.sender);
}
function cancelProgram(uint256 programId) public onlyCharity {
require(programs.length > programId, "program does not exist");
require(programs[programId].charity == msg.sender, "unauthorized");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
programs[programId].status = ProgramStatus.Cancelled;
emit ProgramCancelled(programId, msg.sender);
}
function completeProgram(uint256 programId) public onlyCharity {
require(programs.length > programId, "program does not exist");
require(programs[programId].charity == msg.sender, "unauthorized");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
programs[programId].status = ProgramStatus.Complete;
emit ProgramCompleted(programId, msg.sender);
}
function donate(uint256 programId) public payable {
require(programs.length > programId, "program does not exist");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
Program memory receivingProgram = programs[programId];
donations.push(
Donation({
doner: msg.sender,
programId: programId,
amount: msg.value
})
);
require(sent, "ether not sent to charity");
emit DonationReceived(
msg.value,
receivingProgram.charity,
programId,
msg.sender
);
}
function donate(uint256 programId) public payable {
require(programs.length > programId, "program does not exist");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
Program memory receivingProgram = programs[programId];
donations.push(
Donation({
doner: msg.sender,
programId: programId,
amount: msg.value
})
);
require(sent, "ether not sent to charity");
emit DonationReceived(
msg.value,
receivingProgram.charity,
programId,
msg.sender
);
}
(bool sent, ) = receivingProgram.charity.call{value: msg.value}("");
function getDonations() public view returns (Donation[] memory) {
return donations;
}
}
| 7,269,328 | [
1,
42,
1074,
354,
15914,
2727,
1012,
225,
5323,
750,
225,
1220,
6835,
5360,
1744,
1149,
1961,
358,
6798,
2727,
1012,
364,
8965,
87,
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,
478,
1074,
354,
291,
414,
353,
14223,
6914,
288,
203,
565,
2874,
12,
2867,
516,
3703,
560,
13,
3238,
1149,
560,
4243,
31,
203,
565,
1758,
8526,
3238,
1149,
1961,
31,
203,
565,
13586,
8526,
3238,
25038,
31,
203,
565,
7615,
367,
8526,
3238,
2727,
1012,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
29,
31,
203,
565,
2792,
13586,
1482,
288,
203,
3639,
8857,
16,
203,
3639,
10347,
1259,
16,
203,
3639,
14575,
203,
565,
289,
203,
203,
565,
1958,
3703,
560,
288,
203,
3639,
533,
508,
31,
203,
3639,
2254,
5034,
770,
31,
203,
565,
289,
203,
203,
565,
1958,
13586,
288,
203,
3639,
533,
2077,
31,
203,
3639,
13586,
1482,
1267,
31,
203,
3639,
1758,
1149,
560,
31,
203,
565,
289,
203,
203,
565,
1958,
7615,
367,
288,
203,
3639,
1758,
2727,
264,
31,
203,
3639,
2254,
5034,
5402,
548,
31,
203,
3639,
2254,
5034,
3844,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
1149,
560,
1887,
16,
203,
3639,
2254,
5034,
5402,
548,
16,
203,
3639,
1758,
2727,
264,
203,
565,
11272,
203,
203,
565,
871,
3703,
560,
10868,
12,
2867,
1149,
560,
1887,
16,
533,
508,
1769,
203,
565,
871,
3703,
560,
10026,
12,
2867,
1149,
560,
1887,
1769,
203,
565,
871,
13586,
10868,
12,
11890,
5034,
5402,
548,
16,
1758,
1149,
560,
1887,
1769,
203,
565,
871,
13586,
21890,
12,
11890,
5034,
5402,
548,
16,
1758,
1149,
560,
1887,
1769,
203,
565,
871,
2
]
|
// define ver of solidity
pragma solidity >=0.4.21 <0.7.0;
// refer to ERC-20 token standard
// this contract knows who has each token
contract StkToken {
// name
string public name = "Stonks Token";
// symbol
string public symbol = "STNK";
// not part of erc-20 standard but just shows your ver of smart contract
string public standard = "STNK Token v1.0";
// has 18 decimals behind it's value
// in money, our smallest value is called cents; in ether, its called wei
uint8 public decimals = 18;
// unsigned public int
// the public visibility auto adds a getter func to this var
uint256 public totalSupply = 1000000000000000000000000;
// mapping(key, value) = hashmap<key, value> in java
// this mapping responsible in knowing who has which token
mapping(address => uint256) public balanceOf;
// allowance public mapping - A approve B to C amount
mapping(address => mapping(address => uint256)) public allowance;
// declare a transfer event
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
// approval event
// me, the owner approve acc B (spender) to spend C (_value) amount of tokens
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
// Constructor - run whenever smart contract deployed
// Set total num of tokens
// read total num of tokens
constructor() public{
// msg is global var in solidity
// sender is address that called this function
// read official docs of solidity pls thx
balanceOf[msg.sender] = totalSupply;
// num of tokens that will exist
// state var - kinda like a class var in other lang
// allocate initial supply
}
// transfer func - throws exception if acc dont have enough, return bool
function transfer(address _to, uint256 _value) public returns (bool success){
// if not enough tokens to transfer, raise exception
// require (func in solidity) - if condition is true, continue function execution; if false, throw error
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value); // call event in solidity
return true;
}
// delegated transfer - transfer where acc didnt initiate transfer
// AKA meta transaction, another account (delegate) performs intended action on account's behalf
// one func to approve transfer, another to handle actual delegated transfer
// approve func - allows someone else to spend x tokens on their behalf
function approve(address _spender, uint256 _value) public returns (bool success){
// set allowance to 0 first before setting to another value
// allowance - alloted amount approved to transfer
allowance[msg.sender][_spender] = _value;
// approval event
emit Approval(msg.sender, _spender, _value);
return true;
}
// transferFrom func - when amt approved, can execute that transfer
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
// require _from has enough tokens and allowance is big enough
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
// change balanceOf
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
// update allowance
allowance[_from][msg.sender] -= _value;
// Transfer event
emit Transfer(_from, _to, _value);
return true;
}
} | refer to ERC-20 token standard this contract knows who has each token name symbol not part of erc-20 standard but just shows your ver of smart contract has 18 decimals behind it's value in money, our smallest value is called cents; in ether, its called wei unsigned public int the public visibility auto adds a getter func to this var mapping(key, value) = hashmap<key, value> in java this mapping responsible in knowing who has which token allowance public mapping - A approve B to C amount declare a transfer event approval event me, the owner approve acc B (spender) to spend C (_value) amount of tokens Constructor - run whenever smart contract deployed Set total num of tokens read total num of tokens | contract StkToken {
string public name = "Stonks Token";
string public symbol = "STNK";
string public standard = "STNK Token v1.0";
uint8 public decimals = 18;
uint256 public totalSupply = 1000000000000000000000000;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
pragma solidity >=0.4.21 <0.7.0;
constructor() public{
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success){
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success){
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
} | 14,115,388 | [
1,
266,
586,
358,
4232,
39,
17,
3462,
1147,
4529,
333,
6835,
21739,
10354,
711,
1517,
1147,
508,
3273,
486,
1087,
434,
6445,
71,
17,
3462,
4529,
1496,
2537,
17975,
3433,
1924,
434,
13706,
6835,
711,
6549,
15105,
21478,
518,
1807,
460,
316,
15601,
16,
3134,
13541,
460,
353,
2566,
276,
4877,
31,
316,
225,
2437,
16,
2097,
2566,
732,
77,
9088,
1071,
509,
326,
1071,
9478,
3656,
4831,
279,
7060,
1326,
358,
333,
569,
2874,
12,
856,
16,
460,
13,
273,
1651,
1458,
32,
856,
16,
460,
34,
316,
2252,
333,
2874,
14549,
316,
5055,
310,
10354,
711,
1492,
1147,
1699,
1359,
1071,
2874,
300,
432,
6617,
537,
605,
358,
385,
3844,
14196,
279,
7412,
871,
23556,
871,
1791,
16,
326,
3410,
6617,
537,
4078,
605,
261,
87,
1302,
264,
13,
358,
17571,
385,
261,
67,
1132,
13,
3844,
434,
2430,
11417,
300,
1086,
17334,
13706,
6835,
19357,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
934,
79,
1345,
288,
203,
565,
533,
1071,
508,
273,
315,
510,
265,
7904,
3155,
14432,
203,
565,
533,
1071,
3273,
273,
315,
882,
50,
47,
14432,
203,
203,
565,
533,
1071,
4529,
273,
315,
882,
50,
47,
3155,
331,
21,
18,
20,
14432,
203,
203,
565,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
273,
2130,
12648,
12648,
9449,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
1071,
1699,
1359,
31,
203,
203,
565,
871,
12279,
12,
203,
3639,
1758,
8808,
389,
2080,
16,
203,
3639,
1758,
8808,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
11272,
203,
203,
565,
871,
1716,
685,
1125,
12,
203,
3639,
1758,
8808,
389,
8443,
16,
203,
3639,
1758,
8808,
389,
87,
1302,
264,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
11272,
203,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
24,
18,
5340,
411,
20,
18,
27,
18,
20,
31,
203,
565,
3885,
1435,
1071,
95,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
2078,
3088,
1283,
31,
203,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
15329,
203,
3639,
2583,
12,
12296,
951,
63,
3576,
18,
15330,
65,
1545,
389,
1132,
1769,
203,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
3947,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
contract stocks {
address owner;
constructor() {
owner = msg.sender;
}
/// quote structure
struct stock {
uint price;
uint volume;
}
mapping( bytes4 => stock) stockQuote;
/// Contract owner
//address oracleOwner;
modifier onlyOwner {
require(msg.sender == owner, "Only owner can call this function");
_;
}
/// Set the value of a stock
function setStock(bytes4 symbol, uint price, uint volume) onlyOwner public {
stock memory _Stock = stock({price: price, volume: volume});
stockQuote[symbol] = _Stock;
}
/// Get the value of a stock
function getStockPrice(bytes4 symbol) public view returns (uint) {
return stockQuote[symbol].price;
}
/// Get the value of volume traded for a stock
function getStockVolume(bytes4 symbol) public view returns (uint) {
return stockQuote[symbol].volume;
}
} | Set the value of a stock | function setStock(bytes4 symbol, uint price, uint volume) onlyOwner public {
stockQuote[symbol] = _Stock;
}
| 7,298,759 | [
1,
694,
326,
460,
434,
279,
12480,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
17821,
12,
3890,
24,
3273,
16,
2254,
6205,
16,
2254,
3940,
13,
1338,
5541,
1071,
288,
203,
3639,
12480,
10257,
63,
7175,
65,
273,
389,
17821,
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
]
|
./full_match/100/0xd2FDc59405d1D6B5F293AB3E8fC2fC62D110Ecd6/sources/contracts/ERC20_Reputation.sol | * @dev Executive proposals can trigger some actions such as replacing the admin of the community or trigger treasury transfers/ | struct Proposal {
ProposalTypes proposalType;
uint amount;
address asset;
address oldAdmin;
address payable recipient;
Statuses status;
uint votesFor;
uint votesAgainst;
uint snapshotID;
uint voteEndAt;
Proposal[] public proposals;
mapping(address => mapping(uint => bool)) hasVotedProposal;
| 14,267,115 | [
1,
1905,
322,
688,
450,
22536,
848,
3080,
2690,
4209,
4123,
487,
13993,
326,
3981,
434,
326,
19833,
578,
3080,
9787,
345,
22498,
29375,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1958,
19945,
288,
203,
3639,
19945,
2016,
14708,
559,
31,
203,
3639,
2254,
3844,
31,
203,
3639,
1758,
3310,
31,
203,
3639,
1758,
1592,
4446,
31,
203,
3639,
1758,
8843,
429,
8027,
31,
203,
3639,
2685,
281,
1267,
31,
203,
3639,
2254,
19588,
1290,
31,
203,
3639,
2254,
19588,
23530,
334,
31,
203,
3639,
2254,
4439,
734,
31,
203,
3639,
2254,
12501,
1638,
861,
31,
203,
565,
19945,
8526,
1071,
450,
22536,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
516,
1426,
3719,
711,
58,
16474,
14592,
31,
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
]
|
pragma solidity ^0.4.11;
contract token {
function transferFrom(address, address, uint) returns(bool){}
function burn() {}
}
contract SafeMath {
//internals
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
Assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
Assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
Assert(c >= a && c >= b);
return c;
}
function Assert(bool assertion) internal {
if (!assertion) {
revert();
}
}
}
contract Crowdsale is SafeMath {
/*Owner's address*/
address public owner;
/* tokens will be transferred from BAP's address */
address public initialTokensHolder = 0xB27590b9d328bA0396271303e24db44132531411;
/* if the funding goal is not reached, investors may withdraw their funds */
uint public fundingGoal = 260000000;
/* the maximum amount of tokens to be sold */
uint public maxGoal = 2100000000;
/* how much has been raised by crowdale (in ETH) */
uint public amountRaised;
/* the start date of the crowdsale 12:00 am 31/11/2017 */
uint public start = 1508929200;
/* the start date of the crowdsale 11:59 pm 10/11/2017*/
uint public end = 1508936400;
/*token's price 1ETH = 15000 KRB*/
uint public tokenPrice = 15000;
/* the number of tokens already sold */
uint public tokensSold;
/* the address of the token contract */
token public tokenReward;
/* the balances (in ETH) of all investors */
mapping(address => uint256) public balanceOf;
/*this mapping tracking allowed specific investor to invest and their referral */
mapping(address => address) public permittedInvestors;
/* indicated if the funding goal has been reached. */
bool public fundingGoalReached = false;
/* indicates if the crowdsale has been closed already */
bool public crowdsaleClosed = false;
/* this wallet will store all the fund made by ICO after ICO success*/
address beneficiary = 0x12bF8E198A6474FC65cEe0e1C6f1C7f23324C8D5;
/* notifying transfers and the success of the crowdsale*/
event GoalReached(address TokensHolderAddr, uint amountETHRaised);
event FundTransfer(address backer, uint amount, uint amountRaisedInICO, uint amountTokenSold, uint tokensHaveSold);
event TransferToReferrer(address indexed backer, address indexed referrerAddress, uint commission, uint amountReferralHasInvested, uint tokensReferralHasBought);
event AllowSuccess(address indexed investorAddr, address referralAddr);
event Withdraw(address indexed recieve, uint amount);
function changeTime(uint _start, uint _end){
start = _start;
end = _end;
}
function changeMaxMin(uint _min, uint _max){
fundingGoal = _min;
maxGoal = _max;
}
/* initialization, set the token address */
function Crowdsale() {
tokenReward = token(0x1960edc283c1c7b9fba34da4cc1aa665eec0587e);
owner = msg.sender;
}
/* invest by sending ether to the contract. */
function () payable {
invest();
}
function invest() payable {
if(permittedInvestors[msg.sender] == 0x0) {
revert();
}
uint amount = msg.value;
uint numTokens = safeMul(amount, tokenPrice) / 1000000000000000000; // 1 ETH
if (now < start || now > end || safeAdd(tokensSold, numTokens) > maxGoal) {
revert();
}
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], amount);
amountRaised = safeAdd(amountRaised, amount);
tokensSold += numTokens;
if (!tokenReward.transferFrom(initialTokensHolder, msg.sender, numTokens)) {
revert();
}
if(permittedInvestors[msg.sender] != initialTokensHolder) {
uint commission = safeMul(numTokens, 5) / 100;
if(commission != 0){
/* we plus maxGoal for referrer in value param to distinguish between tokens for investors and tokens for referrer.
This value will be subtracted in token contract */
if (!tokenReward.transferFrom(initialTokensHolder, permittedInvestors[msg.sender], safeAdd(commission, maxGoal))) {
revert();
}
TransferToReferrer(msg.sender, permittedInvestors[msg.sender], commission, amount, numTokens);
}
}
FundTransfer(msg.sender, amount, amountRaised, tokensSold, numTokens);
}
modifier afterDeadline() {
if (now < end) {
revert();
}
_;
}
modifier onlyOwner {
if (msg.sender != owner) {
revert();
}
_;
}
/* checks if the goal or time limit has been reached and ends the campaign */
function checkGoalReached() {
if((tokensSold >= fundingGoal && now >= end) || (tokensSold >= maxGoal)) {
fundingGoalReached = true;
crowdsaleClosed = true;
tokenReward.burn();
sendToBeneficiary();
GoalReached(initialTokensHolder, amountRaised);
}
if(now >= end) {
crowdsaleClosed = true;
}
}
function allowInvest(address investorAddress, address referralAddress) onlyOwner external {
require(permittedInvestors[investorAddress] == 0x0);
if(referralAddress != 0x0 && permittedInvestors[referralAddress] == 0x0) revert();
permittedInvestors[investorAddress] = referralAddress == 0x0 ? initialTokensHolder : referralAddress;
AllowSuccess(investorAddress, referralAddress);
}
/* send money to beneficiary */
function sendToBeneficiary() internal {
beneficiary.transfer(this.balance);
}
/*if the ICO is fail, investors will call this function to get their money back */
function safeWithdrawal() afterDeadline {
require(this.balance != 0);
if(!crowdsaleClosed) revert();
uint amount = balanceOf[msg.sender];
if(address(this).balance >= amount) {
balanceOf[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
Withdraw(msg.sender, amount);
}
}
}
function kill() onlyOwner {
selfdestruct(beneficiary);
}
} | checks if the goal or time limit has been reached and ends the campaign */ | function checkGoalReached() {
if((tokensSold >= fundingGoal && now >= end) || (tokensSold >= maxGoal)) {
fundingGoalReached = true;
crowdsaleClosed = true;
tokenReward.burn();
sendToBeneficiary();
GoalReached(initialTokensHolder, amountRaised);
}
if(now >= end) {
crowdsaleClosed = true;
}
}
| 12,678,900 | [
1,
12366,
309,
326,
17683,
578,
813,
1800,
711,
2118,
8675,
471,
3930,
326,
8965,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
866,
27716,
23646,
1435,
288,
203,
3639,
309,
12443,
7860,
55,
1673,
1545,
22058,
27716,
597,
2037,
1545,
679,
13,
747,
261,
7860,
55,
1673,
1545,
943,
27716,
3719,
288,
203,
5411,
22058,
27716,
23646,
273,
638,
31,
203,
5411,
276,
492,
2377,
5349,
7395,
273,
638,
31,
203,
5411,
1147,
17631,
1060,
18,
70,
321,
5621,
203,
5411,
29091,
38,
4009,
74,
14463,
814,
5621,
203,
5411,
4220,
287,
23646,
12,
6769,
5157,
6064,
16,
3844,
12649,
5918,
1769,
203,
3639,
289,
203,
3639,
309,
12,
3338,
1545,
679,
13,
288,
203,
5411,
276,
492,
2377,
5349,
7395,
273,
638,
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
]
|
pragma solidity ^0.4.24;
// 'ETHERCHAIN' CROWDSALE token contract
//
// Deployed to : 0x49F4B69FEf86C82c8e936Bfaf1b9E326bd1A20D0
// Symbol : ERH
// Name : ETHERCHAIN TOKEN
// Total supply: 1,000,000,000
// Decimals : 18
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract ERH {
// Public variables of the token
string public name = "Etherchain";
string public symbol = "ERH";
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default
uint256 public totalSupply;
uint256 public tokenSupply = 1000000000;
uint256 public buyPrice = 500000;
address public creator;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function ERH() public {
totalSupply = tokenSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give DatBoiCoin Mint the total created tokens
creator = msg.sender;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
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) public {
_transfer(msg.sender, _to, _value);
}
/// @notice Buy tokens from contract by sending ether
function () payable internal {
uint amount = msg.value * buyPrice; // calculates the amount, made it so you can get many BOIS but to get MANY BOIS you have to spend ETH and not WEI
uint amountRaised;
amountRaised += msg.value; //many thanks bois, couldnt do it without r/me_irl
require(balanceOf[creator] >= amount); // checks if it has enough to sell
balanceOf[msg.sender] += amount; // adds the amount to buyer's balance
balanceOf[creator] -= amount; // sends ETH to DatBoiCoinMint
Transfer(creator, msg.sender, amount); // execute an event reflecting the change
creator.transfer(amountRaised);
}
} | Public variables of the token 18 decimals is the strongly suggested default This creates an array with all balances This generates a public event on the blockchain that will notify clients | contract ERH {
string public name = "Etherchain";
string public symbol = "ERH";
uint8 public decimals = 18;
uint256 public totalSupply;
uint256 public tokenSupply = 1000000000;
uint256 public buyPrice = 500000;
address public creator;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event FundTransfer(address backer, uint amount, bool isContribution);
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
function ERH() public {
creator = msg.sender;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function () payable internal {
uint amountRaised;
creator.transfer(amountRaised);
}
} | 10,849,311 | [
1,
4782,
3152,
434,
326,
1147,
6549,
15105,
353,
326,
11773,
715,
22168,
805,
1220,
3414,
392,
526,
598,
777,
324,
26488,
1220,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
7712,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
4232,
44,
288,
203,
565,
533,
1071,
508,
273,
315,
41,
1136,
5639,
14432,
203,
565,
533,
1071,
3273,
273,
315,
654,
44,
14432,
203,
565,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
565,
2254,
5034,
1071,
1147,
3088,
1283,
273,
15088,
3784,
31,
203,
565,
2254,
5034,
1071,
30143,
5147,
273,
1381,
11706,
31,
203,
565,
1758,
1071,
11784,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
1071,
1699,
1359,
31,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
565,
871,
478,
1074,
5912,
12,
2867,
1473,
264,
16,
2254,
3844,
16,
1426,
353,
442,
4027,
1769,
203,
377,
203,
377,
203,
203,
5831,
1147,
18241,
288,
445,
6798,
23461,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
1132,
16,
1758,
389,
2316,
16,
1731,
389,
7763,
751,
13,
1071,
31,
289,
203,
565,
445,
4232,
44,
1435,
1071,
288,
203,
3639,
11784,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
565,
445,
389,
13866,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
13,
2713,
288,
203,
3639,
2583,
24899,
869,
480,
374,
92,
20,
1769,
203,
3639,
2583,
12,
12296,
951,
63,
67,
2080,
65,
1545,
389,
1132,
1769,
203,
3639,
2583,
12,
12296,
951,
63,
67,
869,
65,
397,
389,
1132,
1545,
11013,
951,
63,
67,
2
]
|
./partial_match/1/0xd4d64691Dd72ff412e0dCbd093a66eBF5e01AC6f/sources/Ewagon.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Ewagon", "Baby Ethereum") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), WETH);
excludeFromMaxTransaction(address(uniswapV2Pair), true);
uint256 _buyDevFee = 5;
uint256 _buyLiquidityFee = 0;
uint256 _sellDevFee = 100;
uint256 _sellLiquidityFee = 0;
uint256 totalSupply = 100_000_000_000 * 1e18;
buyDevFee = _buyDevFee;
buyLiquidityFee = _buyLiquidityFee;
buyTotalFees = buyDevFee + buyLiquidityFee;
sellDevFee = _sellDevFee;
sellLiquidityFee = _sellLiquidityFee;
sellTotalFees = sellDevFee + sellLiquidityFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 4,435,166 | [
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,
41,
91,
346,
265,
3113,
315,
38,
24383,
512,
18664,
379,
7923,
288,
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,
203,
5411,
374,
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,
203,
3639,
11272,
203,
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,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
678,
1584,
44,
1769,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
14667,
273,
1381,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
203,
3639,
2254,
5034,
389,
87,
1165,
8870,
14667,
273,
2130,
31,
203,
3639,
2254,
5034,
389,
87,
1165,
48,
18988,
24237,
14667,
273,
374,
31,
203,
203,
3639,
2254,
5034,
2078,
3088,
1283,
273,
2130,
2
]
|
./full_match/1/0x31a91336414d3B955E494E7d485a6B06b55FC8fB/sources/contracts/vault/VaultAdmin.sol | * @notice Set the allowed slippage from the Oracle price for collateral asset swaps. @param _asset Address of the asset token. @param _allowedOracleSlippageBps allowed slippage from Oracle in basis points. eg 20 = 0.2%. Max 10%./ | function setOracleSlippage(address _asset, uint16 _allowedOracleSlippageBps)
external
onlyGovernor
{
require(assets[_asset].isSupported, "Asset not supported");
require(_allowedOracleSlippageBps < 1000, "Slippage too high");
assets[_asset].allowedOracleSlippageBps = _allowedOracleSlippageBps;
emit SwapSlippageChanged(_asset, _allowedOracleSlippageBps);
}
| 4,932,123 | [
1,
694,
326,
2935,
272,
3169,
2433,
628,
326,
28544,
6205,
364,
4508,
2045,
287,
3310,
1352,
6679,
18,
225,
389,
9406,
5267,
434,
326,
3310,
1147,
18,
225,
389,
8151,
23601,
55,
3169,
2433,
38,
1121,
2935,
272,
3169,
2433,
628,
28544,
316,
10853,
3143,
18,
9130,
4200,
273,
374,
18,
22,
9,
18,
4238,
1728,
9,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
444,
23601,
55,
3169,
2433,
12,
2867,
389,
9406,
16,
2254,
2313,
389,
8151,
23601,
55,
3169,
2433,
38,
1121,
13,
203,
3639,
3903,
203,
3639,
1338,
43,
1643,
29561,
203,
565,
288,
203,
3639,
2583,
12,
9971,
63,
67,
9406,
8009,
291,
7223,
16,
315,
6672,
486,
3260,
8863,
203,
3639,
2583,
24899,
8151,
23601,
55,
3169,
2433,
38,
1121,
411,
4336,
16,
315,
55,
3169,
2433,
4885,
3551,
8863,
203,
203,
3639,
7176,
63,
67,
9406,
8009,
8151,
23601,
55,
3169,
2433,
38,
1121,
273,
389,
8151,
23601,
55,
3169,
2433,
38,
1121,
31,
203,
203,
3639,
3626,
12738,
55,
3169,
2433,
5033,
24899,
9406,
16,
389,
8151,
23601,
55,
3169,
2433,
38,
1121,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
// DataHashAuth implements contract for registering authentic
// products hash inside the ledger by hashing their unique attributes
// and validating products authenticity providing the same set of attributes.
contract DataHashAuth {
// TProduct defines the scanned product information stored inside
// the contract for future validation.
struct TProduct {
string name; // name of the product
string producerName; // name of the product manufacturer
string batchNo; // production batch number
string barcodeNo; // barcode of the product
uint64 productionDate; // the UTC timestamp of the production date
uint64 expiryDate; // the UTC timestamp of the expiration date
uint64 added; // the time stamp of the product record creation
uint64 updated; // the time stamp of the last product update
uint64 invalidated; // the time stamp of the product invalidation
bytes32 productHash; // hash of the product data for validation
}
// InputProduct defines a structure for product input.
struct InputProduct {
uint64 pid; // unique product identifier
string name; // name of the product
string producer; // name of the producer
string batchNo; // batch number
string barcodeNo; // barcode number
uint64 productionDate; // timestamp of the production
uint64 expiryDate; // timestamp of the expiration
}
// admin is the account allowed to change contract parameters.
address public _admin;
// proManagers are the accounts allowed to add new products
// and product related data into the contract.
mapping (address => bool) public _proManagers;
// products represents mapping between unique product PID
// and the product details record held inside the contract.
mapping(uint64 => TProduct) public _products;
// pinToProductPid represents mapping between authentic product PIN
// and a unique product identifier, the PID.
mapping(uint256 => uint64) public _pinToProductPid;
// ProductAdded event is emitted on new product receival.
event ProductAdded(uint64 indexed _pid, bytes32 _hash, uint64 _timestamp);
// ProductUpdated event is emitted on an existing product data change.
event ProductUpdated(uint64 indexed _pid, bytes32 _hash, uint64 _timestamp);
// ProductInvalidated event is emitted on marking a product as invalid.
event ProductInvalidated(uint64 indexed _pid, uint64 _timestamp);
// PinAdded event is emitted on adding a new PIN to the contract.
event PinAdded(uint64 indexed _pid, uint256 indexed _pin, uint64 _timestamp);
// ManagerPromoted event is emitted on adding new authorized scanner.
event ManagerPromoted(address indexed _addr, uint64 _timestamp);
// ManagerDemoted event is emitted on removing a scanner from authorized.
event ManagerDemoted(address indexed _addr, uint64 _timestamp);
// constructor initializes new contract instance on deployment
// the creator will also become the hash repository manager
constructor() public payable {
// keep the administrator reference
_admin = msg.sender;
// administrator is the first one allowed to manage products
_proManagers[msg.sender] = true;
}
// ----------------------------------------------------------------
// products management
// ----------------------------------------------------------------
// setProduct adds or updates a product information
// from an authorized product manager address in the contract.
function setProduct(InputProduct calldata _product) external {
// make sure this is autenticated access
require(_proManagers[msg.sender], "access restricted");
// the product PIN is expected to be unique
bool isNew = (_products[_product.pid].added == 0);
// calculate the hash
bytes32 _hash = _hashProduct(
_product.pid,
_product.name,
_product.producer,
_product.batchNo,
_product.barcodeNo,
_product.expiryDate,
_product.productionDate);
// enlist the product in the contract (aloc the storage for it)
TProduct storage inProduct = _products[_product.pid];
// update the product data
inProduct.name = _product.name;
inProduct.producerName = _product.producer;
inProduct.batchNo = _product.batchNo;
inProduct.barcodeNo = _product.barcodeNo;
inProduct.productionDate = _product.productionDate;
inProduct.expiryDate = _product.expiryDate;
inProduct.productHash = _hash;
// set the product timestamp record to recognize the action
// and emit the appropriate product event
if (isNew) {
// the product didn't exist before and so it's a new one
inProduct.added = uint64(now);
emit ProductAdded(_product.pid, _hash, uint64(now));
} else {
// the product existed before and so it's an update
inProduct.updated = uint64(now);
emit ProductUpdated(_product.pid, _hash, uint64(now));
}
}
// invalidate a product identified by it's unique PID id.
function invalidate(uint64 _pid) external {
// make sure this is autenticated access
require(_proManagers[msg.sender], "access restricted");
// make sure the product is known
require(_products[_pid].added > 0, "unknown product");
// make the change
_products[_pid].invalidated = uint64(now);
// emit the event
emit ProductInvalidated(_pid, uint64(now));
}
// _hash calculates the hash of the product used for both
// the product registration and validation procedures.
function _hashProduct(
uint64 _pid,
string memory _name,
string memory _producerName,
string memory _batchNo,
string memory _barcodeNo,
uint64 _productionDate,
uint64 _expiryDate
) internal pure returns (bytes32) {
// calculate the hash from encoded product data pack
return keccak256(abi.encode(
_pid,
_name,
_batchNo,
_barcodeNo,
_expiryDate,
_productionDate,
_producerName
));
}
// ----------------------------------------------------------------
// product PIN management (the PIN is what's printed on QR patches)
// ----------------------------------------------------------------
// addPins adds a new set of PINs for the product identified
// by the unique product PID.
function addPins(uint64 _pid, uint256[] calldata _pins) external {
// make sure this is autenticated access
require(_proManagers[msg.sender], "access restricted");
// we do not check product existence here since the product may
// be added later based on client data processing queue.
for (uint i = 0; i < _pins.length; i++) {
// make sure this pin is new
if (0 == _pinToProductPid[_pins[i]]) {
// add the PIN to PID link
_pinToProductPid[_pins[i]] = _pid;
// emit the event
emit PinAdded(_pid, _pins[i], uint64(now));
}
}
}
// ckeck validates product authenticity for the given product data set
// using an internal authentic products list. Anybody can authenticate
// products using this function, no access restrictions are applied.
function check(
uint256 _pin,
string memory _name,
string memory _producerName,
string memory _batchNo,
string memory _barcodeNo,
uint64 _productionDate,
uint64 _expiryDate
) public view returns (bool) {
// do we even know the PIN?
if (0 == _pinToProductPid[_pin]) {
return false;
}
// get the product PID
uint64 _pid = _pinToProductPid[_pin];
// calculate the hash
bytes32 _hash = _hashProduct(
_pid,
_name,
_producerName,
_batchNo,
_barcodeNo,
_expiryDate,
_productionDate);
// compare the product details hash with the stored product details
// make sure the product has not been invalidated
return (
_hash == _products[_pid].productHash &&
0 == _products[_pid].invalidated
);
}
// ----------------------------------------------------------------
// contract internals management
// ----------------------------------------------------------------
// promote adds a new authorized scanner address
// into the contract.
function promote(address _addr) external {
// only manager can authorize
require(msg.sender == _admin, "access restricted");
// authorize the address and inform listeners
_proManagers[_addr] = true;
emit ManagerPromoted(_addr, uint64(now));
}
// demote removes the specified address
// from authorized scanners.
function demote(address _addr) external {
// only manager can authorize
require(msg.sender == _admin, "access restricted");
// authorize the address
_proManagers[_addr] = false;
emit ManagerDemoted(_addr, uint64(now));
}
}
| constructor initializes new contract instance on deployment the creator will also become the hash repository manager keep the administrator reference administrator is the first one allowed to manage products | constructor() public payable {
_admin = msg.sender;
_proManagers[msg.sender] = true;
}
| 2,550,590 | [
1,
12316,
11643,
394,
6835,
791,
603,
6314,
326,
11784,
903,
2546,
12561,
326,
1651,
3352,
3301,
3455,
326,
22330,
2114,
22330,
353,
326,
1122,
1245,
2935,
358,
10680,
10406,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
1071,
8843,
429,
288,
203,
3639,
389,
3666,
273,
1234,
18,
15330,
31,
203,
203,
3639,
389,
685,
17570,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xE292B17018189aDAc3321E95494520F35859b9df/sources/contracts/pool/impl/exp/DittoPoolExp.sol | Spot price is assumed to be the instant sell price. To avoid arbitraging LPs, we adjust the buy price upwards. If base price for buy and sell were the same, then someone could buy 1 NFT and then sell for immediate profit. EX: Let S be base price. Then buying 1 NFT costs S ETH, now new base price is (S * delta). The same person could then sell for (S * delta) ETH, netting them delta ETH profit. If base price for buy and sell differ by delta, then buying costs (S * delta) ETH. The new base price would become (S * delta), so selling would also yield (S * delta) ETH. | uint256 buyBasePrice = _mul(basePrice, delta);
| 16,497,123 | [
1,
17292,
6205,
353,
12034,
358,
506,
326,
5934,
357,
80,
6205,
18,
2974,
4543,
10056,
2458,
310,
511,
18124,
16,
732,
5765,
326,
30143,
6205,
731,
6397,
18,
971,
1026,
6205,
364,
30143,
471,
357,
80,
4591,
326,
1967,
16,
1508,
18626,
3377,
30143,
404,
423,
4464,
471,
1508,
357,
80,
364,
14483,
450,
7216,
18,
5675,
30,
10559,
348,
506,
1026,
6205,
18,
9697,
30143,
310,
404,
423,
4464,
22793,
348,
512,
2455,
16,
2037,
394,
1026,
6205,
353,
261,
55,
225,
3622,
2934,
1021,
1967,
6175,
3377,
1508,
357,
80,
364,
261,
55,
225,
3622,
13,
512,
2455,
16,
2901,
1787,
2182,
3622,
512,
2455,
450,
7216,
18,
971,
1026,
6205,
364,
30143,
471,
357,
80,
15221,
635,
3622,
16,
1508,
30143,
310,
22793,
261,
55,
225,
3622,
13,
512,
2455,
18,
1021,
394,
1026,
6205,
4102,
12561,
261,
55,
225,
3622,
3631,
1427,
357,
2456,
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,
2254,
5034,
30143,
2171,
5147,
273,
389,
16411,
12,
1969,
5147,
16,
3622,
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
]
|
pragma solidity ^0.5.12;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./CherryPool.sol";
/**
* @title CherrySwap Contract
* @notice Create, manage and store all interest rate swaps within the Cherryswap platform.
* Offers one side of a swap with the other taken by a liquidity pool. The offered rate is
* a function of the pool demand (utilization) and the current floating rates.
*/
contract CherrySwap is Initializable, CherryPool {
// 25% APR is the max the pool will pay. This is 25%, compounding per block,
// scaled by 10^18. calculate by: (0.25 * 1e18) / (4 * 60 * 24 * 365)
uint256 constant MAX_INTEREST_PAID_PER_BLOCK = 118911719939;
// Swap curve hyper parameters
uint256 constant ALPHA = 150; //scaled by 100 so 150 = 1.5
uint256 constant BETA = 0;
// Other constants
uint256 constant RAGE_QUITE_PENALTY = 20; //scaled by 100 so 20 = 0.2
uint256 constant ONE_MONTH_SECONDS = 60 * 60 * 24 * 30;
// Swap Data structures
enum Bet { Short, Long }
struct Swap {
address owner;
uint256 swapId;
uint256 startingTime;
uint256 endingTime;
uint256 fixedRateOffer;
uint256 amount;
uint256 cTokenAmount;
uint256 reserveAmount;
uint256 startingcTokenExchangeRate;
Bet bet;
}
Swap[] public swaps;
event CreateLongPosition(
address indexed trader,
uint256 indexed swapId,
uint256 startingTime,
uint256 endingTime,
uint256 daiAmount,
uint256 cDaiAmount,
uint256 fixedRate,
uint256 amountReserved,
uint256 startingcDaiExchRate
);
event CreateShortPosition(
address indexed trader,
uint256 indexed swapId,
uint256 startingTime,
uint256 endingTime,
uint256 daiAmount,
uint256 cDaiAmount,
uint256 fixedRate,
uint256 amountReserved,
uint256 startingcDaiExchRate
);
event ClosePosition(
uint256 indexed swapId,
address indexed trader,
uint256 cDaiRedeemed,
uint256 daiTransfered
);
event FixedRateOffer(uint256 rate);
/**
* @notice Initialize contract states
*/
function initialize(address _token, address _cToken, address _cherryMath) public initializer {
require(
(_token != address(0)) && (_cToken != address(0) && (_cherryMath != address(0))),
"CherrySwap::invalid tokens addresses"
);
CherryPool.initialize(_token, _cToken, _cherryMath);
cToken.approve(_token, 100000000000e18);
}
/**
* @notice function called by trader to enter into long swap position.
* In a long position the trader will pay a fixed rate and receive a floating rate.
* Because the amount is unbounded for that paid to the long side (they receive a floating rate) an upper
* bound is placed on the maximum amount that they can receive.
* @dev requires long pool utilization < 100% and enough liquidity in the long pool to cover trader.
* @param _amount the number of Dai that the buyer will pay for their long position
*/
function createLongPosition(uint256 _amount) external isLongUtilized {
// Find the upper bound of how much could be paid as a function of the max interest rate the pool will pay
// This defines how much needs to be "reserved" for long positions.
uint256 maxFutureValue = cherryMath.futureValue(_amount, MAX_INTEREST_PAID_PER_BLOCK, 0, ONE_MONTH_SECONDS);
// The amount reserved is the profit that the pool could need to pay in worst case.
uint256 reserveAmount = maxFutureValue - _amount;
// Reserve liquidity. checks the amount spesified is a valid reservation are done in function.
_reserveLongPool(reserveAmount);
// This transfer will fail if the caller has not approved.
require(
token.transferFrom(msg.sender, address(this), _amount),
"CherrySwap::create long position transfer from failed"
);
uint256 cherrySwapBalanceBefore = cToken.balanceOf(address(this));
require(cToken.mint(_amount) == 0, "CherrySwap::create long position compound deposit failed");
uint256 cherrySwapBalanceAfter = cToken.balanceOf(address(this));
uint256 cTokensMinted = cherrySwapBalanceAfter - cherrySwapBalanceBefore;
uint256 fixedRateOffer = getFixedRateOffer(Bet.Long);
uint256 cDaiExchangeRate = getcTokenExchangeRate();
swaps.push(
Swap(
msg.sender, // owner
numSwaps(), // identifer
now, // start time
now + ONE_MONTH_SECONDS, // end time
fixedRateOffer, // rate paid
_amount, // amount of dai committed to the swap
cTokensMinted, // number of cDai tokens added
reserveAmount, // dai reserved from the pool's long side offering
cDaiExchangeRate, // starting cDai exchange rate. used to compute change in floating side
Bet.Long // bet direction (long)
)
);
emit CreateLongPosition(
msg.sender,
numSwaps(),
now,
now + ONE_MONTH_SECONDS,
_amount,
cTokensMinted,
fixedRateOffer,
reserveAmount,
cDaiExchangeRate
);
}
/**
* @notice function called by trader to enter into short swap position.
* @dev requires short pool utlization < 100% and enough liquidity in the short pool to cover trader
* @param _amount the number of Dai that the buyer will pay for their short position
*/
function createShortPosition(uint256 _amount) external isShortUtilized {
uint256 futureValue = cherryMath.futureValue(_amount, MAX_INTEREST_PAID_PER_BLOCK, 0, ONE_MONTH_SECONDS);
uint256 reserveAmount = futureValue - _amount;
// should first check if pool have enough liquidity to cover swap position
_reserveShortPool(reserveAmount);
// This transfer will fail if the caller has not approved.
require(
token.transferFrom(msg.sender, address(this), _amount),
"CherrySwap::create short position transfer from failed"
);
uint256 cherrySwapBalanceBefore = cToken.balanceOf(address(this));
require(cToken.mint(_amount) == 0, "CherrySwap::create short position compound deposit failed");
uint256 cherrySwapBalanceAfter = cToken.balanceOf(address(this));
uint256 cTokensMinted = cherrySwapBalanceAfter - cherrySwapBalanceBefore;
uint256 fixedRateOffer = getFixedRateOffer(Bet.Short);
uint256 cDaiExchangeRate = getcTokenExchangeRate();
swaps.push(
Swap(
msg.sender,
numSwaps(),
now,
now + ONE_MONTH_SECONDS,
fixedRateOffer,
_amount,
cTokensMinted,
reserveAmount,
cDaiExchangeRate,
Bet.Short
)
);
emit CreateShortPosition(
msg.sender,
numSwaps(),
now,
now + ONE_MONTH_SECONDS,
_amount,
cTokensMinted,
fixedRateOffer,
reserveAmount,
cDaiExchangeRate
);
}
/**
* @notice traded withdraw from their position.
* @dev if the time is after the end of the swap then they will receive the swap rate for
* the duration of the swap and then the floating market rate between the end of the
* swap and the current time.
* @param _swapId swap number
*/
function closePosition(uint256 _swapId) external returns (uint256) {
//TODO: add check for caller address. is this needed?
//TODO: add check for maturity of position. should only be able to close position after maturity.
Swap memory swap = swaps[_swapId];
// based on the changing interst rate over time, find the number of Dai tokens to pay to the trader.
uint256 tokensToSend = tokensToPayTrader(swap);
// Need to calculate the number of cTokens that will be withdrawn from the withdrawl
uint256 cTokensToWithdraw = (tokensToSend * 1e18) / getcTokenExchangeRate();
// Tokens need to be withdrawn from Compound.
//TODO: add a require here to check the number of Dai recived is correct.
cToken.redeem(cTokensToWithdraw);
token.transfer(swap.owner, tokensToSend);
int256 poolcTokenProfitChange = int256(swap.cTokenAmount) - int256(cTokensToWithdraw);
_addcTokenPoolProfit(poolcTokenProfitChange);
if (swap.bet == Bet.Long) {
_freeLongPool(swap.reserveAmount);
}
if (swap.bet == Bet.Short) {
_freeShortPool(swap.reserveAmount);
}
emit ClosePosition(_swapId, swap.owner, cTokensToWithdraw, tokensToSend);
}
/**
* @notice calculate how much needs to be paid to the trader at end of swap
* @dev long offer swap where the liquidity pool is short: receiving a fixed rate and paying a floating rate
* @dev short offer swap the liquidity pool is long: receiving floating rate, paying fixed rate
*/
function tokensToPayTrader(Swap memory _swap) internal returns (uint256) {
//if the trader is long then they will pay fixed, receive float.
if (_swap.bet == Bet.Long) {
return
_swap.amount + // swap nominal
getFloatingValue(_swap.startingcTokenExchangeRate, getcTokenExchangeRate(), _swap.amount) - // floating leg, paid to long side
cherryMath.futureValue(_swap.amount, _swap.fixedRateOffer, _swap.startingTime, _swap.endingTime); // fixed leg(paid by long side
}
//if the trader is short then they will receive fixed, pay float.
if (_swap.bet == Bet.Short) {
return
_swap.amount + // swap nominal
cherryMath.futureValue(_swap.amount, _swap.fixedRateOffer, _swap.startingTime, _swap.endingTime) - // fixed leg, paid to short side
getFloatingValue(_swap.startingcTokenExchangeRate, getcTokenExchangeRate(), _swap.amount); // floating leg, paid by the short side
}
}
/**
* @notice at any point a trader in a swap can rage quite.
* @dev This will eject them from the position, free up liquidity and they walk away with some dai
* however there is a heavy penalty in doing this!
*/
function rageQuitSwap(uint256 _swapId) external returns (uint256) {
return 0;
}
function numSwaps() public view returns (uint256) {
return swaps.length;
}
/**
* @notice calculate the offered fixed rate for swaps taken against the liquidity pool
* in future this will be updated to consider the size of the positon. for now it's kept simple.
* @param bet position bet (long or short)
* @return _fixedRateOffer offered fixed rate
*/
function getFixedRateOffer(Bet bet) public returns (uint256 _fixedRateOffer) {
if (bet == Bet.Long) {
_fixedRateOffer = (cToken.supplyRatePerBlock().mul(
uint256(1e18).sub(calcLongPoolUtil(longPoolReserved)).div(ALPHA.sub(BETA))
)).div(1e18);
}
if (bet == Bet.Long) {
_fixedRateOffer = (cToken.supplyRatePerBlock().mul(
uint256(1e18).add(calcShortPoolUtil(shortPoolReserved)).div(ALPHA.add(BETA))
)).div(1e18);
}
emit FixedRateOffer(_fixedRateOffer);
return _fixedRateOffer;
}
/**
* @notice given the starting and end exchange rate of a cToken calculate the final valuation of the position
* @dev this acts to scale the amount by the change in exchange rate seen by the cToken.
* If the starting cToken exchange rate is stored and the end rate is known then this function returns
* the value that _amount has grown by.
* @param _startingExchangeRate starting cToken exchange rate
* @param _endingExchangeRate ending cToken exchange rate
* @param _amount token amount
* @return swap position valuation
*/
function getFloatingValue(uint256 _startingExchangeRate, uint256 _endingExchangeRate, uint256 _amount)
public
view
returns (uint256)
{
return (_amount * _endingExchangeRate) / _startingExchangeRate;
}
}
| * @notice Initialize contract states/ | function initialize(address _token, address _cToken, address _cherryMath) public initializer {
require(
(_token != address(0)) && (_cToken != address(0) && (_cherryMath != address(0))),
"CherrySwap::invalid tokens addresses"
);
CherryPool.initialize(_token, _cToken, _cherryMath);
cToken.approve(_token, 100000000000e18);
}
| 5,535,883 | [
1,
7520,
6835,
5493,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4046,
12,
2867,
389,
2316,
16,
1758,
389,
71,
1345,
16,
1758,
389,
343,
21938,
10477,
13,
1071,
12562,
288,
203,
3639,
2583,
12,
203,
5411,
261,
67,
2316,
480,
1758,
12,
20,
3719,
597,
261,
67,
71,
1345,
480,
1758,
12,
20,
13,
597,
261,
67,
343,
21938,
10477,
480,
1758,
12,
20,
3719,
3631,
203,
5411,
315,
782,
21938,
12521,
2866,
5387,
2430,
6138,
6,
203,
3639,
11272,
203,
203,
3639,
1680,
21938,
2864,
18,
11160,
24899,
2316,
16,
389,
71,
1345,
16,
389,
343,
21938,
10477,
1769,
203,
203,
3639,
276,
1345,
18,
12908,
537,
24899,
2316,
16,
15088,
11706,
73,
2643,
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
]
|
//Address: 0xCDa98bA916AD2561ACA6D5aC7B83C76Fe49165c8
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 4/6/2018
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.15;
pragma solidity ^0.4.15;
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
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 */
contract StandardToken is Token {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function transfer(address _to, uint256 _value) returns (bool success) {
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) {
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];
}
}
pragma solidity ^0.4.15;
pragma solidity ^0.4.15;
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender == owner)
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) owner = newOwner;
}
}
/*
* Pausable
* Abstract contract that allows children to implement an
* emergency stop mechanism.
*/
contract Pausable is Ownable {
bool public stopped;
modifier stopInEmergency {
if (stopped) {
throw;
}
_;
}
modifier onlyInEmergency {
if (!stopped) {
throw;
}
_;
}
// called by the owner on emergency, triggers stopped state
function emergencyStop() external onlyOwner {
stopped = true;
}
// called by the owner on end of emergency, returns to normal state
function release() external onlyOwner onlyInEmergency {
stopped = false;
}
}
pragma solidity ^0.4.15;
contract Utils{
//verifies the amount greater than zero
modifier greaterThanZero(uint256 _value){
require(_value>0);
_;
}
///verifies an address
modifier validAddress(address _add){
require(_add!=0x0);
_;
}
}
pragma solidity ^0.4.15;
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
contract Crowdsale is StandardToken, Pausable, SafeMath, Utils{
string public constant name = "BlockAim Token";
string public constant symbol = "BA";
uint256 public constant decimals = 18;
string public version = "1.0";
bool public tradingStarted = false;
/**
* @dev modifier that throws if trading has not started yet
*/
modifier hasStartedTrading() {
require(tradingStarted);
_;
}
/**
* @dev Allows the owner to enable the trading. This can not be undone
*/
function startTrading() onlyOwner() {
tradingStarted = true;
}
function transfer(address _to, uint _value) hasStartedTrading returns (bool success) {super.transfer(_to, _value);}
function transferFrom(address _from, address _to, uint _value) hasStartedTrading returns (bool success) {super.transferFrom(_from, _to, _value);}
enum State{
Inactive,
Funding,
Success,
Failure
}
uint256 public investmentETH;
mapping(uint256 => bool) transactionsClaimed;
uint256 public initialSupply;
address wallet;
uint256 public constant _totalSupply = 100 * (10**6) * 10 ** decimals; // 100M ~ 10 Crores
uint256 public fundingStartBlock; // crowdsale start block
uint256 public tokensPerEther = 300; // 1 ETH = 300 tokens
uint256 public constant tokenCreationMax = 10 * (10**6) * 10 ** decimals; // 10M ~ 1 Crores
address[] public investors;
//displays number of uniq investors
function investorsCount() constant external returns(uint) { return investors.length; }
function Crowdsale(uint256 _fundingStartBlock, address _owner, address _wallet){
owner = _owner;
fundingStartBlock =_fundingStartBlock;
totalSupply = _totalSupply;
initialSupply = 0;
wallet = _wallet;
//check configuration if something in setup is looking weird
if (
tokensPerEther == 0
|| owner == 0x0
|| wallet == 0x0
|| fundingStartBlock == 0
|| totalSupply == 0
|| tokenCreationMax == 0
|| fundingStartBlock <= block.number)
throw;
}
// don't just send ether to the contract expecting to get tokens
//function() { throw; }
////@dev This function manages the Crowdsale State machine
///We make it a function and do not assign to a variable//
///so that no chance of stale variable
function getState() constant public returns(State){
///once we reach success lock the State
if(block.number<fundingStartBlock) return State.Inactive;
else if(block.number>fundingStartBlock && initialSupply<tokenCreationMax) return State.Funding;
else if (initialSupply >= tokenCreationMax) return State.Success;
else return State.Failure;
}
///get total tokens in that address mapping
function getTokens(address addr) public returns(uint256){
return balances[addr];
}
function() external payable stopInEmergency{
// Abort if not in Funding Active state.
if(getState() == State.Success) throw;
if (msg.value == 0) throw;
uint256 newCreatedTokens = safeMul(msg.value,tokensPerEther);
///since we are creating tokens we need to increase the total supply
initialSupply = safeAdd(initialSupply,newCreatedTokens);
if(initialSupply>tokenCreationMax) throw;
if (balances[msg.sender] == 0) investors.push(msg.sender);
investmentETH += msg.value;
balances[msg.sender] = safeAdd(balances[msg.sender],newCreatedTokens);
Transfer(this, msg.sender, newCreatedTokens);
// Pocket the money
if(!wallet.send(msg.value)) throw;
}
///to be done only the owner can run this function
function tokenMint(address addr,uint256 tokens)
external
stopInEmergency
onlyOwner()
{
if(getState() == State.Success) throw;
if(addr == 0x0) throw;
if (tokens == 0) throw;
uint256 newCreatedTokens = tokens * 1 ether;
initialSupply = safeAdd(initialSupply,newCreatedTokens);
if(initialSupply>tokenCreationMax) throw;
if (balances[addr] == 0) investors.push(addr);
balances[addr] = safeAdd(balances[addr],newCreatedTokens);
Transfer(this, addr, newCreatedTokens);
}
///change exchange rate ~ update price everyday
function changeExchangeRate(uint256 eth)
external
onlyOwner()
{
if(eth == 0) throw;
tokensPerEther = eth;
}
///blacklist the users which are fraudulent
///from getting any tokens
///to do also refund just in cases
function blacklist(address addr)
external
onlyOwner()
{
balances[addr] = 0;
}
}
| change exchange rate ~ update price everyday | function changeExchangeRate(uint256 eth)
external
onlyOwner()
{
if(eth == 0) throw;
tokensPerEther = eth;
}
| 7,324,824 | [
1,
3427,
7829,
4993,
4871,
1089,
6205,
3614,
2881,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
282,
445,
2549,
11688,
4727,
12,
11890,
5034,
13750,
13,
203,
282,
3903,
203,
282,
1338,
5541,
1435,
203,
282,
288,
203,
377,
309,
12,
546,
422,
374,
13,
604,
31,
203,
377,
2430,
2173,
41,
1136,
273,
13750,
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
]
|
// contracts/GameItem.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract BonsaiBank is ERC721URIStorage {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private bonsaiIds;
struct Bonsai {
uint256 lastWatered; // The last time the bonsai was watered
uint256 consecutiveWaterings; // The number of waterings gone without missing a watering
uint256 waterBalance; // The amount of water tokens deposited
uint256 lastFertilized; // The last time the bonsai was fertilized
uint256 consecutiveFertilizings; // The number of fertilizings without missing a fertilize
uint256 fertilizerBalance; // The amount of fertilizer tokens deposited
uint256 lifeStage; // The amount of times this bonsai has been grown or wilted
}
Bonsai[] bonsaiBanks; // All bonsai banks, indexible by bonsai/tokenId - 1
address botanist; // The owner of the contract, has control of the protocol
address waterToken; // The ERC20 token address to use for watering
address fertToken; // The ERC20 token address to use for fertilizing
uint256 waterAmount; // The amount of waterTokens needed for watering
uint256 fertAmount; // The amount of fertTokens needed for fertilizing
uint256 waterRate; // The time delay between waterings in seconds
uint256 fertRate; // The time delay between fertilizing in seconds
uint256 wateringsToGrow; // The number of consecutive waterings needed to grow
constructor(address _botanist) ERC721("Bonsai Bank", "BNZI") {
botanist = _botanist;
}
modifier onlyBotanist {
require(msg.sender == botanist);
_;
}
// Getter Methods
function getBotanist() public view returns(address) {
return botanist;
}
function getWaterToken() public view returns(address) {
return waterToken;
}
function getFertToken() public view returns(address) {
return fertToken;
}
function getWaterAmount() public view returns(uint256) {
return waterAmount;
}
function getFertAmount() public view returns(uint256) {
return fertAmount;
}
function getWaterRate() public view returns(uint256) {
return waterRate;
}
function getFertRate() public view returns(uint256) {
return fertRate;
}
function lastWatered(uint256 bonsaiId) external view returns (uint256){
return bonsaiBanks[bonsaiId-1].lastWatered;
}
function consecutiveWaterings(uint256 bonsaiId) external view returns (uint256){
return bonsaiBanks[bonsaiId-1].consecutiveWaterings;
}
function waterBalance(uint256 bonsaiId) external view returns (uint256){
return bonsaiBanks[bonsaiId-1].waterBalance;
}
function lastFertilized(uint256 bonsaiId) external view returns (uint256){
return bonsaiBanks[bonsaiId-1].lastFertilized;
}
function consecutiveFertilizings(uint256 bonsaiId) external view returns (uint256){
return bonsaiBanks[bonsaiId-1].consecutiveFertilizings;
}
function fertilizerBalance(uint256 bonsaiId) external view returns (uint256){
return bonsaiBanks[bonsaiId-1].fertilizerBalance;
}
function lifeStage(uint256 bonsaiId) external view returns (uint256){
return bonsaiBanks[bonsaiId-1].lifeStage;
}
function exists(uint256 bonsaiId) external view returns (bool){
return _exists(bonsaiId);
}
// Setter Methods
function setBotanist(address _botanist) external onlyBotanist {
botanist = _botanist;
}
function setWaterToken(address _waterToken) external onlyBotanist {
waterToken = _waterToken;
}
function setFertToken(address _fertToken) external onlyBotanist {
fertToken = _fertToken;
}
function setWaterAmount(uint256 _waterAmount) external onlyBotanist {
waterAmount = _waterAmount;
}
function setFertAmount(uint256 _fertAmount) external onlyBotanist {
fertAmount = _fertAmount;
}
function setWaterRate(uint256 _waterRate) external onlyBotanist {
waterRate = _waterRate;
}
function setFertRate(uint256 _fertRate) external onlyBotanist {
fertRate = _fertRate;
}
function setWateringsToGrow(uint256 _wateringsToGrow) external onlyBotanist {
wateringsToGrow = _wateringsToGrow;
}
// Interal only setters for Bonsai Banks
function setLastWatered(uint256 bonsaiId, uint256 _lastWatered) internal {
bonsaiBanks[bonsaiId-1].lastWatered = _lastWatered;
}
function setConsecutiveWaterings(uint256 bonsaiId, uint256 _consecutiveWaterings) internal {
bonsaiBanks[bonsaiId-1].consecutiveWaterings = _consecutiveWaterings;
}
function setWaterBalance(uint256 bonsaiId, uint256 _waterBalance) internal {
bonsaiBanks[bonsaiId-1].waterBalance = _waterBalance;
}
function setLastFertilized(uint256 bonsaiId, uint256 _lastFertilized) internal {
bonsaiBanks[bonsaiId-1].lastFertilized = _lastFertilized;
}
function setConsecutiveFertilizings(uint256 bonsaiId, uint256 _consecutiveFertilizings) internal {
bonsaiBanks[bonsaiId-1].consecutiveFertilizings = _consecutiveFertilizings;
}
function setFertilizerBalance(uint256 bonsaiId, uint256 _fertilizerBalance) internal {
bonsaiBanks[bonsaiId-1].fertilizerBalance = _fertilizerBalance;
}
function setLifeStage(uint256 bonsaiId, uint256 _lifeStage) external {
bonsaiBanks[bonsaiId-1].lifeStage = _lifeStage;
}
// Events
event BonsaiCreated(address caretaker,uint256 _bonsaiId,string bonsaiURI,address botanist );
event BonsaiWatered(address waterer,uint256 _bonsaiId,uint256 lastWatered,uint256 consecutiveWaterings,uint256 waterBalance );
event BonsaiFertilized(address waterer,uint256 _bonsaiId,uint256 lastFertilized,uint256 consecutiveFertilizings,uint256 fertilizerBalance );
event BonsaiGrow(address botanist,uint256 _bonsaiID,string _bonsaiURI,uint256 lifeStage,uint256 consecutiveWaterings);
event BonsaiWilt(address botanist,uint256 _bonsaiID,string _bonsaiURI,uint256 consecutiveFertilizings,uint256 consecutiveWaterings);
event BonsaiDestroy(address botanist,uint256 _bonsaiID,uint256 waterBalance, uint256 fertilizerBalance);
// Core Bonsai Bank Functionality
// @dev Mints a new Bonsai Bank directly to the caretaker
function mint(address caretaker, string memory bonsaiURI) external onlyBotanist returns (uint256 bonsaiId) {
bonsaiIds.increment();
uint256 _bonsaiId = bonsaiIds.current();
Bonsai memory bb = Bonsai(0,0,0,0,0,0,0);
_mint(caretaker, _bonsaiId);
_setTokenURI(_bonsaiId, bonsaiURI);
bonsaiBanks.push(bb);
emit BonsaiCreated(caretaker, _bonsaiId, bonsaiURI, botanist);
return _bonsaiId;
}
function water(uint256 _bonsaiId) external {
require(bonsaiBanks[_bonsaiId - 1].lastWatered < block.timestamp - waterRate, "!waterable");
require(IERC20(waterToken).transferFrom(msg.sender, address(this), getWaterAmount()), "!watered");
bonsaiBanks[_bonsaiId - 1].lastWatered = block.timestamp;
bonsaiBanks[_bonsaiId - 1].consecutiveWaterings += 1;
bonsaiBanks[_bonsaiId - 1].waterBalance += getWaterAmount();
emit BonsaiWatered(msg.sender, _bonsaiId, bonsaiBanks[_bonsaiId - 1].lastWatered, bonsaiBanks[_bonsaiId - 1].consecutiveWaterings, bonsaiBanks[_bonsaiId - 1].waterBalance);
}
function fertilize(uint256 _bonsaiId) external {
require(bonsaiBanks[_bonsaiId - 1].lastFertilized < block.timestamp - fertRate, "!fertalizable");
require(IERC20(fertToken).transferFrom(msg.sender, address(this), getFertAmount()), "!fertilized");
bonsaiBanks[_bonsaiId - 1].lastFertilized = block.timestamp;
bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings += 1;
bonsaiBanks[_bonsaiId - 1].fertilizerBalance += getFertAmount();
emit BonsaiFertilized(msg.sender, _bonsaiId, bonsaiBanks[_bonsaiId - 1].lastFertilized, bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings, bonsaiBanks[_bonsaiId - 1].fertilizerBalance);
}
function grow(uint256 _bonsaiId, string memory _bonsaiURI) external onlyBotanist {
require(bonsaiBanks[_bonsaiId - 1].consecutiveWaterings >= wateringsToGrow, "!growable");
_setTokenURI(_bonsaiId, _bonsaiURI);
bonsaiBanks[_bonsaiId - 1].lifeStage += 1;
bonsaiBanks[_bonsaiId - 1].consecutiveWaterings = 0;
emit BonsaiGrow(botanist, _bonsaiId, _bonsaiURI, bonsaiBanks[_bonsaiId - 1].lifeStage, bonsaiBanks[_bonsaiId - 1].consecutiveWaterings);
}
function wilt(uint256 _bonsaiId, string memory _bonsaiURI) external onlyBotanist {
require(bonsaiBanks[_bonsaiId - 1].lastWatered <= block.timestamp - waterRate.mul(2), "!wiltable");
uint256 waterSlashAmount = bonsaiBanks[_bonsaiId - 1].waterBalance.mul(95).div(100); // TODO: Safe Math
uint256 fertSlashAmount = bonsaiBanks[_bonsaiId - 1].fertilizerBalance.mul(95).div(100); // TODO: Safe Math
require(IERC20(waterToken).transfer(botanist, waterSlashAmount), "!slashedWater");
require(IERC20(fertToken).transfer(botanist, fertSlashAmount), "!slashedFert");
_setTokenURI(_bonsaiId, _bonsaiURI);
bonsaiBanks[_bonsaiId - 1].consecutiveWaterings = 0;
bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings = 0;
emit BonsaiWilt(botanist, _bonsaiId, _bonsaiURI, bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings, bonsaiBanks[_bonsaiId - 1].consecutiveWaterings);
}
function destroy(uint256 _bonsaiId) external {
require(ownerOf(_bonsaiId) == msg.sender, "!caretaker");
require(IERC20(waterToken).transfer(msg.sender, bonsaiBanks[_bonsaiId - 1].waterBalance), "!withdrawWater");
require(IERC20(fertToken).transfer(msg.sender, bonsaiBanks[_bonsaiId - 1].fertilizerBalance), "!withdrawFertlizer");
bonsaiBanks[_bonsaiId - 1].waterBalance = 0;
bonsaiBanks[_bonsaiId - 1].fertilizerBalance = 0;
_burn(_bonsaiId);
emit BonsaiDestroy(botanist, _bonsaiId, bonsaiBanks[_bonsaiId - 1].waterBalance, bonsaiBanks[_bonsaiId - 1].fertilizerBalance);
}
}
| The time delay between waterings in seconds
| uint256 waterRate; | 12,926,558 | [
1,
1986,
813,
4624,
3086,
16313,
899,
316,
3974,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16313,
4727,
31,
10402,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
/**
* @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 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool 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 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 getSortedSpotByFunction(LinkedList storage self, uint256 _node, uint256 _value, bool _direction, function (uint, uint) view returns (bool) smallerComparator, int256 searchLimit)
internal view returns (uint256 nextNodeIndex, bool found, uint256 sizeEnd)
{
if ((sizeEnd=sizeOf(self)) == 0) { return (0, true, sizeEnd); }
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((--searchLimit >= 0) && (next != 0) && (_value != next) && (smallerComparator(_value, next) != _direction)) next = self.list[next][_direction];
if(searchLimit >= 0)
return (next, true, sizeEnd + 1);
else return (0, false, sizeEnd); //We exhausted the search limit without finding a position!
}
/// @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 enrty 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 {
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);
}
}
// ----------------------------------------------------------------------------
// 'Coke' token contract
//
// Deployed to : 0xb9907e0151e8c5937f17d0721953cf1ea114528e
// Symbol : COKE
// Name : Coke Token
// Total supply: 875 000 000 000 000 micrograms (875 tons)
// Decimals : 6 (micrograms)
//
// @2018 FC
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a && c >= b);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
}
contract Mutex {
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// Contract "Recoverable", to allow a failsafe in case of user error, so users can recover their mistakenly sent Tokens or Eth
// https://github.com/ethereum/dapp-bin/blob/master/library/recoverable.sol
// ----------------------------------------------------------------------------
contract Recoverable is Owned {
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ETH
// ------------------------------------------------------------------------
function recoverLostEth(address toAddress, uint value) public onlyOwner returns (bool success) {
toAddress.transfer(value);
return true;
}
}
/**
* @title EmergencyProtectedMode
* @dev Base contract which allows children to implement an emergency stop mechanism different than pausable. Useful for when we want to
* stop the normal business of the contract (using the Pausable contract), but still allow some operations like withdrawls for users.
*/
contract EmergencyProtectedMode is Owned {
event EmergencyProtectedModeActivated();
event EmergencyProtectedModeDeactivated();
bool public emergencyProtectedMode = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotInEmergencyProtectedMode() {
require(!emergencyProtectedMode);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenInEmergencyProtectedMode() {
require(emergencyProtectedMode);
_;
}
/**
* @dev called by the owner to activate emergency protected mode, triggers stopped state, to use in case of last resort, and stop even last case operations (in case of a security compromise)
*/
function activateEmergencyProtectedMode() onlyOwner whenNotInEmergencyProtectedMode public {
emergencyProtectedMode = true;
emit EmergencyProtectedModeActivated();
}
/**
* @dev called by the owner to deactivate emergency protected mode, returns to normal state
*/
function deactivateEmergencyProtectedMode() onlyOwner whenInEmergencyProtectedMode public {
emergencyProtectedMode = false;
emit EmergencyProtectedModeDeactivated();
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Owned {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Migratable
* @dev Base contract which allows children to be migratable, that is it allows contracts to migrate to another contract (sucessor) that
* is a more advanced version of the previous contract (more functionality, improved security, etc.).
*/
contract Migratable is Owned {
address public sucessor; //By default, sucessor will be address 0, meaning the current contract is still active and has no sucessor yet!
function setSucessor(address _sucessor) onlyOwner public {
sucessor=_sucessor;
}
}
// ---------------------------------------------------------------------------------------------
// Directly Exchangeable token
// This will allow users to directly exchange between themselves tokens for Eth and vice versa,
// while having the assurance the other party will be kept to their part of the agreement.
// ---------------------------------------------------------------------------------------------
contract DirectlyExchangeable {
bool public isRatio; //Should be true if the prices used will be a Ratio, and not just a simple price, otherwise false.
function sellToConsumer(address consumer, uint quantity, uint price) public returns (bool success);
function buyFromTrusterDealer(address dealer, uint quantity, uint price) public payable returns (bool success);
function cancelSellToConsumer(address consumer) public returns (bool success);
function checkMySellerOffer(address consumer) public view returns (uint quantity, uint price, uint totalWeiCost);
function checkSellerOffer(address seller) public view returns (uint quantity, uint price, uint totalWeiCost);
//Events:
event DirectOfferAvailable(address indexed seller, address indexed buyer, uint quantity, uint price);
event DirectOfferCancelled(address indexed seller, address indexed consumer, uint quantity, uint price);
event OrderQuantityMismatch(address indexed addr, uint expectedInRegistry, uint buyerValue);
event OrderPriceMismatch(address indexed addr, uint expectedInRegistry, uint buyerValue);
}
// ---------------------------------------------------------------------------------------------
// Black Market Sellable token
// This will allow users to sell and buy from a black market, without knowing one another,
// while having the assurance the other party will keep their part of the agreement.
// ---------------------------------------------------------------------------------------------
contract BlackMarketSellable {
bool public isRatio; //Should be true if the prices used will be a Ratio, and not just a simple price, otherwise false.
function sellToBlackMarket(uint quantity, uint price) public returns (bool success, uint numOrderCreated);
function cancelSellToBlackMarket(uint quantity, uint price, bool continueAfterFirstMatch) public returns (bool success, uint numOrdersCanceled);
function buyFromBlackMarket(uint quantity, uint priceLimit) public payable returns (bool success, bool partial, uint numOrdersCleared);
function getSellOrdersBlackMarket() public view returns (uint[] memory r);
function getSellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices);
function getMySellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices);
//Events:
event BlackMarketOfferAvailable(uint quantity, uint price);
event BlackMarketOfferBought(uint quantity, uint price, uint leftOver);
event BlackMarketNoOfferForPrice(uint price);
event BlackMarketOfferCancelled(uint quantity, uint price);
event OrderInsufficientPayment(address indexed addr, uint expectedValue, uint valueReceived);
event OrderInsufficientBalance(address indexed addr, uint expectedBalance, uint actualBalance);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Coke is ERC20Interface, Owned, Pausable, EmergencyProtectedMode, Recoverable, Mutex, Migratable, DirectlyExchangeable, BlackMarketSellable, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
//Needed setup for LinkedList needed for the market:
using LinkedListLib for LinkedListLib.LinkedList;
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
//Token specific properties:
uint16 public constant yearOfProduction = 1997;
string public constant protectedDenominationOfOrigin = "Colombia";
string public constant targetDemographics = "The jet set / Top of the tops";
string public constant securityAudit = "ExtremeAssets Team Ref: XN872 Approved";
uint buyRatio; //Ratio to buy from the contract directly
uint sellRatio; //Ratio to sell from the contract directly
uint private _factorDecimalsEthToToken;
uint constant undergroundBunkerReserves = 2500000000000;
mapping(address => uint) changeToReturn; //The change to return to senders (in ETH value (Wei))
mapping(address => uint) gainsToReceive; //The gains to receive (for sellers) (in ETH value (Wei))
mapping(address => uint) tastersReceived; //Number of tokens received as a taster for each address
mapping(address => uint) toFlush; //Keeps address to be flushed (the value stored is the number of the block of when coke can be really flushed from the system)
event Flushed(address indexed addr);
event ChangeToReceiveGotten(address indexed addr, uint weiToReceive, uint totalWeiToReceive);
event GainsGotten(address indexed addr, uint weiToReceive, uint totalWeiToReceive);
struct SellOffer {
uint price;
uint quantity;
}
struct SellOfferComplete {
uint price;
uint quantity;
address seller;
}
mapping(address => mapping(address => SellOffer)) directOffers; //Direct offers
LinkedListLib.LinkedList blackMarketOffersSorted;
mapping(uint => SellOfferComplete) public blackMarketOffersMap;
uint marketOfferCounter = 0; //Counter that will increment for each offer
uint directOffersComissionRatio = 100; //Ratio of the comission to buy from the contract directly (1%)
uint marketComissionRatio = 50; //Ratio of the comission to buy from the market (2%)
int32 maxMarketOffers = 100; //Maximum of market offers at the same time (will only keep the N less costly offers)
//Message board variables:
struct Message {
uint valuePayed;
string msg;
address from;
}
LinkedListLib.LinkedList topMessagesSorted;
mapping(uint => Message) public topMessagesMap;
uint topMessagesCounter = 0; //Counter that will increment for each message
int32 maxMessagesTop = 20; //Maximum of top messages at the same time (will keep the N most payed messages)
Message[] messages;
int32 maxMessagesGlobal = 100; //Maximum number of messages at the same time (will keep the N most recently received messages)
int32 firstMsgGlobal = 0; //Indexes that will mark the first and the last message received in the array of global messages (revolving array)
int32 lastMsgGlobal = -1;
uint maxCharactersMessage = 750; //The maximum of characters a message can have
event NewMessageAvailable(address indexed from, string message);
event ExceededMaximumMessageSize(uint messageSize, uint maximumMessageSize); //Message is bigger than maximum allowed characters for each message
//Addresses to be used for random letItRain!
address[] lastAddresses;
int32 maxAddresses = 100; //Maximum number of addresses at the same time (will keep the N most recently mentioned addresses)
int32 firstAddress = 0; //Indexes that will mark the first and the last address received in the array of last addresses (revolving array)
int32 lastAddress = -1;
event NoAddressesAvailable();
// ------------------------------------------------------------------------
// Confirms the user is not in the middle of a flushing process
// ------------------------------------------------------------------------
modifier whenNotFlushing() {
require(toFlush[msg.sender] == 0);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Coke() public {
symbol = "Coke";
name = "100 % Pure Cocaine";
decimals = 6; //Micrograms
_totalSupply = 875000000 * (uint(10)**decimals);
_factorDecimalsEthToToken = uint(10)**(18);
buyRatio = 10 * (uint(10)**decimals); //10g <- 1 ETH
sellRatio = 20 * (uint(10)**decimals); //20g -> 1 ETH
isRatio = true; //Buy and sell prices are ratios (and not simple prices) of how many tokens per 1 ETH
balances[0] = _totalSupply - undergroundBunkerReserves;
balances[msg.sender] = undergroundBunkerReserves;
//blackMarketOffers.length = maxMarketOffers;
//Do a reservation for msg.sender! Allow rest to be sold by contract!
emit Transfer(address(0), msg.sender, undergroundBunkerReserves);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply /* - balances[address(0)] */;
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transferInt(address from, address to, uint tokens, bool updateTasters) internal returns (bool success) {
if(updateTasters) {
//Check if sender has received tasters:
if(tastersReceived[from] > 0) {
uint tasterTokens = min(tokens, tastersReceived[from]);
tastersReceived[from] = safeSub(tastersReceived[from], tasterTokens);
if(to != address(0)) {
tastersReceived[to] = safeAdd(tastersReceived[to], tasterTokens);
}
}
}
balances[from] = safeSub(balances[from], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public whenNotPaused returns (bool success) {
return transferInt(msg.sender, to, tokens, true);
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public whenNotPaused returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) {
//Update the allowance, the rest it business as usual for the transferInt method:
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
return transferInt(from, to, tokens, true);
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant whenNotPaused returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public whenNotPaused returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Calculates the number of tokens (in unsigned integer form [decimals included]) corresponding to the weiValue passed, using the ratio specified
// ------------------------------------------------------------------------
function calculateTokensFromWei(uint weiValue, uint ratio) public view returns (uint numTokens) {
uint calc1 = safeMul(weiValue, ratio);
uint ethValue = calc1 / _factorDecimalsEthToToken;
return ethValue;
}
// ------------------------------------------------------------------------
// Calculates the Eth value (in wei) corresponding to the number of tokens passed (in unsigned integer form [decimals included]), using the ratio specified
// ------------------------------------------------------------------------
function calculateEthValueFromTokens(uint numTokens, uint ratio) public view returns (uint weiValue) {
uint calc1 = safeMul(numTokens, _factorDecimalsEthToToken);
uint retValue = calc1 / ratio;
return retValue;
}
// ------------------------------------------------------------------------
// Will buy tokens corresponding to the Ether sent (Own Token Specific Method)
// - Contract supply of tokens must have enough balance
// ------------------------------------------------------------------------
function buyCoke() public payable returns (bool success) {
//Calculate tokens corresponding to the Ether sent:
uint numTokensToBuy = calculateTokensFromWei(msg.value, buyRatio);
uint finalNumTokensToBuy = numTokensToBuy;
if(numTokensToBuy > balances[0]) {
//Adjust number of tokens to buy, to those available in stock:
finalNumTokensToBuy = balances[0];
//Update change to return for this sender (in Wei):
//SAFETY CHECK: No need to use safeSub for (numTokensToBuy - finalNumTokensToBuy), as we already know that numTokensToBuy > finalNumTokensToBuy!
uint ethValueFromTokens = calculateEthValueFromTokens(numTokensToBuy - finalNumTokensToBuy, buyRatio); //In Wei
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], ethValueFromTokens );
emit ChangeToReceiveGotten(msg.sender, ethValueFromTokens, changeToReturn[msg.sender]);
}
if(finalNumTokensToBuy <= balances[0]) {
/*
balances[0] = safeSub(balances[0], finalNumTokensToBuy);
balances[msg.sender] = safeAdd(balances[msg.sender], finalNumTokensToBuy);
Transfer(address(0), msg.sender, finalNumTokensToBuy);
*/
transferInt(address(0), msg.sender, finalNumTokensToBuy, false);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will show to the user that is asking the change he has to receive
// ------------------------------------------------------------------------
function checkChangeToReceive() public view returns (uint changeInWei) {
return changeToReturn[msg.sender];
}
// ------------------------------------------------------------------------
// Will show to the user that is asking the gains he has to receive
// ------------------------------------------------------------------------
function checkGainsToReceive() public view returns (uint gainsInWei) {
return gainsToReceive[msg.sender];
}
// ------------------------------------------------------------------------
// Will get change in ETH from the tokens that were not possible to buy in a previous order
// - Contract supply of ETH must have enough balance (which should be in every case)
// ------------------------------------------------------------------------
function retrieveChange() public noReentrancy whenNotInEmergencyProtectedMode returns (bool success) {
uint change = changeToReturn[msg.sender];
if(change > 0) {
//Set correct value of change before calling transfer method to avoid reentrance after sending to another contracts:
changeToReturn[msg.sender] = 0;
//Send corresponding ETH to sender:
msg.sender.transfer(change);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will get gains in ETH from the tokens that the seller has previously sold
// - Contract supply of ETH must have enough balance (which should be in every case)
// ------------------------------------------------------------------------
function retrieveGains() public noReentrancy whenNotInEmergencyProtectedMode returns (bool success) {
uint gains = gainsToReceive[msg.sender];
if(gains > 0) {
//Set correct value of "gains to receive" before calling transfer method to avoid reentrance attack after possibly sending to another contract:
gainsToReceive[msg.sender] = 0;
//Send corresponding ETH to sender:
msg.sender.transfer(gains);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will return N bought tokens to the contract
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function returnCoke(uint ugToReturn) public noReentrancy whenNotPaused whenNotFlushing returns (bool success) {
//require(ugToReturn <= balances[msg.sender]); //Check balance of user
//Following require not needed anymore, will just pay the difference!
//require(ugToReturn > tastersReceived[msg.sender]); //Check if the mg to return are greater than the ones received as a taster
//Maximum possible number of mg to return, have to be lower than the balance of the user minus the tasters received:
uint finalUgToReturnForEth = min(ugToReturn, safeSub(balances[msg.sender], tastersReceived[msg.sender])); //Subtract tasters received from the total amount to return
//require(finalUgToReturnForEth <= balances[msg.sender]); //Check balance of user (No need for this extra check, as the minimum garantees at most the value of the balance[] to be returned)
//Calculate tokens corresponding to the Ether sent:
uint ethToReturn = calculateEthValueFromTokens(finalUgToReturnForEth, sellRatio); //Ethereum to return (in Wei)
if(ethToReturn > 0) {
//Will return eth in exchange for the coke!
//Receive the coke:
transfer(address(0), finalUgToReturnForEth);
/*
balances[0] = safeAdd(balances[0], finalUgToReturnForEth);
balances[msg.sender] = safeSub(balances[msg.sender], finalUgToReturnForEth);
Transfer(msg.sender, address(0), finalUgToReturnForEth);
*/
//Return the Eth:
msg.sender.transfer(ethToReturn);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will return all bought tokens to the contract
// ------------------------------------------------------------------------
function returnAllCoke() public returns (bool success) {
return returnCoke(safeSub(balances[msg.sender], tastersReceived[msg.sender]));
}
// ------------------------------------------------------------------------
// Sends a special taster package to recipient
// - Contract supply of tokens must have enough balance
// ------------------------------------------------------------------------
function sendSpecialTasterPackage(address addr, uint ugToTaste) public whenNotPaused onlyOwner returns (bool success) {
tastersReceived[addr] = safeAdd(tastersReceived[addr], ugToTaste);
transfer(addr, ugToTaste);
return true;
}
// ------------------------------------------------------------------------
// Will transfer to selected address a load of tokens
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function sendShipmentTo(address to, uint tokens) public returns (bool success) {
return transfer(to, tokens);
}
// ------------------------------------------------------------------------
// Will transfer a small sample to selected address
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function sendTaster(address to) public returns (bool success) {
//Sending in 0.000002 g (that is 2 micrograms):
return transfer(to, 2);
}
function lengthAddresses() internal view returns (uint) {
return (firstAddress > 0) ? lastAddresses.length : uint(lastAddress + 1);
}
// ------------------------------------------------------------------------
// Will make it rain! Will throw some tokens from the user to some random addresses, spreading the happiness everywhere!
// The greater the range, it will supply to addresses further away.
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function letItRain(uint8 range, uint quantity) public returns (bool success) {
require(quantity <= balances[msg.sender]);
if(lengthAddresses() == 0) {
emit NoAddressesAvailable();
return false;
}
bytes32 hashBlock100 = block.blockhash(100); //Get hash of previous 100th block
bytes32 randomHash = keccak256(keccak256(hashBlock100)); //SAFETY CHECK: Increase difficulty to reverse needed hashBlock100 (in case of attack by the miners)
byte posAddr = randomHash[1]; //Check position one (to 10, maximum) of randomHash to use for the position(s) in the addresses array
byte howMany = randomHash[30]; //Check position 30 of randomHash to use for how many addresses base
uint8 posInt = (uint8(posAddr) + range * 2) % uint8(lengthAddresses()); //SAFETY CHECK: lengthAddresses() can't be greater than 256!!
uint8 howManyInt = uint8(howMany) % uint8(lengthAddresses()); //SAFETY CHECK: lengthAddresses() can't be greater than 256!!
howManyInt = howManyInt > 10 ? 10 : howManyInt; //At maximum distribute to 10 addresses
howManyInt = howManyInt < 2 ? 2 : howManyInt; //At minimum distribute to 2 addresses
address addr;
uint8 counter = 0;
uint quant = quantity / howManyInt;
do {
//Distribute to one random address:
addr = lastAddresses[posInt];
transfer(addr, quant);
posInt = (uint8(randomHash[1 + counter]) + range * 2) % uint8(lengthAddresses());
counter++;
//SAFETY CHECK: As the integer divisions are truncated (--> (quant * howManyInt) <= quantity (always) ), the following code is not needed:
/*
//we have to ensure, in case of uneven division, to just use at maximum the quantity specified by the user:
if(quantity > quant) {
quantity = quantity - quant;
}
else {
quant = quantity;
}
*/
}
while(quantity > 0 && counter < howManyInt);
return true;
}
// ------------------------------------------------------------------------
// Method will be used to set a certain number of addresses periodically. These addresses will be the ones to receive randomly the tokens when somebody makes it rain!
// The list of addresses should be gotten from the main ethereum, by checking for addresses used in the latest transactions.
// ------------------------------------------------------------------------
function setAddressesForRain(address[] memory addresses) public onlyOwner returns (bool success) {
require(addresses.length <= uint(maxAddresses) && addresses.length > 0);
lastAddresses = addresses;
firstAddress = 0;
lastAddress = int32(addresses.length) - 1;
return true;
}
// ------------------------------------------------------------------------
// Will get the Maximum of addresses to be used for making it rain
// ------------------------------------------------------------------------
function getMaxAddresses() public view returns (int32) {
return maxAddresses;
}
// ------------------------------------------------------------------------
// Will set the Maximum of addresses to be used for making it rain (Maximum of 255 Addresses)
// ------------------------------------------------------------------------
function setMaxAddresses(int32 _maxAddresses) public onlyOwner returns (bool success) {
require(_maxAddresses > 0 && _maxAddresses < 256);
maxAddresses = _maxAddresses;
return true;
}
// ------------------------------------------------------------------------
// Will get the Buy Ratio
// ------------------------------------------------------------------------
function getBuyRatio() public view returns (uint) {
return buyRatio;
}
// ------------------------------------------------------------------------
// Will set the Buy Ratio
// ------------------------------------------------------------------------
function setBuyRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
buyRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will get the Sell Ratio
// ------------------------------------------------------------------------
function getSellRatio() public view returns (uint) {
return sellRatio;
}
// ------------------------------------------------------------------------
// Will set the Sell Ratio
// ------------------------------------------------------------------------
function setSellRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
sellRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will set the Direct Offers Comission Ratio
// ------------------------------------------------------------------------
function setDirectOffersComissionRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
directOffersComissionRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will get the Direct Offers Comission Ratio
// ------------------------------------------------------------------------
function getDirectOffersComissionRatio() public view returns (uint) {
return directOffersComissionRatio;
}
// ------------------------------------------------------------------------
// Will set the Market Comission Ratio
// ------------------------------------------------------------------------
function setMarketComissionRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
marketComissionRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will get the Market Comission Ratio
// ------------------------------------------------------------------------
function getMarketComissionRatio() public view returns (uint) {
return marketComissionRatio;
}
// ------------------------------------------------------------------------
// Will set the Maximum of Market Offers
// ------------------------------------------------------------------------
function setMaxMarketOffers(int32 _maxMarketOffers) public onlyOwner returns (bool success) {
uint blackMarketOffersSortedSize = blackMarketOffersSorted.sizeOf();
if(blackMarketOffersSortedSize > uint(_maxMarketOffers)) {
int32 diff = int32(blackMarketOffersSortedSize - uint(_maxMarketOffers));
//require(diff < _maxMarketOffers);
require(diff <= int32(blackMarketOffersSortedSize)); //SAFETY CHECK (recommended because of type conversions)!
//Do the needed number of Pops to clear the market offers list if _maxMarketOffers (new) < maxMarketOffers (old)
while (diff > 0) {
uint lastOrder = blackMarketOffersSorted.pop(PREV); //Pops element from the Tail!
delete blackMarketOffersMap[lastOrder];
diff--;
}
}
maxMarketOffers = _maxMarketOffers;
//blackMarketOffers.length = maxMarketOffers;
return true;
}
// ------------------------------------------------------------------------
// Internal function to calculate the number of extra blocks needed to flush, depending on the stash to flush (the greater the load, more difficult it will be)
// ------------------------------------------------------------------------
function calculateFactorFlushDifficulty(uint stash) internal pure returns (uint extraBlocks) {
uint numBlocksToFlush = 10;
uint16 factor;
if(stash < 1000) {
factor = 1;
}
else if(stash < 5000) {
factor = 2;
}
else if(stash < 10000) {
factor = 3;
}
else if(stash < 100000) {
factor = 4;
}
else if(stash < 1000000) {
factor = 5;
}
else if(stash < 10000000) {
factor = 10;
}
else if(stash < 100000000) {
factor = 50;
}
else if(stash < 1000000000) {
factor = 500;
}
else {
factor = 5000;
}
return numBlocksToFlush * factor;
}
// ------------------------------------------------------------------------
// Throws away your stash (down the drain ;) ) immediately.
// ------------------------------------------------------------------------
function downTheDrainImmediate() internal returns (bool success) {
//Clean any flushing that it still had if possible:
toFlush[msg.sender] = 0;
//Transfer to contract all the balance:
transfer(address(0), balances[msg.sender]);
tastersReceived[msg.sender] = 0;
emit Flushed(msg.sender);
return true;
}
// ------------------------------------------------------------------------
// Throws away your stash (down the drain ;) ). It can take awhile to be completely flushed. You can send in 0.01 ether to speed up this process.
// ------------------------------------------------------------------------
function downTheDrain() public whenNotPaused payable returns (bool success) {
if(msg.value < 0.01 ether) {
//No hurry, will use default method to flush the coke (will take some time)
toFlush[msg.sender] = block.number + calculateFactorFlushDifficulty(balances[msg.sender]);
return true;
}
else return downTheDrainImmediate();
}
// ------------------------------------------------------------------------
// Checks if the dump is complete and we can flush the whole stash!
// ------------------------------------------------------------------------
function flush() public whenNotPaused returns (bool success) {
//Current block number is already greater than the limit to be flushable?
if(block.number >= toFlush[msg.sender]) {
return downTheDrainImmediate();
}
else return false;
}
// ------------------------------------------------------------------------
// Comparator used to compare priceRatios inside the LinkedList
// ------------------------------------------------------------------------
function smallerPriceComparator(uint priceNew, uint nodeNext) internal view returns (bool success) {
//When comparing ratios the smaller one will be the one with the greater ratio (cheaper price):
//return priceNew < blackMarketOffersMap[nodeNext].price;
return priceNew > blackMarketOffersMap[nodeNext].price; //If priceNew ratio is greater, it means it is a cheaper offer!
}
// ------------------------------------------------------------------------
// Put order on the blackmarket to sell a certain quantity of coke at a certain price.
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH) (for example, to get 10g for 1 ETH, the ratio should be 10000000)
// For sellers the lower the ratio the better, the more ETH the buyer will need to spend to get each token!
// - Seller must have enough balance of tokens
// ------------------------------------------------------------------------
function sellToBlackMarket(uint quantity, uint priceRatio) public whenNotPaused whenNotFlushing returns (bool success, uint numOrderCreated) {
//require(quantity <= balances[msg.sender]block.number >= toFlush[msg.sender]);
//CHeck if user has sufficient balance to do a sell offer:
if(quantity > balances[msg.sender]) {
//Seller is missing funds: Abort order:
emit OrderInsufficientBalance(msg.sender, quantity, balances[msg.sender]);
return (false, 0);
}
//Insert order in the sorted list (from cheaper to most expensive)
//Find an offer that is more expensive:
//nodeMoreExpensive =
uint nextSpot;
bool foundPosition;
uint sizeNow;
(nextSpot, foundPosition, sizeNow) = blackMarketOffersSorted.getSortedSpotByFunction(HEAD, priceRatio, NEXT, smallerPriceComparator, maxMarketOffers);
if(foundPosition) {
//Create new Sell Offer:
uint newNodeNum = ++marketOfferCounter; //SAFETY CHECK: Doesn't matter if we cycle again from MAX_INT to 0, as we have only 100 maximum offers at a time, so there will never be some overwriting of valid offers!
blackMarketOffersMap[newNodeNum].quantity = quantity;
blackMarketOffersMap[newNodeNum].price = priceRatio;
blackMarketOffersMap[newNodeNum].seller = msg.sender;
//Insert cheaper offer before nextSpot:
blackMarketOffersSorted.insert(nextSpot, newNodeNum, PREV);
if(int32(sizeNow) > maxMarketOffers) {
//Delete the tail element so we can keep the same number of max market offers:
uint lastIndex = blackMarketOffersSorted.pop(PREV); //Pops and removes last element of the list!
delete blackMarketOffersMap[lastIndex];
}
emit BlackMarketOfferAvailable(quantity, priceRatio);
return (true, newNodeNum);
}
else {
return (false, 0);
}
}
// ------------------------------------------------------------------------
// Cancel order on the blackmarket to sell a certain quantity of coke at a certain price.
// If the seller has various order with the same quantity and priceRatio, and can put parameter "continueAfterFirstMatch" to true,
// so it will continue and cancel all those black market orders.
// ------------------------------------------------------------------------
function cancelSellToBlackMarket(uint quantity, uint priceRatio, bool continueAfterFirstMatch) public whenNotPaused returns (bool success, uint numOrdersCanceled) {
//Get first node:
bool exists;
bool matchFound = false;
uint offerNodeIndex;
uint offerNodeIndexToProcess;
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(HEAD, NEXT);
if(!exists)
return (false, 0); //Black Market is empty of offers!
do {
offerNodeIndexToProcess = offerNodeIndex; //Store the current index that is being processed!
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(offerNodeIndex, NEXT); //Get next node
//Analyse current node, to see if it is the one to cancel:
if( blackMarketOffersMap[offerNodeIndexToProcess].seller == msg.sender
&& blackMarketOffersMap[offerNodeIndexToProcess].quantity == quantity
&& blackMarketOffersMap[offerNodeIndexToProcess].price == priceRatio) {
//Cancel current offer:
blackMarketOffersSorted.remove(offerNodeIndexToProcess);
delete blackMarketOffersMap[offerNodeIndexToProcess];
matchFound = true;
numOrdersCanceled++;
success = true;
emit BlackMarketOfferCancelled(quantity, priceRatio);
}
else {
matchFound = false;
}
}
while(offerNodeIndex != NULL && exists && (!matchFound || continueAfterFirstMatch));
return (success, numOrdersCanceled);
}
function calculateAndUpdateGains(SellOfferComplete offerThisRound) internal returns (uint) {
//Calculate values to be payed for this seller:
uint weiToBePayed = calculateEthValueFromTokens(offerThisRound.quantity, offerThisRound.price);
//Calculate fees and values to distribute:
uint fee = safeDiv(weiToBePayed, marketComissionRatio);
uint valueForSeller = safeSub(weiToBePayed, fee);
//Update change values (seller will have to retrieve his/her gains by calling method "retrieveGains" to receive the Eth)
gainsToReceive[offerThisRound.seller] = safeAdd(gainsToReceive[offerThisRound.seller], valueForSeller);
emit GainsGotten(offerThisRound.seller, valueForSeller, gainsToReceive[offerThisRound.seller]);
return weiToBePayed;
}
function matchOffer(uint quantity, uint nodeIndex, SellOfferComplete storage offer) internal returns (bool exists, uint offerNodeIndex, uint quantityRound, uint weiToBePayed, bool cleared) {
uint quantityToCheck = min(quantity, offer.quantity); //Quantity to check for this seller offer)
SellOfferComplete memory offerThisRound = offer;
bool forceRemovalOffer = false;
//Check token balance of seller:
if(balances[offerThisRound.seller] < quantityToCheck) {
//Invalid offer now, user no longer has sufficient balance
quantityToCheck = balances[offerThisRound.seller];
//Seller will no longer have balance: Clear offer from market!
forceRemovalOffer = true;
}
offerThisRound.quantity = quantityToCheck;
if(offerThisRound.quantity > 0) {
//Seller of this offer will receive his Ether:
//Calculate and update gains:
weiToBePayed = calculateAndUpdateGains(offerThisRound);
//Update current offer:
offer.quantity = safeSub(offer.quantity, offerThisRound.quantity);
//Emit event to signal an order was bought:
emit BlackMarketOfferBought(offerThisRound.quantity, offerThisRound.price, offer.quantity);
//Transfer tokens between seller and buyer:
//SAFETY CHECK: No more transactions are made to other contracts!
transferInt(offer.seller, msg.sender /* buyer */, offerThisRound.quantity, true);
}
//Keep a copy of next node:
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(nodeIndex, NEXT);
//Check if current offer was completely fullfulled and remove it from market:
if(forceRemovalOffer || offer.quantity == 0) {
//Seller no longer has balance: Clear offer from market!
//Or Seller Offer was completely fulfilled
//Delete the first element so we can remove current order from the market:
uint firstIndex = blackMarketOffersSorted.pop(NEXT); //Pops and removes first element of the list!
delete blackMarketOffersMap[firstIndex];
cleared = true;
}
quantityRound = offerThisRound.quantity;
return (exists, offerNodeIndex, quantityRound, weiToBePayed, cleared);
}
// ------------------------------------------------------------------------
// Put order on the blackmarket to sell a certain quantity of coke at a certain price.
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH) (for example, to get 10g for 1 ETH, the ratio should be 10000000)
// For buyers the higher the ratio the better, the more they get!
// - Buyer must have sent enough payment for the buy he wants
// - If buyer sends more than needed, it will be available for him to get it back as change (through the retrieveChange method)
// - Gains of sellers will be available through the retrieveGains method
// ------------------------------------------------------------------------
function buyFromBlackMarket(uint quantity, uint priceRatioLimit) public payable whenNotPaused whenNotFlushing noReentrancy returns (bool success, bool partial, uint numOrdersCleared) {
numOrdersCleared = 0;
partial = false;
//Get cheapest offer on the market right now:
bool exists;
bool cleared = false;
uint offerNodeIndex;
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(HEAD, NEXT);
if(!exists) {
//Abort buy from market!
revert(); //Return Eth to buyer!
//Maybe in the future, put the buyer offer in a buyer's offers list!
//TODO: IMPROVEMENTS!
}
SellOfferComplete storage offer = blackMarketOffersMap[offerNodeIndex];
uint totalToBePayedWei = 0;
uint weiToBePayedRound = 0;
uint quantityRound = 0;
//When comparing ratios the smaller one will be the one with the greater ratio (cheaper price):
//if(offer.price > priceRatioLimit) {
if(offer.price < priceRatioLimit) {
//Abort buy from market! Not one sell offer is cheaper than the priceRatioLimit
//BlackMarketNoOfferForPrice(priceRatioLimit);
//return (false, 0);
revert(); //Return Eth to buyer!
//Maybe in the future, put the buyer offer in a buyer's offers list!
//TODO: IMPROVEMENTS!
}
bool abort = false;
//Cycle through market seller offers:
do {
(exists /* Exists next offer to match */,
offerNodeIndex, /* Node index for Next Offer */
quantityRound, /* Quantity that was matched in this round */
weiToBePayedRound, /* Wei that was used to pay for this round */
cleared /* Offer was completely fulfilled and was cleared! */
) = matchOffer(quantity, offerNodeIndex, offer);
if(cleared) {
numOrdersCleared++;
}
//Update total to be payed (in Wei):
totalToBePayedWei = safeAdd(totalToBePayedWei, weiToBePayedRound);
//Update quantity (still missing to be satisfied):
quantity = safeSub(quantity, quantityRound);
//Check if buyer send enough balance to buy the orders:
if(totalToBePayedWei > msg.value) {
emit OrderInsufficientPayment(msg.sender, totalToBePayedWei, msg.value);
//Abort transaction!:
revert(); //Revert transaction, so Eth send are not transferred, and go back to user!
//TODO: IMPROVEMENTS!
//TODO: Improvements to allow a partial buy, if not possible to buy all!
}
//Confirm if next node exists:
if(offerNodeIndex != NULL) {
//Get Next Node (More Info):
offer = blackMarketOffersMap[offerNodeIndex];
//Check if next order is above the priceRatioLimit set by the buyer:
//When comparing ratios the smaller one will be the one with the greater ratio (cheaper price):
//if(offer.price > priceRatioLimit) {
if(offer.price < priceRatioLimit) {
//Abort buying more from the seller's market:
abort = true;
partial = true; //Partial buy order done! (no sufficient seller offer's below the priceRatioLimit)
//Maybe in the future, put the buyer offer in a buyer's offers list!
//TODO: IMPROVEMENTS!
}
}
else {
//Abort buying more from the seller's market (the end was reached!):
abort = true;
}
}
while (exists && quantity > 0 && !abort);
//End Cycle through orders!
//Final operations after checking all orders:
if(totalToBePayedWei < msg.value) {
//Give change back to the buyer:
//Return change to the buyer (sender of the message in this case)
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value - totalToBePayedWei); //SAFETY CHECK: No need to use safeSub, as we already know that "msg.value" > "totalToBePayedWei"!
emit ChangeToReceiveGotten(msg.sender, msg.value - totalToBePayedWei, changeToReturn[msg.sender]);
}
return (true, partial, numOrdersCleared);
}
// ------------------------------------------------------------------------
// Gets the list of orders on the black market (ordered by cheapest to expensive).
// ------------------------------------------------------------------------
function getSellOrdersBlackMarket() public view returns (uint[] memory r) {
r = new uint[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
uint size = blackMarketOffersSorted.sizeOf();
for (uint i = 0; i < size; i++) {
r[i] = elem;
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
}
// ------------------------------------------------------------------------
// Gets the list of orders on the black market (ordered by cheapest to expensive).
// WARNING: Not Supported by Remix or Web3!! (Structure Array returns)
// ------------------------------------------------------------------------
/*
function getSellOrdersBlackMarketComplete() public view returns (SellOffer[] memory r) {
r = new SellOffer[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
for (uint i = 0; i < blackMarketOffersSorted.sizeOf(); i++) {
SellOfferComplete storage offer = blackMarketOffersMap[elem];
r[i].quantity = offer.quantity;
r[i].price = offer.price;
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
}
*/
function getSellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices) {
quantities = new uint[](blackMarketOffersSorted.sizeOf());
prices = new uint[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
uint size = blackMarketOffersSorted.sizeOf();
for (uint i = 0; i < size; i++) {
SellOfferComplete storage offer = blackMarketOffersMap[elem];
quantities[i] = offer.quantity;
prices[i] = offer.price;
//Get next element:
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
}
function getMySellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices) {
quantities = new uint[](blackMarketOffersSorted.sizeOf());
prices = new uint[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
uint size = blackMarketOffersSorted.sizeOf();
uint j = 0;
for (uint i = 0; i < size; i++) {
SellOfferComplete storage offer = blackMarketOffersMap[elem];
if(offer.seller == msg.sender) {
quantities[j] = offer.quantity;
prices[j] = offer.price;
j++;
}
//Get next element:
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
//quantities.length = j; //Memory Arrays can't be returned with dynamic size, we have to create arrays with a fixed size to be returned!
//prices.length = j;
}
// ------------------------------------------------------------------------
// Puts an offer on the market to a specific user (if an offer from the same seller to the same consumer already exists, the latest offer will replace it)
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function sellToConsumer(address consumer, uint quantity, uint priceRatio) public whenNotPaused whenNotFlushing returns (bool success) {
require(consumer != address(0) && quantity > 0 && priceRatio > 0);
//Mark offer to sell to consumer on registry:
SellOffer storage offer = directOffers[msg.sender][consumer];
offer.quantity = quantity;
offer.price = priceRatio;
emit DirectOfferAvailable(msg.sender, consumer, offer.quantity, offer.price);
return true;
}
// ------------------------------------------------------------------------
// Puts an offer on the market to a specific user
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function cancelSellToConsumer(address consumer) public whenNotPaused returns (bool success) {
//Check if order exists with the correct values:
SellOffer memory sellOffer = directOffers[msg.sender][consumer];
if(sellOffer.quantity > 0 || sellOffer.price > 0) {
//We found matching sell to consumer, delete it to cancel it!
delete directOffers[msg.sender][consumer];
emit DirectOfferCancelled(msg.sender, consumer, sellOffer.quantity, sellOffer.price);
return true;
}
return false;
}
// ------------------------------------------------------------------------
// Checks a seller offer from the seller side
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function checkMySellerOffer(address consumer) public view returns (uint quantity, uint priceRatio, uint totalWeiCost) {
quantity = directOffers[msg.sender][consumer].quantity;
priceRatio = directOffers[msg.sender][consumer].price;
totalWeiCost = calculateEthValueFromTokens(quantity, priceRatio); //Value to be payed by the buyer (in Wei)
}
// ------------------------------------------------------------------------
// Checks a seller offer to the user. Method used by the buyer to check an offer (direct offer) from a seller to him/her and to see
// how much he/she will have to pay for it (in Wei).
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function checkSellerOffer(address seller) public view returns (uint quantity, uint priceRatio, uint totalWeiCost) {
quantity = directOffers[seller][msg.sender].quantity;
priceRatio = directOffers[seller][msg.sender].price;
totalWeiCost = calculateEthValueFromTokens(quantity, priceRatio); //Value to be payed by the buyer (in Wei)
}
// ------------------------------------------------------------------------
// Buys from a trusted dealer.
// The buyer has to send the needed Ether to pay for the quantity of material specified at that priceRatio (the buyer can use
// checkSellerOffer(), and input the seller address to know the quantity and priceRatio specified and also, of course, how much Ether in Wei
// he/she will have to pay for it).
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function buyFromTrusterDealer(address dealer, uint quantity, uint priceRatio) public payable noReentrancy whenNotPaused returns (bool success) {
//Check up on offer:
require(directOffers[dealer][msg.sender].quantity > 0 && directOffers[dealer][msg.sender].price > 0); //Offer exists?
if(quantity > directOffers[dealer][msg.sender].quantity) {
emit OrderQuantityMismatch(dealer, directOffers[dealer][msg.sender].quantity, quantity);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
if(directOffers[dealer][msg.sender].price != priceRatio) {
emit OrderPriceMismatch(dealer, directOffers[dealer][msg.sender].price, priceRatio);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
//Offer valid, start buying proccess:
//Get values to be payed:
uint weiToBePayed = calculateEthValueFromTokens(quantity, priceRatio);
//Check eth payment from buyer:
if(msg.value < weiToBePayed) {
emit OrderInsufficientPayment(msg.sender, weiToBePayed, msg.value);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
//Check balance from seller:
if(quantity > balances[dealer]) {
//Seller is missing funds: Abort order:
emit OrderInsufficientBalance(dealer, quantity, balances[dealer]);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
//Update balances of seller/buyer:
balances[dealer] = balances[dealer] - quantity; //SAFETY CHECK: No need to use safeSub, as we already know that "balances[dealer]" >= "quantity"!
balances[msg.sender] = safeAdd(balances[msg.sender], quantity);
emit Transfer(dealer, msg.sender, quantity);
//Update direct offers registry:
if(quantity < directOffers[dealer][msg.sender].quantity) {
//SAFETY CHECK: No need to use safeSub, as we already know that "directOffers[dealer][msg.sender].quantity" > "quantity"!
directOffers[dealer][msg.sender].quantity = directOffers[dealer][msg.sender].quantity - quantity;
}
else {
//Remove offer from registry (order completely filled)
delete directOffers[dealer][msg.sender];
}
//Receive payment from one user and send it to another, minus the comission:
//Calculate fees and values to distribute:
uint fee = safeDiv(weiToBePayed, directOffersComissionRatio);
uint valueForSeller = safeSub(weiToBePayed, fee);
//SAFETY CHECK: Possible Denial of Service, by putting a fallback function impossible to run: No problem! As this is a direct offer between two users, if it doesn't work the first time, the user can just ignore the offer!
//SAFETY CHECK: No Reentrancy possible: Modifier active!
//SAFETY CHECK: Balances are all updated before transfer, and offer is removed/updated too! Only change is updated later, which is good as user can only retrieve the funds after this operations finishes with success!
dealer.transfer(valueForSeller);
//Set change to the buyer if he sent extra eth:
uint changeToGive = safeSub(msg.value, weiToBePayed);
if(changeToGive > 0) {
//Update change values (user will have to retrieve the change calling method "retrieveChange" to receive the Eth)
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], changeToGive);
emit ChangeToReceiveGotten(msg.sender, changeToGive, changeToReturn[msg.sender]);
}
return true;
}
/****************************************************************************
// Message board management functions
//***************************************************************************/
// ------------------------------------------------------------------------
// Comparator used to compare Eth payed for a message inside the top messages LinkedList
// ------------------------------------------------------------------------
function greaterPriceMsgComparator(uint valuePayedNew, uint nodeNext) internal view returns (bool success) {
return valuePayedNew > (topMessagesMap[nodeNext].valuePayed);
}
// ------------------------------------------------------------------------
// Place a message in the Message Board
// The latest messages will be shown on the message board (usually it should display the 100 latest messages)
// User can also spend some wei to put the message in the top 10/20 of messages, ordered by the most payed to the least payed.
// ------------------------------------------------------------------------
function placeMessage(string message, bool anon) public payable whenNotPaused returns (bool success, uint numMsgTop) {
uint msgSize = bytes(message).length;
if(msgSize > maxCharactersMessage) { //Check number of bytes of message
//Message is bigger than maximum allowed: Reject message!
emit ExceededMaximumMessageSize(msgSize, maxCharactersMessage);
if(msg.value > 0) { //We have Eth to return, so we will return it!
revert(); //Cancel transaction and Return Eth!
}
return (false, 0);
}
//Insert message in the sorted list (from most to least expensive) of top messages
//If the value payed is enough for it to reach the top
//Find an offer that is cheaper:
//nodeLessExpensive =
uint nextSpot;
bool foundPosition;
uint sizeNow;
(nextSpot, foundPosition, sizeNow) = topMessagesSorted.getSortedSpotByFunction(HEAD, msg.value, NEXT, greaterPriceMsgComparator, maxMessagesTop);
if(foundPosition) {
//Create new Message:
uint newNodeNum = ++topMessagesCounter; //SAFETY CHECK: Doesn't matter if we cycle again from MAX_INT to 0, as we have only 10/20/100 maximum messages at a time, so there will never be some overwriting of valid offers!
topMessagesMap[newNodeNum].valuePayed = msg.value;
topMessagesMap[newNodeNum].msg = message;
topMessagesMap[newNodeNum].from = anon ? address(0) : msg.sender;
//Insert more expensive message before nextSpot:
topMessagesSorted.insert(nextSpot, newNodeNum, PREV);
if(int32(sizeNow) > maxMessagesTop) {
//Delete the tail element so we can keep the same number of max top messages:
uint lastIndex = topMessagesSorted.pop(PREV); //Pops and removes last element of the list!
delete topMessagesMap[lastIndex];
}
}
//Place message in the most recent messages (Will always be put here, even if the value payed is zero! Will only be ordered by time, from older to most recent):
insertMessage(message, anon);
emit NewMessageAvailable(anon ? address(0) : msg.sender, message);
return (true, newNodeNum);
}
function lengthMessages() internal view returns (uint) {
return (firstMsgGlobal > 0) ? messages.length : uint(lastMsgGlobal + 1);
}
function insertMessage(string message, bool anon) internal {
Message memory newMsg;
bool insertInLastPos = false;
newMsg.valuePayed = msg.value;
newMsg.msg = message;
newMsg.from = anon ? address(0) : msg.sender;
if(((lastMsgGlobal + 1) >= int32(messages.length) && int32(messages.length) < maxMessagesGlobal)) {
//Still have space in the messages array, add new message at the end:
messages.push(newMsg);
//lastMsgGlobal++;
} else {
//Messages array is full, start rotating through it:
insertInLastPos = true;
}
//Rotating indexes in case we reach the end of the array!
uint sizeMessages = lengthMessages(); //lengthMessages() depends on lastMsgGlobal, se we have to keep a temporary copy first!
lastMsgGlobal = (lastMsgGlobal + 1) % maxMessagesGlobal;
if(lastMsgGlobal <= firstMsgGlobal && sizeMessages > 0) {
firstMsgGlobal = (firstMsgGlobal + 1) % maxMessagesGlobal;
}
if(insertInLastPos) {
messages[uint(lastMsgGlobal)] = newMsg;
}
}
function strConcat(string _a, string _b, string _c) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory ab = new string(_ba.length + _bb.length + _bc.length);
bytes memory ba = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) ba[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) ba[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) ba[k++] = _bc[i];
return string(ba);
}
// ------------------------------------------------------------------------
// Place a message in the Message Board
// The latest messages will be shown on the message board (usually it should display the 100 latest messages)
// User can also spend some wei to put the message in the top 10/20 of messages, ordered by the most payed to the least payed.
// ------------------------------------------------------------------------
function getMessages() public view returns (string memory r) {
uint countMsg = lengthMessages(); //Take into account if messages was reset, and no new messages have been inserted until now!
uint indexMsg = uint(firstMsgGlobal);
bool first = true;
while(countMsg > 0) {
if(first) {
r = messages[indexMsg].msg;
first = false;
}
else {
r = strConcat(r, " <||> ", messages[indexMsg].msg);
}
indexMsg = (indexMsg + 1) % uint(maxMessagesGlobal);
countMsg--;
}
return r;
}
// ------------------------------------------------------------------------
// Will set the Maximum of Global Messages
// ------------------------------------------------------------------------
function setMaxMessagesGlobal(int32 _maxMessagesGlobal) public onlyOwner returns (bool success) {
if(_maxMessagesGlobal < maxMessagesGlobal) {
//New value will be shorter than old value: reset values:
//messages.clear(); //No need to clear the array completely (costs gas!): Just reinitialize the pointers!
//lastMsgGlobal = firstMsgGlobal > 0 ? int32(messages.length) - 1 : lastMsgGlobal; //The last position will specify the real size of the array, that is, until the firstMsgGlobal is greater than zero, at that time we know the array is full, so the real size is the size of the complete array!
lastMsgGlobal = int32(lengthMessages()) - 1; //The last position will specify the real size of the array, that is, until the firstMsgGlobal is greater than zero, at that time we know the array is full, so the real size is the size of the complete array!
if(lastMsgGlobal != -1 && lastMsgGlobal > (int32(_maxMessagesGlobal) - 1)) {
lastMsgGlobal = int32(_maxMessagesGlobal) - 1;
}
firstMsgGlobal = 0;
messages.length = uint(_maxMessagesGlobal);
}
maxMessagesGlobal = _maxMessagesGlobal;
return true;
}
// ------------------------------------------------------------------------
// Will set the Maximum of Top Messages (usually Top 10 / 20)
// ------------------------------------------------------------------------
function setMaxMessagesTop(int32 _maxMessagesTop) public onlyOwner returns (bool success) {
uint topMessagesSortedSize = topMessagesSorted.sizeOf();
if(topMessagesSortedSize > uint(_maxMessagesTop)) {
int32 diff = int32(topMessagesSortedSize - uint(_maxMessagesTop));
require(diff <= int32(topMessagesSortedSize)); //SAFETY CHECK (recommended because of type conversions)!
//Do the needed number of Pops to clear the top message list if _maxMessagesTop (new) < maxMessagesTop (old)
while (diff > 0) {
uint lastMsg = topMessagesSorted.pop(PREV); //Pops element from the Tail!
delete topMessagesMap[lastMsg];
diff--;
}
}
maxMessagesTop = _maxMessagesTop;
return true;
}
// ------------------------------------------------------------------------
// Gets the list of top 10 messages (ordered by most payed to least payed).
// ------------------------------------------------------------------------
function getTop10Messages() public view returns (string memory r) {
bool exists;
uint prev;
uint elem;
bool first = true;
(exists, prev, elem) = topMessagesSorted.getNode(HEAD);
if(exists) {
uint size = min(topMessagesSorted.sizeOf(), 10);
for (uint i = 0; i < size; i++) {
if(first) {
r = topMessagesMap[elem].msg;
first = false;
}
else {
r = strConcat(r, " <||> ", topMessagesMap[elem].msg);
}
(exists, elem) = topMessagesSorted.getAdjacent(elem, NEXT);
}
}
return r;
}
// ------------------------------------------------------------------------
// Gets the list of top 11 to 20 messages (ordered by most payed to least payed).
// ------------------------------------------------------------------------
function getTop11_20Messages() public view returns (string memory r) {
bool exists;
uint prev;
uint elem;
bool first = true;
(exists, prev, elem) = topMessagesSorted.getNode(HEAD);
if(exists) {
uint size = min(topMessagesSorted.sizeOf(), uint(maxMessagesTop));
for (uint i = 0; i < size; i++) {
if(i >= 10) {
if(first) {
r = topMessagesMap[elem].msg;
first = false;
}
else {
r = strConcat(r, " <||> ", topMessagesMap[elem].msg);
}
}
(exists, elem) = topMessagesSorted.getAdjacent(elem, NEXT);
}
}
return r;
}
// ------------------------------------------------------------------------
// Will set the Maximum Characters each message can have
// ------------------------------------------------------------------------
function setMessageMaxCharacters(uint _maxCharactersMessage) public onlyOwner returns (bool success) {
maxCharactersMessage = _maxCharactersMessage;
return true;
}
// ------------------------------------------------------------------------
// Get the Maximum Characters each message can have
// ------------------------------------------------------------------------
function getMessageMaxCharacters() public view returns (uint maxChars) {
return maxCharactersMessage;
}
// ------------------------------------------------------------------------
// Default function
// ------------------------------------------------------------------------
function () public payable {
buyCoke();
}
} | Update total to be payed (in Wei): | totalToBePayedWei = safeAdd(totalToBePayedWei, weiToBePayedRound);
| 620,775 | [
1,
1891,
2078,
358,
506,
8843,
329,
261,
267,
1660,
77,
4672,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
2078,
15360,
9148,
329,
3218,
77,
273,
4183,
986,
12,
4963,
15360,
9148,
329,
3218,
77,
16,
732,
77,
15360,
9148,
329,
11066,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0xf90bA889C8f993Fd625D05D8aB0459dbFE46C3FD/sources/contracts/fee-distribution/FeeDistributor.sol | * @notice Claims a number of tokens on behalf of a user. @dev A version of `claimToken` which supports claiming multiple `tokens` on behalf of `user`. See `claimToken` for more details. @param user - The user on behalf of which to claim. @param tokens - An array of ERC20 token addresses to be claimed. @return An array of the amounts of each token in `tokens` sent to `user` as a result of claiming./ | function claimTokens(address user, IERC20[] calldata tokens)
external
override
nonReentrant
optionalOnlyCaller(user)
returns (uint256[] memory)
{
_checkpointTotalSupply();
_checkpointUserBalance(user);
uint256 tokensLength = tokens.length;
uint256[] memory amounts = new uint256[](tokensLength);
for (uint256 i = 0; i < tokensLength; ++i) {
_checkpointToken(tokens[i], false);
amounts[i] = _claimToken(user, tokens[i]);
}
return amounts;
}
| 3,839,409 | [
1,
15925,
279,
1300,
434,
2430,
603,
12433,
6186,
434,
279,
729,
18,
225,
432,
1177,
434,
1375,
14784,
1345,
68,
1492,
6146,
7516,
310,
3229,
1375,
7860,
68,
603,
12433,
6186,
434,
1375,
1355,
8338,
2164,
1375,
14784,
1345,
68,
364,
1898,
3189,
18,
225,
729,
300,
1021,
729,
603,
12433,
6186,
434,
1492,
358,
7516,
18,
225,
2430,
300,
1922,
526,
434,
4232,
39,
3462,
1147,
6138,
358,
506,
7516,
329,
18,
327,
1922,
526,
434,
326,
30980,
434,
1517,
1147,
316,
1375,
7860,
68,
3271,
358,
1375,
1355,
68,
487,
279,
563,
434,
7516,
310,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
7516,
5157,
12,
2867,
729,
16,
467,
654,
39,
3462,
8526,
745,
892,
2430,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
3129,
3386,
11095,
12,
1355,
13,
203,
3639,
1135,
261,
11890,
5034,
8526,
3778,
13,
203,
565,
288,
203,
3639,
389,
25414,
5269,
3088,
1283,
5621,
203,
3639,
389,
25414,
1299,
13937,
12,
1355,
1769,
203,
203,
3639,
2254,
5034,
2430,
1782,
273,
2430,
18,
2469,
31,
203,
3639,
2254,
5034,
8526,
3778,
30980,
273,
394,
2254,
5034,
8526,
12,
7860,
1782,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2430,
1782,
31,
965,
77,
13,
288,
203,
5411,
389,
25414,
1345,
12,
7860,
63,
77,
6487,
629,
1769,
203,
5411,
30980,
63,
77,
65,
273,
389,
14784,
1345,
12,
1355,
16,
2430,
63,
77,
19226,
203,
3639,
289,
203,
203,
3639,
327,
30980,
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
]
|
./full_match/4/0x0642303fF6E8c87F6303eFe7000F65A520e4d21e/sources/browser/1115-factory.sol | map Token owner to ETH | mapping (address => uint) ethBalance;
| 12,423,419 | [
1,
1458,
3155,
3410,
358,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
6770,
261,
2867,
516,
2254,
13,
13750,
13937,
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
]
|
./full_match/80001/0xb57B2D20F774fd4b20CD6Df03754B69d0E7e629A/sources/contracts/StakeBoredomFactory.sol | * @dev Return the log in base 10, following the selected rounding direction, of a positive value. Returns 0 if given 0./ | function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
| 867,909 | [
1,
990,
326,
613,
316,
1026,
1728,
16,
3751,
326,
3170,
13885,
4068,
16,
434,
279,
6895,
460,
18,
2860,
374,
309,
864,
374,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
613,
2163,
12,
11890,
5034,
460,
16,
11370,
310,
13885,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
563,
273,
613,
2163,
12,
1132,
1769,
203,
5411,
327,
563,
397,
261,
17376,
422,
11370,
310,
18,
1211,
597,
1728,
2826,
563,
411,
460,
692,
404,
294,
374,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8B554aC5D96873702cFc44B4559625DCdDA2491b/sources/contracts/test.sol | require( amounts[amounts.length - 1] >= amountOutMin, "OUT_AMOUNT_INVALID" ); | function buyMoon(uint256 ethToSell, address[] calldata path)
external
onlyOwner
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "PATH_INVALID");
amounts = UniswapV2Library.getAmountsOut(factory, ethToSell, path);
assert(
IWETH(WETH).transfer(
UniswapV2Library.pairFor(factory, path[0], path[1]),
amounts[0]
)
);
_exchange(amounts, path);
}
| 9,566,155 | [
1,
6528,
12,
377,
30980,
63,
8949,
87,
18,
2469,
300,
404,
65,
1545,
3844,
1182,
2930,
16,
377,
315,
5069,
67,
2192,
51,
5321,
67,
9347,
6,
11272,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
30143,
16727,
265,
12,
11890,
5034,
13750,
774,
55,
1165,
16,
1758,
8526,
745,
892,
589,
13,
203,
3639,
3903,
203,
3639,
1338,
5541,
203,
3639,
1135,
261,
11890,
5034,
8526,
3778,
30980,
13,
203,
565,
288,
203,
3639,
2583,
12,
803,
63,
20,
65,
422,
678,
1584,
44,
16,
315,
4211,
67,
9347,
8863,
203,
203,
3639,
30980,
273,
1351,
291,
91,
438,
58,
22,
9313,
18,
588,
6275,
87,
1182,
12,
6848,
16,
13750,
774,
55,
1165,
16,
589,
1769,
203,
203,
3639,
1815,
12,
203,
5411,
467,
59,
1584,
44,
12,
59,
1584,
44,
2934,
13866,
12,
203,
7734,
1351,
291,
91,
438,
58,
22,
9313,
18,
6017,
1290,
12,
6848,
16,
589,
63,
20,
6487,
589,
63,
21,
65,
3631,
203,
7734,
30980,
63,
20,
65,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
389,
16641,
12,
8949,
87,
16,
589,
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
]
|
./partial_match/1/0x99143689FEA3E57ad55AbAB55Fc4Cc77A432706B/sources/PublicStakePool.sol | _withdrawReward(_msgSender()); withdraw any existing rewards | function stake(
uint256 amount
) external {
require(
"amount should be greater than 0"
);
require(
amount >= minimumAmount,
"amount too low"
);
require(
amount <= maximumAmount,
"amount too high"
);
require(
"#transferFrom failed"
);
Stake storage currentStake = userToStakes[_msgSender()];
currentStake.stakingPeriodEndTime = block.timestamp.add(
stakingDuration
.add(amount);
.add(amount);
emit Staked(
stakeToken,
_msgSender(),
amount
}
| 2,818,669 | [
1,
67,
1918,
9446,
17631,
1060,
24899,
3576,
12021,
10663,
225,
598,
9446,
1281,
2062,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
315,
8949,
1410,
506,
6802,
2353,
374,
6,
203,
3639,
11272,
203,
540,
203,
3639,
2583,
12,
203,
5411,
3844,
1545,
5224,
6275,
16,
203,
5411,
315,
8949,
4885,
4587,
6,
203,
3639,
11272,
203,
540,
203,
3639,
2583,
12,
203,
5411,
3844,
1648,
4207,
6275,
16,
203,
5411,
315,
8949,
4885,
3551,
6,
203,
3639,
11272,
203,
540,
203,
3639,
2583,
12,
203,
5411,
6619,
13866,
1265,
2535,
6,
203,
3639,
11272,
203,
540,
203,
203,
540,
203,
3639,
934,
911,
2502,
783,
510,
911,
273,
729,
774,
510,
3223,
63,
67,
3576,
12021,
1435,
15533,
203,
3639,
783,
510,
911,
18,
334,
6159,
5027,
25255,
273,
1203,
18,
5508,
18,
1289,
12,
203,
5411,
384,
6159,
5326,
203,
203,
5411,
263,
1289,
12,
8949,
1769,
203,
540,
203,
5411,
263,
1289,
12,
8949,
1769,
203,
203,
3639,
3626,
934,
9477,
12,
203,
5411,
384,
911,
1345,
16,
203,
5411,
389,
3576,
12021,
9334,
203,
5411,
3844,
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
]
|
./partial_match/3/0xa39155B39bDeBacFFEC7142205E2a7E50e524Eb9/sources/Marathon.sol | Tạo ngẫu nhiên thời gian chạy của vận động viên nếu hoàn thành cự li | function updateQuangDuong(uint _sttVDV,uint _quangduong) public
{
vdvs[_sttVDV].quangduong=_quangduong;
if (_quangduong==vdvs[_sttVDV].culi)
{
if (vdvs[_sttVDV].culi==25)
{
nonce=100;
randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 200;
randomnumber = randomnumber + 80;
vdvs[_sttVDV].thoigianchay=randomnumber;
}
else
if (vdvs[_sttVDV].culi==50)
{
nonce=100;
randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 200;
randomnumber = randomnumber + 80;
vdvs[_sttVDV].thoigianchay=randomnumber;
}
else
if (vdvs[_sttVDV].culi==75)
{
nonce=100;
randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 200;
randomnumber = randomnumber + 80;
vdvs[_sttVDV].thoigianchay=randomnumber;
}
else
{
nonce=100;
randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 200;
randomnumber = randomnumber + 80;
vdvs[_sttVDV].thoigianchay=randomnumber;
}
}
}
| 5,187,929 | [
1,
56,
162,
123,
99,
83,
10944,
162,
123,
109,
89,
290,
12266,
132,
108,
82,
286,
162,
124,
256,
77,
314,
2779,
462,
162,
123,
99,
93,
276,
162,
124,
105,
69,
331,
162,
123,
260,
82,
225,
133,
244,
162,
124,
252,
3368,
13206,
132,
108,
82,
290,
162,
123,
128,
89,
26025,
132,
259,
82,
286,
132,
259,
82,
76,
276,
162,
124,
114,
4501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
928,
539,
40,
89,
932,
12,
11890,
389,
334,
88,
21544,
58,
16,
11890,
389,
372,
539,
2544,
932,
13,
1071,
203,
565,
288,
203,
3639,
21161,
6904,
63,
67,
334,
88,
21544,
58,
8009,
372,
539,
2544,
932,
33,
67,
372,
539,
2544,
932,
31,
203,
3639,
309,
261,
67,
372,
539,
2544,
932,
631,
16115,
6904,
63,
67,
334,
88,
21544,
58,
8009,
1934,
77,
13,
203,
3639,
288,
203,
3639,
309,
261,
16115,
6904,
63,
67,
334,
88,
21544,
58,
8009,
1934,
77,
631,
2947,
13,
203,
5411,
288,
203,
7734,
7448,
33,
6625,
31,
203,
7734,
2744,
2696,
273,
2254,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3338,
16,
1234,
18,
15330,
16,
7448,
20349,
738,
4044,
31,
203,
7734,
2744,
2696,
273,
2744,
2696,
397,
8958,
31,
203,
7734,
21161,
6904,
63,
67,
334,
88,
21544,
58,
8009,
451,
83,
360,
2779,
343,
528,
33,
9188,
2696,
31,
203,
5411,
289,
203,
5411,
469,
203,
5411,
309,
261,
16115,
6904,
63,
67,
334,
88,
21544,
58,
8009,
1934,
77,
631,
3361,
13,
203,
7734,
288,
203,
10792,
7448,
33,
6625,
31,
203,
10792,
2744,
2696,
273,
2254,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3338,
16,
1234,
18,
15330,
16,
7448,
20349,
738,
4044,
31,
203,
10792,
2744,
2696,
273,
2744,
2696,
397,
8958,
31,
203,
10792,
21161,
6904,
63,
67,
334,
88,
21544,
58,
8009,
451,
83,
360,
2779,
343,
528,
33,
9188,
2696,
31,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import {LibDiamond} from "../../shared/libraries/LibDiamond.sol";
import {LibMeta} from "../../shared/libraries/LibMeta.sol";
import {ILink} from "../interfaces/ILink.sol";
//import "../interfaces/IERC20.sol";
// import "hardhat/console.sol";
uint256 constant EQUIPPED_WEARABLE_SLOTS = 16;
uint256 constant NUMERIC_TRAITS_NUM = 6;
uint256 constant TRAIT_BONUSES_NUM = 5;
uint256 constant PORTAL_AAVEGOTCHIS_NUM = 10;
// switch (traitType) {
// case 0:
// return energy(value);
// case 1:
// return aggressiveness(value);
// case 2:
// return spookiness(value);
// case 3:
// return brain(value);
// case 4:
// return eyeShape(value);
// case 5:
// return eyeColor(value);
struct Aavegotchi {
uint16[EQUIPPED_WEARABLE_SLOTS] equippedWearables; //The currently equipped wearables of the Aavegotchi
// [Experience, Rarity Score, Kinship, Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
int8[NUMERIC_TRAITS_NUM] temporaryTraitBoosts;
int16[NUMERIC_TRAITS_NUM] numericTraits; // Sixteen 16 bit ints. [Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
string name;
uint256 randomNumber;
uint256 experience; //How much XP this Aavegotchi has accrued. Begins at 0.
uint256 minimumStake; //The minimum amount of collateral that must be staked. Set upon creation.
uint256 usedSkillPoints; //The number of skill points this aavegotchi has already used
uint256 interactionCount; //How many times the owner of this Aavegotchi has interacted with it.
address collateralType;
uint40 claimTime; //The block timestamp when this Aavegotchi was claimed
uint40 lastTemporaryBoost;
uint16 hauntId;
address owner;
uint8 status; // 0 == portal, 1 == VRF_PENDING, 2 == open portal, 3 == Aavegotchi
uint40 lastInteracted; //The last time this Aavegotchi was interacted with
bool locked;
address escrow; //The escrow address this Aavegotchi manages.
}
struct Dimensions {
uint8 x;
uint8 y;
uint8 width;
uint8 height;
}
struct ItemType {
string name; //The name of the item
string description;
string author;
// treated as int8s array
// [Experience, Rarity Score, Kinship, Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
int8[NUMERIC_TRAITS_NUM] traitModifiers; //[WEARABLE ONLY] How much the wearable modifies each trait. Should not be more than +-5 total
//[WEARABLE ONLY] The slots that this wearable can be added to.
bool[EQUIPPED_WEARABLE_SLOTS] slotPositions;
// this is an array of uint indexes into the collateralTypes array
uint8[] allowedCollaterals; //[WEARABLE ONLY] The collaterals this wearable can be equipped to. An empty array is "any"
// SVG x,y,width,height
Dimensions dimensions;
uint256 ghstPrice; //How much GHST this item costs
uint256 maxQuantity; //Total number that can be minted of this item.
uint256 totalQuantity; //The total quantity of this item minted so far
uint32 svgId; //The svgId of the item
uint8 rarityScoreModifier; //Number from 1-50.
// Each bit is a slot position. 1 is true, 0 is false
bool canPurchaseWithGhst;
uint16 minLevel; //The minimum Aavegotchi level required to use this item. Default is 1.
bool canBeTransferred;
uint8 category; // 0 is wearable, 1 is badge, 2 is consumable
int16 kinshipBonus; //[CONSUMABLE ONLY] How much this consumable boosts (or reduces) kinship score
uint32 experienceBonus; //[CONSUMABLE ONLY]
}
struct WearableSet {
string name;
uint8[] allowedCollaterals;
uint16[] wearableIds; // The tokenIdS of each piece of the set
int8[TRAIT_BONUSES_NUM] traitsBonuses;
}
struct Haunt {
uint256 hauntMaxSize; //The max size of the Haunt
uint256 portalPrice;
bytes3 bodyColor;
uint24 totalCount;
}
struct SvgLayer {
address svgLayersContract;
uint16 offset;
uint16 size;
}
struct AavegotchiCollateralTypeInfo {
// treated as an arary of int8
int16[NUMERIC_TRAITS_NUM] modifiers; //Trait modifiers for each collateral. Can be 2, 1, -1, or -2
bytes3 primaryColor;
bytes3 secondaryColor;
bytes3 cheekColor;
uint8 svgId;
uint8 eyeShapeSvgId;
uint16 conversionRate; //Current conversionRate for the price of this collateral in relation to 1 USD. Can be updated by the DAO
bool delisted;
}
struct ERC1155Listing {
uint256 listingId;
address seller;
address erc1155TokenAddress;
uint256 erc1155TypeId;
uint256 category; // 0 is wearable, 1 is badge, 2 is consumable, 3 is tickets
uint256 quantity;
uint256 priceInWei;
uint256 timeCreated;
uint256 timeLastPurchased;
uint256 sourceListingId;
bool sold;
bool cancelled;
}
struct ERC721Listing {
uint256 listingId;
address seller;
address erc721TokenAddress;
uint256 erc721TokenId;
uint256 category; // 0 is closed portal, 1 is vrf pending, 2 is open portal, 3 is Aavegotchi
uint256 priceInWei;
uint256 timeCreated;
uint256 timePurchased;
bool cancelled;
}
struct ListingListItem {
uint256 parentListingId;
uint256 listingId;
uint256 childListingId;
}
struct AppStorage {
mapping(address => AavegotchiCollateralTypeInfo) collateralTypeInfo;
mapping(address => uint256) collateralTypeIndexes;
mapping(bytes32 => SvgLayer[]) svgLayers;
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) nftItemBalances;
mapping(address => mapping(uint256 => uint256[])) nftItems;
// indexes are stored 1 higher so that 0 means no items in items array
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) nftItemIndexes;
ItemType[] itemTypes;
WearableSet[] wearableSets;
mapping(uint256 => Haunt) haunts;
mapping(address => mapping(uint256 => uint256)) ownerItemBalances;
mapping(address => uint256[]) ownerItems;
// indexes are stored 1 higher so that 0 means no items in items array
mapping(address => mapping(uint256 => uint256)) ownerItemIndexes;
mapping(uint256 => uint256) tokenIdToRandomNumber;
mapping(uint256 => Aavegotchi) aavegotchis;
mapping(address => uint32[]) ownerTokenIds;
mapping(address => mapping(uint256 => uint256)) ownerTokenIdIndexes;
uint32[] tokenIds;
mapping(uint256 => uint256) tokenIdIndexes;
mapping(address => mapping(address => bool)) operators;
mapping(uint256 => address) approved;
mapping(string => bool) aavegotchiNamesUsed;
mapping(address => uint256) metaNonces;
uint32 tokenIdCounter;
uint16 currentHauntId;
string name;
string symbol;
//Addresses
address[] collateralTypes;
address ghstContract;
address childChainManager;
address gameManager;
address dao;
address daoTreasury;
address pixelCraft;
address rarityFarming;
string itemsBaseUri;
bytes32 domainSeparator;
//VRF
mapping(bytes32 => uint256) vrfRequestIdToTokenId;
mapping(bytes32 => uint256) vrfNonces;
bytes32 keyHash;
uint144 fee;
address vrfCoordinator;
ILink link;
// Marketplace
uint256 nextERC1155ListingId;
// erc1155 category => erc1155Order
//ERC1155Order[] erc1155MarketOrders;
mapping(uint256 => ERC1155Listing) erc1155Listings;
// category => ("listed" or purchased => first listingId)
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(uint256 => mapping(string => uint256)) erc1155ListingHead;
// "listed" or purchased => (listingId => ListingListItem)
mapping(string => mapping(uint256 => ListingListItem)) erc1155ListingListItem;
mapping(address => mapping(uint256 => mapping(string => uint256))) erc1155OwnerListingHead;
// "listed" or purchased => (listingId => ListingListItem)
mapping(string => mapping(uint256 => ListingListItem)) erc1155OwnerListingListItem;
mapping(address => mapping(uint256 => mapping(address => uint256))) erc1155TokenToListingId;
uint256 listingFeeInWei;
// erc1155Token => (erc1155TypeId => category)
mapping(address => mapping(uint256 => uint256)) erc1155Categories;
uint256 nextERC721ListingId;
//ERC1155Order[] erc1155MarketOrders;
mapping(uint256 => ERC721Listing) erc721Listings;
// listingId => ListingListItem
mapping(uint256 => ListingListItem) erc721ListingListItem;
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(uint256 => mapping(string => uint256)) erc721ListingHead;
// user address => category => sort => listingId => ListingListItem
mapping(uint256 => ListingListItem) erc721OwnerListingListItem;
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(address => mapping(uint256 => mapping(string => uint256))) erc721OwnerListingHead;
// erc1155Token => (erc1155TypeId => category)
// not really in use now, for the future
mapping(address => mapping(uint256 => uint256)) erc721Categories;
// erc721 token address, erc721 tokenId, user address => listingId
mapping(address => mapping(uint256 => mapping(address => uint256))) erc721TokenToListingId;
// body wearableId => sleevesId
mapping(uint256 => uint256) sleeves;
// mapping(address => mapping(uint256 => address)) petOperators;
// mapping(address => uint256[]) petOperatorTokenIds;
mapping(address => bool) petters;
}
library LibAppStorage {
function diamondStorage() internal pure returns (AppStorage storage ds) {
assembly {
ds.slot := 0
}
}
function abs(int256 x) internal pure returns (uint256) {
return uint256(x >= 0 ? x : -x);
}
}
contract Modifiers {
AppStorage internal s;
modifier onlyAavegotchiOwner(uint256 _tokenId) {
require(LibMeta.msgSender() == s.aavegotchis[_tokenId].owner, "LibAppStorage: Only aavegotchi owner can call this function");
_;
}
modifier onlyUnlocked(uint256 _tokenId) {
require(s.aavegotchis[_tokenId].locked == false, "LibAppStorage: Only callable on unlocked Aavegotchis");
_;
}
modifier onlyOwner {
LibDiamond.enforceIsContractOwner();
_;
}
modifier onlyDao {
address sender = LibMeta.msgSender();
require(sender == s.dao, "Only DAO can call this function");
_;
}
modifier onlyDaoOrOwner {
address sender = LibMeta.msgSender();
require(sender == s.dao || sender == LibDiamond.contractOwner(), "LibAppStorage: Do not have access");
_;
}
modifier onlyOwnerOrDaoOrGameManager {
address sender = LibMeta.msgSender();
require(sender == s.dao || sender == LibDiamond.contractOwner() || sender == s.gameManager, "LibAppStorage: Do not have access");
_;
}
}
| The escrow address this Aavegotchi manages.
| address escrow; | 1,780,323 | [
1,
1986,
2904,
492,
1758,
333,
432,
836,
13212,
24010,
20754,
281,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1758,
2904,
492,
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
]
|
pragma solidity ^0.4.23;
import "../AppProxyFactory.sol";
import "./PinnedProxy.sol";
contract PinnedProxyFactory is AppProxyFactory {
/**
* @dev Creates a new PinnedProxy proxy
* @param _version representing the first version to be set for the proxy
* @return address of the new proxy created
*/
function create(bytes32 _version, address _implementation, bytes _contentURI) public payable returns (ERCProxy) {
PinnedProxy proxy = new PinnedProxy(_version, _implementation, _contentURI);
_init(proxy, true);
return proxy;
}
}
| * @dev Creates a new PinnedProxy proxy @param _version representing the first version to be set for the proxy @return address of the new proxy created/ | function create(bytes32 _version, address _implementation, bytes _contentURI) public payable returns (ERCProxy) {
PinnedProxy proxy = new PinnedProxy(_version, _implementation, _contentURI);
_init(proxy, true);
return proxy;
}
| 12,992,316 | [
1,
2729,
279,
394,
14999,
11748,
3886,
2889,
225,
389,
1589,
5123,
326,
1122,
1177,
358,
506,
444,
364,
326,
2889,
327,
1758,
434,
326,
394,
2889,
2522,
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,
225,
445,
752,
12,
3890,
1578,
389,
1589,
16,
1758,
389,
30810,
16,
1731,
389,
1745,
3098,
13,
1071,
8843,
429,
1135,
261,
654,
39,
3886,
13,
288,
203,
565,
14999,
11748,
3886,
2889,
273,
394,
14999,
11748,
3886,
24899,
1589,
16,
389,
30810,
16,
389,
1745,
3098,
1769,
203,
565,
389,
2738,
12,
5656,
16,
638,
1769,
203,
565,
327,
2889,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Sources flattened with hardhat v2.6.4 https://hardhat.org
// File openzeppelin-solidity/contracts/utils/[email protected]
// 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;
}
}
// File openzeppelin-solidity/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File openzeppelin-solidity/contracts/utils/cryptography/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File contracts/ArpeggiGenesisFinal.sol
pragma solidity >=0.8.0 <0.9.0;
// Arpeggi Studio Genesis is the first on-chain music creation platform. All data and instructions to recreate your Arpeggi song reside on the Ethereum blockchain.
//
// To recreate your song, you will need to retrieve two compressed files from the chain: "samples" and "scripts".
//
// STEPS TO RETRIEVE "samples":
// - The mp3 samples to play your song have been packaged together as a single compressed file, split into pieces, and stored in transaction data on-chain.
// - Make a new file on your local, 'samples.hex,' to piece together the samples hex data gathered from the contract.
// - Query the contract for the sampleCount - this is the number of pieces of the samples file. You will need all of them.
// - Pass in the sampleCount starting with 0 into the _samples read method of the ArpeggiStudioGenesis contract, this is will return a transaction hash.
// - Use the transaction hash to find the sample transaction on Etherscan.
// - Copy the "Input Data" field of this the transaction to the end of your local 'samples.hex' file, removing the leading 0x at the beggining of the input data.
// - Repeat the last three steps, incrementing the sampleConut in the _samples read method and appending to the end of your local file data until you have copied all the sample data.
// - Convert the local file from hex to binary using a command line tool. Example command: xxd -r -p samples.hex > samples.zip
// - Follow the instructions to retrieve the scripts below.
//
// STEPS TO RETRIEVE "scripts":
// - The song player script is written in JavaScript, split into pieces, and stored on chain.
// - Make a new file on your local, 'scripts.hex' to piece together the script hex data gathered from the contract
// - Query the contract for the scriptCount - this is the number of pieces of the player script. It's likely to be one transaction.
// - Pass in the scriptCount starting with 0 into the _scripts read method of the ArpeggiStudioGenesis contract, this is will return a transaction hash.
// - Use the transaction hash to find the script transaction on Etherscan
// - Copy the "Input Data" field of this the transaction to your local 'scripts.hex' file, removing the leading 0x at the beggining of the input data.
// - Repeat these last three steps, incrementing the scriptCount in the _scripts method and appending to the end of your local file data until you have copied all the script data.
// - Convert the local file from hex to binary using a command line tool. Example command: xxd -r -p scripts.hex > scripts.zip
//
// PLAYING YOUR SONG:
// - Extract the scripts and the samples files. This is all of the data required to play your song.
// - Follow the instructions in the scripts/README file to play your song!
contract ArpeggiStudioGenesis is
ERC721,
Ownable
{
////////////////// STRUCT //////////////////
/**
* @dev Struct for Pass and Song
*/
struct Pass {
string title;
string artist;
bytes composition;
uint mintTime;
address artistAddress;
}
////////////////// CONSTANTS //////////////////
uint256 public constant MAX_PASSES = 600;
uint256 public constant PRESALE_MINT_PRICE = 0.25 ether;
uint256 public constant GENERAL_MINT_PRICE = 0.3 ether;
/**
* @dev Max number of Passes that the contract owner can mint.
*/
uint256 public constant CREATORS_NUM_PASSES = 64;
/**
* @dev Max number of Passes that the contract owner can mint.
*/
uint256 public constant DEVELOPERS_NUM_PASSES = 24;
////////////////// STORAGE //////////////////
uint256 public _numMinted = 0;
/**
* @dev Custom pause functionality for Creator/Developer Reserve Mint
*/
bool private _paused = true;
bool public _onlyEarlyAccess = true;
address public immutable CREATORS_RESERVE;
address public immutable DEVELOPERS_RESERVE;
/**
* @dev Base URL for external_url metadata field.
*/
string private _basePassExternalUrl = "http://www.arpeggi.io/metadata/pass/";
/**
* @dev Base URL for external_url metadata field.
*/
string private _baseSongExternalUrl = "http://www.arpeggi.io/metadata/song/";
/**
* @dev All existing Passes.
*/
mapping(uint256 => Pass) public _passes;
/**
* @dev Addresses with early minting access.
*/
mapping(address => bool) private _earlyAccess;
/**
* @dev For setting scripts. When locked it is irreversible.
*/
bool private _locked = false;
/**
* @dev The scripts used to render a composition from a token
*/
mapping (uint256 => string) public _scripts;
uint256 public scriptCount = 0;
/**
* @dev The samples used to play a song
*/
mapping (uint256 => string) public _samples;
uint256 public sampleCount = 0;
////////////////// CONSTRUCTOR //////////////////
constructor(
address creatorsReserve,
address developersReserve
)
ERC721(
"Arpeggi Genesis Studio Pass",
"ARPEGGI"
)
{
CREATORS_RESERVE = creatorsReserve;
DEVELOPERS_RESERVE = developersReserve;
}
////////////////// MODIFIERS //////////////////
/**
* @dev Modifier to make a function callable only when the contract is not paused.
* Contract must not be paused
*/
modifier whenNotPaused() {
require(!isPaused(), "Paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
* Contract must be paused.
*/
modifier whenPaused() {
require(isPaused(), "Paused");
_;
}
/**
* @dev Lock functionality to lock scripts/samples after uploading
*/
modifier onlyUnlocked() {
require(!_locked, "Contract is locked");
_;
}
////////////////// EXTERNAL ONLY-OWNER FUNCTIONS //////////////////
/**
* @dev Returns to unpaused state. The contract must be paused.
*/
function unpause()
external
onlyOwner
whenPaused
{
_paused = false;
}
/**
* @dev Function to lock on-chain scripts and samples
*/
function setLocked()
external
onlyOwner
onlyUnlocked
{
_locked = true;
}
/**
* @dev Add a new section of the script
* @param script String value of script or pointer
*/
function addScript(
string memory script
)
external
onlyOwner
onlyUnlocked
{
_scripts[scriptCount] = script;
scriptCount++;
}
/**
* @dev Overwrite a script section at a particular index
* @param script String value of script or pointer
* @param index Index of the script to replace
*/
function updateScript(
string memory script,
uint256 index
)
external
onlyOwner
onlyUnlocked
{
require(index < scriptCount, "Index out of bounds");
_scripts[index] = script;
}
/**
* @dev Reset script index to zero, caller must be owner and the contract unlocked
*/
function resetScriptCount()
external
onlyOwner
onlyUnlocked
{
scriptCount = 0;
}
/**
* @dev Add a new section of the sample
* @param sample String value of sample or pointer
*/
function addSample(
string memory sample
)
external
onlyOwner
onlyUnlocked
{
_samples[sampleCount] = sample;
sampleCount++;
}
/**
* @dev Reset sample index to zero, caller must be owner and the contract unlocked
*/
function resetSampleCount()
external
onlyOwner
onlyUnlocked
{
sampleCount = 0;
}
/**
* @dev Set the _onlyEarlyAccess flag.
*/
function setOnlyEarlyAccess(
bool to
)
external
onlyOwner
{
_onlyEarlyAccess = to;
}
/**
* @dev Set early-access granting or revocation for the addresses. eg. ["0x12345"]
*/
function setEarlyAccessGrants(
address[] calldata addresses,
bool hasAccess
)
external
onlyOwner
{
for (uint i = 0; i < addresses.length; i++) {
_earlyAccess[addresses[i]] = hasAccess;
}
}
/**
* @dev Allocate passes to Arpeggi Creators Reserve wallet
*/
function mintCreatorsReserve()
external
onlyOwner
whenPaused
{
for (uint i=0; i < CREATORS_NUM_PASSES; i++) {
_mintToken(CREATORS_RESERVE);
}
}
/**
* @dev Allocate passes to Arpeggi Creators Reserve wallet
*/
function mintDevelopersReserve()
external
onlyOwner
whenPaused
{
for (uint i=0; i < DEVELOPERS_NUM_PASSES; i++) {
_mintToken(DEVELOPERS_RESERVE);
}
}
/**
* @dev Withdraw funds from contract to owner
*/
function withdraw() public onlyOwner {
payable(owner()).transfer(address(this).balance);
}
////////////////// EXTERNAL FUNCTIONS //////////////////
/**
* @dev Mint a lab pass
*/
function mint()
external
payable
whenNotPaused
{
require(_numMinted < MAX_PASSES, "No More Passes Left");
require(
(_onlyEarlyAccess && PRESALE_MINT_PRICE == msg.value) || (!_onlyEarlyAccess && GENERAL_MINT_PRICE == msg.value),
"Incorrect Ether value.");
require(!_isContract(msg.sender), "Can't mint from a contract smh");
require(
!_onlyEarlyAccess || _earlyAccess[msg.sender],
"You are not approved for presale"
);
_mintToken(msg.sender);
if (_onlyEarlyAccess) {
_earlyAccess[msg.sender] = false;
}
}
function pressSong(
uint256 _tokenId,
bytes calldata _composition,
string calldata _title,
string calldata _artist
)
external
whenNotPaused
{
require(_isApprovedOrOwner(_msgSender(), _tokenId));
require(_passes[_tokenId].mintTime == 0, "Your Studio Pass has already been used");
_pressSongToken(msg.sender, _tokenId, _title, _artist, _composition);
}
////////////////// PUBLIC ONLY-OWNER FUNCTIONS //////////////////
/**
* @dev Set the base URL for external_url metadata field.
*/
function setBasePassExternalUrl(
string memory url
)
public
onlyOwner
{
_basePassExternalUrl = url;
}
/**
* @dev Set the base URL for external_url metadata field.
*/
function setBaseSongExternalUrl(
string memory url
)
public
onlyOwner
{
_baseSongExternalUrl = url;
}
////////////////// PUBLIC FUNCTIONS //////////////////
/**
* @dev Returns data URI of token metadata.
*/
function tokenURI(
uint256 _tokenId
)
public
override
view
returns (string memory)
{
if (_passes[_tokenId].mintTime == 0) {
return string(abi.encodePacked(_basePassExternalUrl, Strings.toString(_tokenId)));
}
else {
return string(abi.encodePacked(_baseSongExternalUrl, Strings.toString(_tokenId)));
}
}
/**
* @dev Checks an address to see if it has early access
*/
function hasEarlyAccess(address _address) public view returns (bool) {
return _earlyAccess[_address] == true;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function isPaused()
public
view
returns (bool)
{
return _paused;
}
////////////////// INTERNAL FUNCTIONS //////////////////
function _mintToken(
address _to
)
internal
{
_numMinted++;
_safeMint(_to, _numMinted);
}
function _pressSongToken(
address _artistAddress,
uint256 _tokenId,
string calldata _title,
string calldata _artist,
bytes calldata _composition
)
internal
returns(uint256 _songToken)
{
_passes[_tokenId].title = _title;
_passes[_tokenId].artist = _artist;
_passes[_tokenId].composition = _composition;
_passes[_tokenId].mintTime = block.timestamp;
_passes[_tokenId].artistAddress = _artistAddress;
return _tokenId;
}
/**
* @dev Function to check if an address is a contract for minting
*/
function _isContract(
address _addr
)
internal
view
returns (bool)
{
uint32 _size;
assembly {
_size:= extcodesize(_addr)
}
return (_size > 0);
}
} | * @dev Checks an address to see if it has early access/ | function hasEarlyAccess(address _address) public view returns (bool) {
return _earlyAccess[_address] == true;
}
| 14,709,615 | [
1,
4081,
392,
1758,
358,
2621,
309,
518,
711,
11646,
2006,
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,
711,
41,
20279,
1862,
12,
2867,
389,
2867,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
2091,
715,
1862,
63,
67,
2867,
65,
422,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0xD15e7599C8E12516ACfebFfB66393f2e7588d819/sources/browser/tests/4_Ballot_test.sol | * Change safeguard status on or off When safeguard is true, then all the non-owner functions will stop working. When safeguard is false, then all the functions will resume working back again!/ | function changeSafeguardStatus() onlyOwner public{
if (safeGuard == false){
safeGuard = true;
}
else{
safeGuard = false;
}
}
| 808,488 | [
1,
3043,
11029,
1332,
89,
1060,
1267,
603,
578,
3397,
5203,
11029,
1332,
89,
1060,
353,
638,
16,
1508,
777,
326,
1661,
17,
8443,
4186,
903,
2132,
5960,
18,
5203,
11029,
1332,
89,
1060,
353,
629,
16,
1508,
777,
326,
4186,
903,
10774,
5960,
1473,
3382,
5,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2549,
26946,
1332,
89,
1060,
1482,
1435,
1338,
5541,
1071,
95,
203,
3639,
309,
261,
4626,
16709,
422,
629,
15329,
203,
5411,
4183,
16709,
273,
638,
31,
203,
3639,
289,
203,
3639,
469,
95,
203,
5411,
4183,
16709,
273,
629,
31,
377,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0x963178bE123906DFB0EE1BBaA3441bFc27E48326/sources/contracts/FREther.sol | * @notice Sender redeems cTokens in exchange for the underlying asset @dev Accrues interest whether or not the operation succeeds, unless reverted @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function redeem(uint supplyId) external returns (uint) {
return redeemInternal(supplyId);
}
| 16,272,139 | [
1,
12021,
283,
323,
7424,
276,
5157,
316,
7829,
364,
326,
6808,
3310,
225,
15980,
86,
3610,
16513,
2856,
578,
486,
326,
1674,
21933,
16,
3308,
15226,
329,
327,
2254,
374,
33,
4768,
16,
3541,
279,
5166,
261,
5946,
1068,
13289,
18,
18281,
364,
3189,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
283,
24903,
12,
11890,
14467,
548,
13,
3903,
1135,
261,
11890,
13,
288,
203,
3639,
327,
283,
24903,
3061,
12,
2859,
1283,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.7;
import "../strategy-sushi-farm-base.sol";
contract StrategySushiEthWBtcLp is StrategySushiFarmBase {
// Token/ETH pool id in MasterChef contract
uint256 public sushi_wbtc_poolId = 21;
// Token addresses
address public sushi_eth_wbtc_lp = 0xCEfF51756c56CeFFCA006cD410B03FFC46dd3a58;
address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
constructor(
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategySushiFarmBase(
wbtc,
sushi_wbtc_poolId,
sushi_eth_wbtc_lp,
_governance,
_strategist,
_controller,
_timelock
)
{}
// **** Views ****
function getName() external override pure returns (string memory) {
return "StrategySushiEthWBtcLp";
}
}
| Token/ETH pool id in MasterChef contract Token addresses **** Views **** | contract StrategySushiEthWBtcLp is StrategySushiFarmBase {
uint256 public sushi_wbtc_poolId = 21;
address public sushi_eth_wbtc_lp = 0xCEfF51756c56CeFFCA006cD410B03FFC46dd3a58;
address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
constructor(
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategySushiFarmBase(
wbtc,
sushi_wbtc_poolId,
sushi_eth_wbtc_lp,
_governance,
_strategist,
_controller,
_timelock
)
pragma solidity ^0.6.7;
{}
function getName() external override pure returns (string memory) {
return "StrategySushiEthWBtcLp";
}
}
| 12,691,204 | [
1,
1345,
19,
1584,
44,
2845,
612,
316,
13453,
39,
580,
74,
6835,
3155,
6138,
225,
31117,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
19736,
55,
1218,
77,
41,
451,
59,
38,
5111,
48,
84,
353,
19736,
55,
1218,
77,
42,
4610,
2171,
288,
203,
565,
2254,
5034,
1071,
272,
1218,
77,
67,
9464,
5111,
67,
6011,
548,
273,
9035,
31,
203,
565,
1758,
1071,
272,
1218,
77,
67,
546,
67,
9464,
5111,
67,
9953,
273,
374,
92,
1441,
74,
42,
25,
4033,
4313,
71,
4313,
39,
73,
2246,
3587,
713,
26,
71,
40,
24,
2163,
38,
4630,
2246,
39,
8749,
449,
23,
69,
8204,
31,
203,
565,
1758,
1071,
17298,
5111,
273,
374,
92,
3787,
4848,
2046,
39,
25,
41,
2539,
9452,
69,
4700,
23,
37,
69,
6334,
74,
16283,
3030,
40,
74,
27,
39,
3657,
23,
13459,
22,
39,
25,
2733,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
75,
1643,
82,
1359,
16,
203,
3639,
1758,
389,
701,
1287,
376,
16,
203,
3639,
1758,
389,
5723,
16,
203,
3639,
1758,
389,
8584,
292,
975,
203,
565,
262,
203,
3639,
1071,
203,
3639,
19736,
55,
1218,
77,
42,
4610,
2171,
12,
203,
5411,
17298,
5111,
16,
203,
5411,
272,
1218,
77,
67,
9464,
5111,
67,
6011,
548,
16,
203,
5411,
272,
1218,
77,
67,
546,
67,
9464,
5111,
67,
9953,
16,
203,
5411,
389,
75,
1643,
82,
1359,
16,
203,
5411,
389,
701,
1287,
376,
16,
203,
5411,
389,
5723,
16,
203,
5411,
389,
8584,
292,
975,
203,
3639,
262,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
27,
31,
203,
565,
2618,
203,
565,
445,
1723,
1435,
3903,
2
]
|
pragma solidity 0.4.24;
import "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "zeppelin-solidity/contracts/lifecycle/Pausable.sol";
contract ShopinToken is StandardToken, Ownable, Pausable {
using SafeMath for uint256;
string public constant name = "Shopin Token"; // solium-disable-line uppercase
string public constant symbol = "SHOPIN"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
mapping (address => bool) whitelist;
mapping (address => bool) blacklist;
uint private unlockTime;
event AddedToWhitelist(address indexed _addr);
event RemovedFromWhitelist(address indexed _addr);
event AddedToBlacklist(address indexed _addr);
event RemovedFromBlacklist(address indexed _addr);
event SetNewUnlockTime(uint newUnlockTime);
constructor(
uint256 _totalSupply,
uint256 _unlockTime
)
Ownable()
public
{
require(_totalSupply > 0);
require(_unlockTime > 0 && _unlockTime > now);
totalSupply_ = _totalSupply;
unlockTime = _unlockTime;
balances[msg.sender] = totalSupply_;
emit Transfer(0x0, msg.sender, totalSupply_);
}
modifier whenNotPausedOrInWhitelist() {
require(
!paused || isWhitelisted(msg.sender) || msg.sender == owner,
"contract paused and sender is not in whitelist"
);
_;
}
/**
* @dev Transfer a token to a specified address
* transfer
*
* transfer conditions:
* - the msg.sender address must be valid
* - the msg.sender _cannot_ be on the blacklist
* - one of the three conditions can be met:
* - the token contract is unlocked entirely
* - the msg.sender is whitelisted
* - the msg.sender is the owner of the contract
*
* @param _to address to transfer to
* @param _value amount to transfer
*/
function transfer(
address _to,
uint _value
)
public
whenNotPausedOrInWhitelist()
returns (bool)
{
require(_to != address(0));
require(msg.sender != address(0));
require(!isBlacklisted(msg.sender));
require(isUnlocked() ||
isWhitelisted(msg.sender) ||
msg.sender == owner);
return super.transfer(_to, _value);
}
/**
* @dev addToBlacklist
* @param _addr the address to add the blacklist
*/
function addToBlacklist(
address _addr
) onlyOwner public returns (bool) {
require(_addr != address(0));
require(!isBlacklisted(_addr));
blacklist[_addr] = true;
emit AddedToBlacklist(_addr);
return true;
}
/**
* @dev remove from blacklist
* @param _addr the address to remove from the blacklist
*/
function removeFromBlacklist(
address _addr
) onlyOwner public returns (bool) {
require(_addr != address(0));
require(isBlacklisted(_addr));
blacklist[_addr] = false;
emit RemovedFromBlacklist(_addr);
return true;
}
/**
* @dev addToWhitelist
* @param _addr the address to add to the whitelist
*/
function addToWhitelist(
address _addr
) onlyOwner public returns (bool) {
require(_addr != address(0));
require(!isWhitelisted(_addr));
whitelist[_addr] = true;
emit AddedToWhitelist(_addr);
return true;
}
/**
* @dev remove an address from the whitelist
* @param _addr address to remove from whitelist
*/
function removeFromWhitelist(
address _addr
) onlyOwner public returns (bool) {
require(_addr != address(0));
require(isWhitelisted(_addr));
whitelist[_addr] = false;
emit RemovedFromWhitelist(_addr);
return true;
}
function isBlacklisted(address _addr)
internal
view
returns (bool)
{
require(_addr != address(0));
return blacklist[_addr];
}
/**
* @dev isWhitelisted check if an address is on whitelist
* @param _addr address to check if on whitelist
*/
function isWhitelisted(address _addr)
internal
view
returns (bool)
{
require(_addr != address(0));
return whitelist[_addr];
}
/**
* @dev get the unlock time
*/
function getUnlockTime() public view returns (uint) {
return unlockTime;
}
/**
* @dev set a new unlock time
*/
function setUnlockTime(uint newUnlockTime) onlyOwner public returns (bool)
{
unlockTime = newUnlockTime;
emit SetNewUnlockTime(unlockTime);
}
/**
* @dev is the contract unlocked or not
*/
function isUnlocked() public view returns (bool) {
return (getUnlockTime() >= now);
}
}
| * @dev addToBlacklist @param _addr the address to add the blacklist/ | function addToBlacklist(
address _addr
) onlyOwner public returns (bool) {
require(_addr != address(0));
require(!isBlacklisted(_addr));
blacklist[_addr] = true;
emit AddedToBlacklist(_addr);
return true;
}
| 952,303 | [
1,
1289,
774,
25811,
225,
389,
4793,
326,
1758,
358,
527,
326,
11709,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9604,
25811,
12,
203,
3639,
1758,
389,
4793,
203,
565,
262,
1338,
5541,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
4793,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
5,
291,
13155,
18647,
24899,
4793,
10019,
203,
203,
3639,
11709,
63,
67,
4793,
65,
273,
638,
31,
203,
3639,
3626,
25808,
774,
25811,
24899,
4793,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x395434d252B0a4510cff10299bfe8D3489D0508B/sources/project_/contracts/InitialStableCoinDeclaration.sol | @notice the function reduces the amount to the required decimals @param _amount amount of token you want to reduce @param _amountDecimals decimals which amount has now @param _decimalsToUse decimals you want to get after scaling @return uint256 the scaled amount with proper decimals | function _scaleAmount(
uint256 _amount,
uint8 _amountDecimals,
uint8 _decimalsToUse
) internal pure returns (uint256) {
if (_amountDecimals < _decimalsToUse) {
return _amount * (10 ** uint256(_decimalsToUse - _amountDecimals));
return _amount / (10 ** uint256(_amountDecimals - _decimalsToUse));
}
return _amount;
}
| 874,279 | [
1,
5787,
445,
30568,
326,
3844,
358,
326,
1931,
15105,
225,
389,
8949,
3844,
434,
1147,
1846,
2545,
358,
5459,
225,
389,
8949,
31809,
15105,
1492,
3844,
711,
2037,
225,
389,
31734,
18762,
15105,
1846,
2545,
358,
336,
1839,
10612,
327,
2254,
5034,
326,
12304,
3844,
598,
5338,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
5864,
6275,
12,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
2254,
28,
389,
8949,
31809,
16,
203,
3639,
2254,
28,
389,
31734,
18762,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
67,
8949,
31809,
411,
389,
31734,
18762,
13,
288,
203,
5411,
327,
389,
8949,
380,
261,
2163,
2826,
2254,
5034,
24899,
31734,
18762,
300,
389,
8949,
31809,
10019,
203,
5411,
327,
389,
8949,
342,
261,
2163,
2826,
2254,
5034,
24899,
8949,
31809,
300,
389,
31734,
18762,
10019,
203,
3639,
289,
203,
3639,
327,
389,
8949,
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
]
|
// File: contracts/openzeppelin/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "hardhat/console.sol";
import "./CommonIERC20.sol";
abstract contract Burnable {
function burn(uint256 amount) public virtual;
function symbol() public pure virtual returns (string memory);
function burn(address holder, uint256 amount) public virtual;
}
contract ScarcityLite is CommonIERC20 {
event Mint(address sender, address recipient, uint256 value);
event Burn(uint256 value);
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
struct BurnConfig {
uint256 transferFee; // percentage expressed as number betewen 1 and 1000
uint256 burnFee; // percentage expressed as number betewen 1 and 1000
address feeDestination;
}
BurnConfig public config;
function configureScarcity(
uint256 transferFee,
uint256 burnFee,
address feeDestination
) public {
require(config.transferFee + config.burnFee < 1000);
config.transferFee = transferFee;
config.burnFee = burnFee;
config.feeDestination = feeDestination;
}
function getConfiguration()
public
view
returns (
uint256,
uint256,
address
)
{
return (config.transferFee, config.burnFee, config.feeDestination);
}
function name() public pure returns (string memory) {
return "Scarcity";
}
function symbol() public pure returns (string memory) {
return "SCX";
}
function decimals() public pure override returns (uint8) {
return 18;
}
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender] - (amount));
return true;
}
function burn(uint256 value) external returns (bool) {
burn(msg.sender, value);
return true;
}
function burn(address holder, uint256 value) internal {
balances[holder] = balances[holder] - value;
_totalSupply = _totalSupply - value;
emit Burn(value);
}
function mint(address recipient, uint256 value) internal {
balances[recipient] = balances[recipient] + (value);
_totalSupply = _totalSupply + (value);
emit Mint(msg.sender, recipient, value);
}
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);
}
//outside of Behodler, Scarcity transfer incurs a fee.
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "Scarcity: transfer from the zero address");
require(recipient != address(0), "Scarcity: transfer to the zero address");
uint256 feeComponent = (config.transferFee * amount) / (1000);
// console.log("transferFee %s, amount %s, feeComponent %s", config.transferFee, amount, feeComponent);
uint256 burnComponent = (config.burnFee * amount) / (1000);
_totalSupply = _totalSupply - burnComponent;
emit Burn(burnComponent);
balances[config.feeDestination] = balances[config.feeDestination] + (feeComponent);
balances[sender] = balances[sender] - (amount);
balances[recipient] = balances[recipient] + (amount - (feeComponent + burnComponent));
emit Transfer(sender, recipient, amount);
}
function applyBurnFee(
address token,
uint256 amount,
bool proxyBurn
) internal returns (uint256) {
uint256 burnAmount = (config.burnFee * amount) / (1000);
Burnable bToken = Burnable(token);
if (proxyBurn) {
bToken.burn(address(this), burnAmount);
} else {
bToken.burn(burnAmount);
}
return burnAmount;
}
}
library AddressBalanceCheck {
function tokenBalance(address token) public view returns (uint256) {
return CommonIERC20(token).balanceOf(address(this));
}
function shiftedBalance(address token, uint256 factor) public view returns (uint256) {
return CommonIERC20(token).balanceOf(address(this)) / factor;
}
function transferIn(
address token,
address sender,
uint256 value
) public {
CommonIERC20(token).transferFrom(sender, address(this), value);
}
function transferOut(
address token,
address recipient,
uint256 value
) public {
CommonIERC20(token).transfer(recipient, value);
}
}
library ABDK {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(uint128(x << 64));
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2(uint256 x) internal pure returns (uint256) {
require(x > 0);
uint256 msb = 0;
uint256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
uint256 result = (msb - 64) << 64;
uint256 ux = uint256(x) << uint256(127 - msb);
for (uint256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * b;
}
return result;
}
}
contract StubLiquidityReceiver {}
contract LachesisLite {
struct tokenConfig {
bool valid;
bool burnable;
}
address public behodler;
mapping(address => tokenConfig) private config;
function cut(address token) public view returns (bool, bool) {
tokenConfig memory parameters = config[token];
return (parameters.valid, parameters.burnable);
}
function measure(
address token,
bool valid,
bool burnable
) public {
_measure(token, valid, burnable);
}
function _measure(
address token,
bool valid,
bool burnable
) internal {
config[token] = tokenConfig({valid: valid, burnable: burnable});
}
function setBehodler(address b) public {
behodler = b;
}
function updateBehodler(address token) public {
(bool valid, bool burnable) = cut(token);
BehodlerLite(behodler).setValidToken(token, valid, burnable);
BehodlerLite(behodler).setTokenBurnable(token, burnable);
}
}
contract BehodlerLite is ScarcityLite {
using ABDK for int128;
using ABDK for uint256;
using AddressBalanceCheck for address;
mapping(address => bool) validTokens;
struct PrecisionFactors {
uint8 swapPrecisionFactor;
uint8 maxLiquidityExit; //percentage as number between 1 and 100
}
address receiver;
address lachesis;
PrecisionFactors safetyParameters;
address tokenDumper;
constructor() {
receiver = address(new StubLiquidityReceiver());
safetyParameters.swapPrecisionFactor = 30; //approximately a billion
safetyParameters.maxLiquidityExit = 90;
tokenDumper = msg.sender;
}
function setLachesis(address l) public {
lachesis = l;
}
function setValidToken(
address token,
bool valid,
bool burnable
) public {
require(msg.sender == lachesis);
validTokens[token] = valid;
tokenBurnable[token] = burnable;
}
modifier onlyValidToken(address token) {
if (!validTokens[token]) console.log("invalid token %s", token);
require(lachesis == address(0) || validTokens[token], "BehodlerLite: tokenInvalid");
_;
}
function setReceiver(address newReceiver) public {
receiver = newReceiver;
}
function setSafetParameters(uint8 swapPrecisionFactor, uint8 maxLiquidityExit) external {
safetyParameters.swapPrecisionFactor = swapPrecisionFactor;
safetyParameters.maxLiquidityExit = maxLiquidityExit;
}
//Logarithmic growth can get quite flat beyond the first chunk. We divide input amounts by
uint256 public constant MIN_LIQUIDITY = 1e12;
mapping(address => bool) public tokenBurnable;
function setTokenBurnable(address token, bool burnable) public {
tokenBurnable[token] = burnable;
}
mapping(address => bool) public whiteListUsers; // can trade on tokens that are disabled
function swap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
) external payable onlyValidToken(inputToken) returns (bool success) {
uint256 initialInputBalance = inputToken.tokenBalance();
inputToken.transferIn(msg.sender, inputAmount);
uint256 netInputAmount = inputAmount - burnToken(inputToken, inputAmount);
uint256 initialOutputBalance = outputToken.tokenBalance();
require(
(outputAmount * 100) / initialOutputBalance <= safetyParameters.maxLiquidityExit,
"BEHODLER: liquidity withdrawal too large."
);
uint256 finalInputBalance = initialInputBalance + (netInputAmount);
uint256 finalOutputBalance = initialOutputBalance - (outputAmount);
//new scope to avoid stack too deep errors.
{
//if the input balance after adding input liquidity is 1073741824 bigger than the initial balance, we revert.
uint256 inputRatio = (initialInputBalance << safetyParameters.swapPrecisionFactor) / finalInputBalance;
uint256 outputRatio = (finalOutputBalance << safetyParameters.swapPrecisionFactor) / initialOutputBalance;
require(inputRatio != 0 && inputRatio == outputRatio, "BEHODLER: swap invariant.");
}
require(finalOutputBalance >= MIN_LIQUIDITY, "BEHODLER: min liquidity.");
outputToken.transferOut(msg.sender, outputAmount);
success = true;
}
function addLiquidity(address inputToken, uint256 amount)
external
payable
onlyValidToken(inputToken)
returns (uint256 deltaSCX)
{
uint256 initialBalance = uint256(int256(inputToken.shiftedBalance(MIN_LIQUIDITY).fromUInt()));
inputToken.transferIn(msg.sender, amount);
uint256 netInputAmount = uint256(int256(((amount - burnToken(inputToken, amount)) / MIN_LIQUIDITY).fromUInt()));
uint256 finalBalance = uint256(initialBalance + netInputAmount);
require(uint256(finalBalance) >= MIN_LIQUIDITY, "BEHODLER: min liquidity.");
deltaSCX = uint256(finalBalance.log_2() - (initialBalance > 1 ? initialBalance.log_2() : 0));
mint(msg.sender, deltaSCX);
}
/*
ΔSCX = log(InitialBalance) - log(FinalBalance)
tokensToRelease = InitialBalance -FinalBalance
=>FinalBalance = InitialBalance - tokensToRelease
Then apply logs and deduct SCX from msg.sender
The choice of base for the log isn't relevant from a mathematical point of view
but from a computational point of view, base 2 is the cheapest for obvious reasons.
"From my point of view, the Jedi are evil" - Darth Vader
*/
function withdrawLiquidity(address outputToken, uint256 tokensToRelease)
external
payable
onlyValidToken(outputToken)
returns (uint256 deltaSCX)
{
uint256 initialBalance = outputToken.tokenBalance();
uint256 finalBalance = initialBalance - tokensToRelease;
require(finalBalance > MIN_LIQUIDITY, "BEHODLER: min liquidity");
require(
(tokensToRelease * 100) / initialBalance <= safetyParameters.maxLiquidityExit,
"BEHODLER: liquidity withdrawal too large."
);
uint256 logInitial = initialBalance.log_2();
uint256 logFinal = finalBalance.log_2();
deltaSCX = logInitial - (finalBalance > 1 ? logFinal : 0);
uint256 scxBalance = balances[msg.sender];
if (deltaSCX > scxBalance) {
//rounding errors in scx creation and destruction. Err on the side of holders
uint256 difference = deltaSCX - scxBalance;
if ((difference * 10000) / deltaSCX == 0) deltaSCX = scxBalance;
}
burn(msg.sender, deltaSCX);
outputToken.transferOut(msg.sender, tokensToRelease);
}
/*
ΔSCX = log(InitialBalance) - log(FinalBalance)
tokensToRelease = InitialBalance -FinalBalance
=>FinalBalance = InitialBalance - tokensToRelease
Then apply logs and deduct SCX from msg.sender
The choice of base for the log isn't relevant from a mathematical point of view
but from a computational point of view, base 2 is the cheapest for obvious reasons.
"From my point of view, the Jedi are evil" - Darth Vader
*/
function withdrawLiquidityFindSCX(
address outputToken,
uint256 tokensToRelease,
uint256 scx,
uint256 passes
) external view returns (uint256) {
uint256 upperBoundary = outputToken.tokenBalance();
uint256 lowerBoundary = 0;
for (uint256 i = 0; i < passes; i++) {
uint256 initialBalance = outputToken.tokenBalance();
uint256 finalBalance = initialBalance - tokensToRelease;
uint256 logInitial = initialBalance.log_2();
uint256 logFinal = finalBalance.log_2();
int256 deltaSCX = int256(logInitial - (finalBalance > 1 ? logFinal : 0));
int256 difference = int256(scx) - deltaSCX;
// if (difference**2 < 1000000) return tokensToRelease;
if (difference == 0) return tokensToRelease;
if (difference < 0) {
// too many tokens requested
upperBoundary = tokensToRelease - 1;
} else {
//too few tokens requested
lowerBoundary = tokensToRelease + 1;
}
tokensToRelease = ((upperBoundary - lowerBoundary) / 2) + lowerBoundary; //bitshift
tokensToRelease = tokensToRelease > initialBalance ? initialBalance : tokensToRelease;
}
return tokensToRelease;
}
function burnToken(address token, uint256 amount) private returns (uint256 burnt) {
if (tokenBurnable[token]) {
burnt = applyBurnFee(token, amount, false);
} else {
burnt = (config.burnFee * amount) / (1000);
token.transferOut(receiver, burnt);
}
}
//just for allowing repeat limbo migrations
function dumpTokens(address token) public {
require(msg.sender == tokenDumper, "Only token dumper can dump tokens.");
uint balance = CommonIERC20(token).balanceOf(address(this));
CommonIERC20(token).transfer(msg.sender,balance);
}
}
| approximately a billion
| safetyParameters.swapPrecisionFactor = 30; | 12,943,933 | [
1,
26742,
381,
5173,
279,
20714,
285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
24179,
2402,
18,
22270,
15410,
6837,
273,
5196,
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
]
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPermissions.sol";
import "../token/IRusd.sol";
/// @title Core Interface
/// @author Ring Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event RusdUpdate(address indexed _rusd);
event RingUpdate(address indexed _ring);
event GenesisGroupUpdate(address indexed _genesisGroup);
event RingAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setRusd(address token) external;
function setRing(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateRing(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
/// @title Permissions interface
/// @author Ring Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[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.
*/
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./SafeMathCopy.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
/// @title generic oracle interface for Ring Protocol
/// @author Ring Protocol
interface IOracle {
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "./UniswapPCVDeposit.sol";
/// @title implementation for an ETH Uniswap LP PCV Deposit
/// @author Ring Protocol
contract ERC20UniswapPCVDeposit is UniswapPCVDeposit {
using Address for address payable;
using SafeCast for uint256;
/// @notice ETH Uniswap PCV Deposit constructor
/// @param _core Ring Core for reference
/// @param _pool Uniswap V3 Pool to deposit to
/// @param _nft Uniswap V3 position manager to reference
/// @param _router Uniswap Router
/// @param _oracle oracle for reference
constructor(
address _core,
address _pool,
address _nft,
address _router,
address _oracle,
int24 _tickLower,
int24 _tickUpper
) UniswapPCVDeposit(_core, _pool, _nft, _router, _oracle) {
tickLower = _tickLower;
tickUpper = _tickUpper;
}
/// @notice deposit tokens into the PCV allocation
function deposit() external payable override whenNotPaused {
uint256 erc20AmountBalance = IERC20(token()).balanceOf(address(this)); // include any ERC20 dust from prior LP
uint256 rusdAmount = _getAmountRusdToDeposit(erc20AmountBalance);
_addLiquidity(erc20AmountBalance, rusdAmount);
_burnRusdHeld(); // burn any RUSD dust from LP
emit Deposit(msg.sender, erc20AmountBalance);
}
/// @notice collect fee income
function collect() public override whenNotPaused returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = nft.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: address(this),
amount0Max: uint128(-1),
amount1Max: uint128(-1)
})
);
emit Collect(address(this), amount0, amount1);
}
function _removeLiquidity(uint128 liquidity) internal override {
uint256 endOfTime = uint256(-1);
nft.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: tokenId,
liquidity: liquidity,
amount0Min: 0,
amount1Min: 0,
deadline: endOfTime
})
);
collect();
}
function _transferWithdrawn(address to) internal override {
uint256 balance = IERC20(token()).balanceOf(address(this));
TransferHelper.safeTransfer(token(), to, balance);
}
function _addLiquidity(uint256 erc20Amount, uint256 rusdAmount) internal {
_mintRusd(rusdAmount);
uint256 endOfTime = uint256(-1);
address rusdAddress = address(rusd());
address tokenAddress = token();
(address token0, address token1) = rusdAddress < tokenAddress ? (rusdAddress, tokenAddress) : (tokenAddress, rusdAddress);
(uint256 amount0Desired, uint256 amount1Desired) = rusdAddress < tokenAddress ? (rusdAmount, erc20Amount) : (erc20Amount, rusdAmount);
if (tokenId == 0) {
(tokenId, , ,) = nft.mint(
INonfungiblePositionManager.MintParams({
token0: token0,
token1: token1,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
amount0Min: 0,
amount1Min: 0,
recipient: address(this),
deadline: endOfTime,
fee: fee
})
);
} else {
if (amount0Desired > 0 || amount1Desired > 0) {
nft.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: tokenId,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
amount0Min: 0,
amount1Min: 0,
deadline: endOfTime
})
);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title a PCV Deposit interface
/// @author Ring Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Collect(address indexed _from, uint256 _amount0, uint256 _amount1);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external payable;
function collect() external returns (uint256 amount0, uint256 amount1);
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function totalLiquidity() external view returns (uint128);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "./IPCVDeposit.sol";
import "../refs/UniRef.sol";
/// @title abstract implementation for Uniswap LP PCV Deposit
/// @author Ring Protocol
abstract contract UniswapPCVDeposit is IPCVDeposit, UniRef {
using Decimal for Decimal.D256;
using SafeCast for uint256;
uint24 public override fee = 500;
int24 public override tickLower;
int24 public override tickUpper;
/// @notice Uniswap PCV Deposit constructor
/// @param _core Ring Core for reference
/// @param _pool Uniswap Pair to deposit to
/// @param _nft Uniswap V3 position manager to reference
/// @param _router Uniswap Router
/// @param _oracle oracle for reference
constructor(
address _core,
address _pool,
address _nft,
address _router,
address _oracle
) UniRef(_core, _pool, _nft, _router, _oracle) {}
/// @notice withdraw tokens from the PCV allocation
/// @param amountLiquidity withdrawn
/// @param to the address to send PCV to
function withdraw(address to, uint256 amountLiquidity)
external
override
onlyPCVController
whenNotPaused
{
require(
amountLiquidity <= liquidityOwned(),
"UniswapPCVDeposit: Insufficient underlying"
);
_removeLiquidity(amountLiquidity.toUint128());
_transferWithdrawn(to);
_burnRusdHeld();
emit Withdrawal(msg.sender, to, amountLiquidity);
}
/// @notice burn old position and reset parameters of new position
/// @param _fee of new position
/// @param _tickLower of new position
/// @param _tickUpper of new position
function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper)
external
override
onlyPCVController
whenNotPaused
{
nft.burn(tokenId);
tokenId = 0;
fee = _fee;
tickLower = _tickLower;
tickUpper = _tickUpper;
}
/// @notice returns total value of PCV in the Deposit
function totalLiquidity() public view override returns (uint128) {
return liquidityOwned();
}
function _getAmountRusdToDeposit(uint256 amountToken)
internal
view
returns (uint256 amountRusd)
{
return peg().mul(amountToken).asUint256();
}
function _removeLiquidity(uint128 liquidity) internal virtual;
function _transferWithdrawn(address to) internal virtual;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A Reference to Core
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param newCore Ring Core to reference
constructor(address newCore) {
_core = ICore(newCore);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyRusd() {
require(msg.sender == address(rusd()), "CoreRef: Caller is not RUSD");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param _newCore the new core address
function setCore(address _newCore) external override onlyGovernor {
_core = ICore(_newCore);
emit CoreUpdate(_newCore);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Rusd contract referenced by Core
/// @return IRusd implementation address
function rusd() public view override returns (IRusd) {
return _core.rusd();
}
/// @notice address of the Ring contract referenced by Core
/// @return IERC20 implementation address
function ring() public view override returns (IERC20) {
return _core.ring();
}
/// @notice rusd balance of contract
/// @return rusd amount held
function rusdBalance() public view override returns (uint256) {
return rusd().balanceOf(address(this));
}
/// @notice ring balance of contract
/// @return ring amount held
function ringBalance() public view override returns (uint256) {
return ring().balanceOf(address(this));
}
function _burnRusdHeld() internal {
rusd().burn(rusdBalance());
}
function _mintRusd(uint256 amount) internal {
rusd().mint(address(this), amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Ring Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address _newCore) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function rusdBalance() external view returns (uint256);
function ringBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Ring Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- Governor only state changing API -----------
function setOracle(address _oracle) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function peg() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
/// @title UniRef interface
/// @author Ring Protocol
interface IUniRef {
// ----------- Events -----------
event PoolUpdate(address indexed _pool);
// ----------- Governor only state changing api -----------
function setPool(address _pool) external;
// ----------- Getters -----------
function nft() external view returns (INonfungiblePositionManager);
function router() external view returns (ISwapRouter);
function pool() external view returns (IUniswapV3Pool);
function tokenId() external view returns (uint256);
function token() external view returns (address);
function liquidityOwned() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IOracleRef.sol";
import "./CoreRef.sol";
/// @title Reference to an Oracle
/// @author Ring Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Ring Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) CoreRef(_core) {
_setOracle(_oracle);
}
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per RUSD
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as RUSD per X with X being ETH, dollars, etc
function peg() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
emit OracleUpdate(_oracle);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "./OracleRef.sol";
import "./IUniRef.sol";
/// @title A Reference to Uniswap
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Uniswap
/// @dev the uniswap v3 pool should be RUSD and another asset
abstract contract UniRef is IUniRef, OracleRef {
using Decimal for Decimal.D256;
using SafeMathCopy for uint256;
using SafeMathCopy for uint160;
uint256 private constant FIXED_POINT_GRANULARITY = 2**96;
/// @notice the Uniswap V3 position manager
INonfungiblePositionManager public override nft;
/// @notice the Uniswap router contract
ISwapRouter public override router;
/// @notice the referenced Uniswap V3 pool contract
IUniswapV3Pool public override pool;
/// @notice the referenced Uniswap V3 pool position id
uint256 public override tokenId;
/// @notice UniRef constructor
/// @param _core Ring Core to reference
/// @param _pool Uniswap V3 pool to reference
/// @param _nft Uniswap V3 position manager to reference
/// @param _router Uniswap Router to reference
/// @param _oracle oracle to reference
constructor(
address _core,
address _pool,
address _nft,
address _router,
address _oracle
) OracleRef(_core, _oracle) {
_setupPool(_pool);
nft = INonfungiblePositionManager(_nft);
router = ISwapRouter(_router);
_approveTokenToRouter(address(rusd()));
_approveTokenToRouter(token());
_approveTokenToNFT(address(rusd()));
_approveTokenToNFT(token());
}
/// @notice set the new pool contract
/// @param _pool the new pool
/// @dev also approves the router for the new pool token and underlying token
function setPool(address _pool) external override onlyGovernor {
_setupPool(_pool);
_approveTokenToRouter(token());
_approveTokenToNFT(token());
}
/// @notice the address of the non-rusd underlying token
function token() public view override returns (address) {
address token0 = pool.token0();
if (address(rusd()) == token0) {
return pool.token1();
}
return token0;
}
/// @notice amount of pool liquidity owned by this contract
/// @return amount of liquidity
function liquidityOwned() public view override returns (uint128) {
(, , , , , , , uint128 liquidity, , , , ) = nft.positions(tokenId);
return liquidity;
}
/// @notice returns true if price is below the peg
/// @dev counterintuitively checks if peg < price because price is reported as RUSD per X
function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) {
Decimal.D256 memory price = _getUniswapPrice();
return peg.lessThan(price);
}
/// @notice approves a token for the router
function _approveTokenToRouter(address _token) internal {
uint256 maxTokens = uint256(-1);
TransferHelper.safeApprove(_token, address(router), maxTokens);
}
/// @notice approves a token for the position manager
function _approveTokenToNFT(address _token) internal {
uint256 maxTokens = uint256(-1);
TransferHelper.safeApprove(_token, address(nft), maxTokens);
}
function _setupPool(address _pool) internal {
pool = IUniswapV3Pool(_pool);
emit PoolUpdate(_pool);
}
/// @notice get uniswap price
/// @return price reported as Rusd per X
function _getUniswapPrice()
internal
view
returns (Decimal.D256 memory)
{
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
if (token() < address(rusd())) {
return Decimal.ratio(sqrtPriceX96, FIXED_POINT_GRANULARITY).pow(2);
} else {
return Decimal.ratio(FIXED_POINT_GRANULARITY, sqrtPriceX96).pow(2);
}
}
/// @notice return current percent distance from peg
/// @dev will return Decimal.zero() if above peg
function _getDistanceToPeg()
internal
view
returns (Decimal.D256 memory distance)
{
Decimal.D256 memory price = _getUniswapPrice();
return _deviationBelowPeg(price, peg());
}
/// @notice get deviation from peg as a percent given price
/// @dev will return Decimal.zero() if above peg
function _deviationBelowPeg(
Decimal.D256 memory price,
Decimal.D256 memory peg
) internal pure returns (Decimal.D256 memory) {
// If price <= peg, then RUSD is more expensive and above peg
// In this case we can just return zero for deviation
if (price.lessThanOrEqualTo(peg)) {
return Decimal.zero();
}
Decimal.D256 memory delta = price.sub(peg, "Impossible underflow");
return delta.div(peg);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title RUSD stablecoin interface
/// @author Ring Protocol
interface IRusd is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address incentive) external;
// ----------- Getters -----------
function incentiveContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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 Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: GPL-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.5.0;
/// @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;
}
// 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 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 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.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 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 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.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @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;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @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;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @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);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @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;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @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);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
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);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
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});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
| @notice collect fee income | function collect() public override whenNotPaused returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = nft.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: address(this),
amount0Max: uint128(-1),
amount1Max: uint128(-1)
})
);
emit Collect(address(this), amount0, amount1);
}
| 10,058,255 | [
1,
14676,
14036,
316,
5624,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3274,
1435,
1071,
3849,
1347,
1248,
28590,
1135,
261,
11890,
5034,
3844,
20,
16,
2254,
5034,
3844,
21,
13,
288,
203,
3639,
261,
8949,
20,
16,
3844,
21,
13,
273,
290,
1222,
18,
14676,
12,
203,
5411,
2120,
265,
12125,
75,
1523,
2555,
1318,
18,
10808,
1370,
12590,
203,
7734,
1147,
548,
30,
1147,
548,
16,
203,
7734,
8027,
30,
1758,
12,
2211,
3631,
203,
7734,
3844,
20,
2747,
30,
2254,
10392,
19236,
21,
3631,
203,
7734,
3844,
21,
2747,
30,
2254,
10392,
19236,
21,
13,
203,
5411,
289,
13,
203,
3639,
11272,
203,
203,
3639,
3626,
9302,
12,
2867,
12,
2211,
3631,
3844,
20,
16,
3844,
21,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/10/0x02bD0b89F7b198014425Df1a4152A2E77576c38D/sources/src/abstract/BaseTrigger.sol | @notice The Sets that use this trigger in a market. @dev Use this function to retrieve all Sets. | function getSets() public view returns(ISet[] memory) {
return sets;
}
| 3,778,144 | [
1,
1986,
11511,
716,
999,
333,
3080,
316,
279,
13667,
18,
225,
2672,
333,
445,
358,
4614,
777,
11511,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
336,
2785,
1435,
1071,
1476,
1135,
12,
45,
694,
8526,
3778,
13,
288,
203,
565,
327,
1678,
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,
-100
]
|
pragma solidity ^0.6.0;
import "../common/IERC20.sol";
import "../common/SafeMath.sol";
import "../common/SafeERC20.sol";
import "../common/Context.sol";
// RewardDistribution is an abstract contract
// responsible for stake rewards distribution.
contract RewardDistribution is Context {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// rewardToken represents the address of an ERC20 token used for staking
// rewards on the Bridge.
IERC20 public rewardToken;
// rewardsStash represents a container where calculated rewards are stored before
// the owner asks for the refund.
// Map: Staker => ValidatorID => stashed amount
mapping(address => mapping(uint256 => uint256)) public getRewardStash;
// rewardPerTokenPaid represents a value of the rewardPerTokenLast already consumed
// by the reward update function to calculate current rewards per stake.
// Map: Staker => ValidatorID => rewardPerTokenLast amount consumed
mapping(address => mapping(uint256 => uint256)) rewardPerTokenPaid;
// rewardRate represents the rate of reward tokens distribution.
// It stores the amount of total reward tokens distributed per second
// to the total stake amount.
uint256 public rewardRate;
// rewardPerTokenLast represents the latest calculated total amount of reward
// per a stake token.
uint256 public rewardPerTokenLast;
// rewardPerTokenUpdated represents the timestamp
// of the latest rewards per stake token update.
uint256 public rewardPerTokenUpdated;
// rewardPerTokenDecimalsCorrection represents a decimal correction
// used by reward distribution for more precise fractions handling.
uint256 rewardPerTokenDecimalsCorrection = 1e18;
// -------------------------------------------------
// events
// -------------------------------------------------
// RewardRateChanged event is emitted when a new reward rate value is set.
event RewardRateChanged(uint256 oldRate, uint256 newRate);
// RewardPaid event is emitted when an account claims their rewards from the system.
event RewardPaid(address indexed staker, uint256 indexed toValidatorID, uint256 amount);
// -------------------------------------------------
// interface
// -------------------------------------------------
// rewardClaim allows caller to claim their rewards for the stake towards given
// Validator identified by its ID, both stashed and pending.
function rewardClaim(uint256 validatorID) external {
// who is the staker we are working with
address staker = _sender();
// update the rewards first so we stash any pending rewards
rewardUpdate(staker, validatorID);
// make sure there is a reward and that it can be claimed
require(0 != getRewardsStash[staker][validatorID], "RewardDistribution: no reward earned");
require(canClaimRewards(staker, validatorID), "RewardDistribution: claim rejected");
require(getRewardsStash[staker][validatorID] <= rewardToken.balanceOf(address(this)), "RewardDistribution: reward not available");
// get the current amount
uint256 amount = getRewardsStash[staker][validatorID];
// reset the stored value so any re-entrance would not find any remaining reward
getRewardsStash[staker][validatorID] = 0;
// send the tokens
rewardToken.safeTransfer(staker, amount);
// emit notification
emit RewardPaid(staker, validatorID, amount);
}
// rewardUpdateGlobal updates the global stored reward distribution state for all stakes.
function rewardUpdateGlobal() public {
rewardPerTokenLast = rewardPerToken();
rewardPerTokenUpdated = _now();
}
// rewardUpdate updates the reward distribution state and the accumulated reward
// for the given stake; it is called on each stake token amount change to reflect
// the impact on reward distribution.
function rewardUpdate(address staker, uint256 toValidatorID) public {
// calculate the current reward per token value globally
rewardUpdateGlobal();
// stash all the current pending reward, if any
getRewardsStash[staker][toValidatorID] = rewardPending(staker, toValidatorID);
// adjust paid part of the accumulated reward
// if the account is not eligible to receive reward up to this point
// we just skip it and they will never get it
getRewardsUpdated[staker][toValidatorID] = rewardLastPerToken;
}
// rewardPending calculates the amount of pending reward for the given stake
// including the current stash balance.
function rewardPending(address staker, uint256 toValidatorID) public view returns (uint256) {
// calculate earned rewards based on the amount of staked tokens
return getStakeBy(staker, toValidatorID)
/* multiply by the unpaid reward per token */
.mul(rewardPerToken().sub(rewardPerTokenPaid[staker][toValidatorID]))
/* remove the decimal precision adjustment of the rewardPerToken() call */
.div(rewardPerTokenDecimalsCorrection)
/* add existing stash */
.add(getRewardStash[staker][toValidatorID]);
}
// rewardPerToken calculates the reward share per single stake token.
// It's calculated from the amount of tokens rewarded per second
// and the total amount of staked tokens.
// Note: the value is not in WEI tokens, it's adjusted to increase precision
// using the rewardPerTokenDecimalsCorrection decimal places.
function rewardPerToken() public view returns (uint256) {
// how many tokens are staked? check for total to avoid div by zero later
uint256 total = getStakeTotal();
if (0 == total) {
return rewardPerTokenLast;
}
// return current accumulated rewards per stake token
return rewardPerToken.add(
/* number of seconds passed from the last update */
_now().sub(rewardPerTokenUpdated)
/* times the rate per second */
.mul(rewardRate)
/* times the decimal correction */
.mul(rewardPerTokenDecimalsCorrection)
/* div/per total staked amount */
.div(total)
);
}
// canClaimRewards checks if a reward for the stake can be claimed.
function canClaimRewards(address staker, uint256 validatorID) public view returns (bool) {
return !isStakeJailed(staker, validatorID);
}
// setRewardRate changes the base reward rate value.
function setRewardRate(uint256 newValue) external {
// emit an event about the update and change the value
emit RewardRateChanged(baseRewardRate, newValue);
rewardRate = newValue;
}
// -------------------------------------------------
// internal functions
// -------------------------------------------------
function _initRewards(address token, uint256 rate) internal {
rewardToken = IERC20(rwToken);
rewardRate = rate;
rewardPerTokenUpdated = _now();
}
// getTotalStake returns the total amount of staked tokens for the reward
// distribution calculation.
function getStakeTotal() internal returns (uint256);
// getStakeBy returns the amount of staked tokens of a specific staker/validator combo
// for the reward distribution calculation.
function getStakeBy(address staker, uint256 validatorID) internal returns (uint256);
// isStakeJailed returns jail status of the given stake.
function isStakeJailed(address staker, uint256 validatorID) public view returns (bool);
}
| who is the staker we are working with update the rewards first so we stash any pending rewards make sure there is a reward and that it can be claimed get the current amount reset the stored value so any re-entrance would not find any remaining reward send the tokens emit notification | function rewardClaim(uint256 validatorID) external {
address staker = _sender();
rewardUpdate(staker, validatorID);
require(0 != getRewardsStash[staker][validatorID], "RewardDistribution: no reward earned");
require(canClaimRewards(staker, validatorID), "RewardDistribution: claim rejected");
require(getRewardsStash[staker][validatorID] <= rewardToken.balanceOf(address(this)), "RewardDistribution: reward not available");
uint256 amount = getRewardsStash[staker][validatorID];
getRewardsStash[staker][validatorID] = 0;
rewardToken.safeTransfer(staker, amount);
emit RewardPaid(staker, validatorID, amount);
}
| 5,453,730 | [
1,
3350,
83,
353,
326,
384,
6388,
732,
854,
5960,
598,
1089,
326,
283,
6397,
1122,
1427,
732,
23017,
1281,
4634,
283,
6397,
1221,
3071,
1915,
353,
279,
19890,
471,
716,
518,
848,
506,
7516,
329,
336,
326,
783,
3844,
2715,
326,
4041,
460,
1427,
1281,
283,
17,
8230,
1359,
4102,
486,
1104,
1281,
4463,
19890,
1366,
326,
2430,
3626,
3851,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
19890,
9762,
12,
11890,
5034,
4213,
734,
13,
3903,
288,
203,
3639,
1758,
384,
6388,
273,
389,
15330,
5621,
203,
203,
3639,
19890,
1891,
12,
334,
6388,
16,
4213,
734,
1769,
203,
203,
3639,
2583,
12,
20,
480,
4170,
359,
14727,
510,
961,
63,
334,
6388,
6362,
7357,
734,
6487,
315,
17631,
1060,
9003,
30,
1158,
19890,
425,
1303,
329,
8863,
203,
3639,
2583,
12,
4169,
9762,
17631,
14727,
12,
334,
6388,
16,
4213,
734,
3631,
315,
17631,
1060,
9003,
30,
7516,
11876,
8863,
203,
3639,
2583,
12,
588,
17631,
14727,
510,
961,
63,
334,
6388,
6362,
7357,
734,
65,
1648,
19890,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
315,
17631,
1060,
9003,
30,
19890,
486,
2319,
8863,
203,
203,
3639,
2254,
5034,
3844,
273,
4170,
359,
14727,
510,
961,
63,
334,
6388,
6362,
7357,
734,
15533,
203,
203,
3639,
4170,
359,
14727,
510,
961,
63,
334,
6388,
6362,
7357,
734,
65,
273,
374,
31,
203,
203,
3639,
19890,
1345,
18,
4626,
5912,
12,
334,
6388,
16,
3844,
1769,
203,
203,
3639,
3626,
534,
359,
1060,
16507,
350,
12,
334,
6388,
16,
4213,
734,
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
]
|
./full_match/8453/0x102516AD3cB1e1fC46AB15123BDfeb730480416B/sources/contracts/interfaces/INotary.sol | * Notary The notary approves and signs-off on deposit, withdrawals, and fund movements within a ledger on-behalf of the associated key-holder. A notary won't approve deposits unless the collateral provider is trusted by the root key. A notary won't approve withdrawals unless the collateral provider is trusted by the root key, and the receiver key has approved the withdrawal amount. A notary won't approve funds to move between trust keys unless a root key holder has approved the scribe moving the funds./ Events This is going to help indexers and web applications watch and respond to blocks that contain trust transactions. Permission Methods Because the role between the collateral provider, ledger, and key holder are generally determined - the interface requires the ability to manage withdrawal allowances. Ledger Methods These methods should be considered as the public interface of the contract for the ledger. | interface INotary {
event trustedRoleChange(address keyHolder, uint256 trustId, uint256 rootKeyId,
address ledger, address actor, bool trustLevel, uint role);
event withdrawalAllowanceAssigned(address keyHolder, uint256 keyId,
address ledger, address provider, bytes32 arn, uint256 amount);
event notaryDepositApproval(address ledger, address provider, uint256 trustId, uint256 rootKeyId,
bytes32 arn, uint256 amount);
event notaryWithdrawalApproval(address ledger, address provider, uint256 trustId,
uint256 keyId, bytes32 arn, uint256 amount, uint256 allowance);
event notaryDistributionApproval(address ledger, address provider, address scribe,
bytes32 arn, uint256 trustId, uint256 sourceKeyId,
uint256[] keys, uint256[] amounts);
event notaryEventRegistrationApproval(address dispatcher, uint256 trustId,
bytes32 eventHash, bytes32 description);
function setWithdrawalAllowance(address ledger, address provider, uint256 keyId, bytes32 arn, uint256 amount) external;
function withdrawalAllowances(address ledger, uint256 keyId, address provider, bytes32 arn) external returns (uint256);
function notarizeDeposit(address provider, uint256 keyId, bytes32 arn, uint256 amount) external returns (uint256);
function notarizeWithdrawal(address provider, uint256 keyId, bytes32 arn, uint256 amount) external returns (uint256);
function notarizeDistribution(address scribe, address provider, bytes32 arn,
uint256 sourceKeyId, uint256[] calldata keys, uint256[] calldata amounts) external returns (uint256);
function notarizeEventRegistration(address dispatcher, uint256 trustId, bytes32 eventHash, bytes32 description) external;
function setTrustedLedgerRole(uint256 rootKeyId, uint8 role, address ledger, address actor,
bool trustLevel, bytes32 actorAlias) external;
pragma solidity ^0.8.16;
}
| 11,538,210 | [
1,
1248,
814,
1021,
486,
814,
6617,
3324,
471,
21588,
17,
3674,
603,
443,
1724,
16,
598,
9446,
1031,
16,
471,
284,
1074,
5730,
17110,
3470,
279,
16160,
603,
17,
2196,
20222,
434,
326,
3627,
498,
17,
4505,
18,
432,
486,
814,
8462,
1404,
6617,
537,
443,
917,
1282,
3308,
326,
4508,
2045,
287,
2893,
353,
13179,
635,
326,
1365,
498,
18,
432,
486,
814,
8462,
1404,
6617,
537,
598,
9446,
1031,
3308,
326,
4508,
2045,
287,
2893,
353,
13179,
635,
326,
1365,
498,
16,
471,
326,
5971,
498,
711,
20412,
326,
598,
9446,
287,
3844,
18,
432,
486,
814,
8462,
1404,
6617,
537,
284,
19156,
358,
3635,
3086,
10267,
1311,
3308,
279,
1365,
498,
10438,
711,
20412,
326,
888,
1902,
12499,
326,
284,
19156,
18,
19,
9043,
1220,
353,
8554,
358,
2809,
31932,
471,
3311,
12165,
4267,
471,
6846,
358,
4398,
716,
912,
10267,
8938,
18,
8509,
13063,
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,
5831,
467,
1248,
814,
288,
203,
203,
565,
871,
13179,
2996,
3043,
12,
2867,
498,
6064,
16,
2254,
5034,
10267,
548,
16,
2254,
5034,
1365,
14140,
16,
203,
3639,
1758,
16160,
16,
1758,
8327,
16,
1426,
10267,
2355,
16,
2254,
2478,
1769,
203,
203,
565,
871,
598,
9446,
287,
7009,
1359,
20363,
12,
2867,
498,
6064,
16,
2254,
5034,
30914,
16,
203,
3639,
1758,
16160,
16,
1758,
2893,
16,
1731,
1578,
26399,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
486,
814,
758,
1724,
23461,
12,
2867,
16160,
16,
1758,
2893,
16,
2254,
5034,
10267,
548,
16,
2254,
5034,
1365,
14140,
16,
203,
3639,
1731,
1578,
26399,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
486,
814,
1190,
9446,
287,
23461,
12,
2867,
16160,
16,
1758,
2893,
16,
2254,
5034,
10267,
548,
16,
7010,
3639,
2254,
5034,
30914,
16,
1731,
1578,
26399,
16,
2254,
5034,
3844,
16,
2254,
5034,
1699,
1359,
1769,
203,
203,
565,
871,
486,
814,
9003,
23461,
12,
2867,
16160,
16,
1758,
2893,
16,
1758,
888,
1902,
16,
203,
3639,
1731,
1578,
26399,
16,
2254,
5034,
10267,
548,
16,
2254,
5034,
1084,
14140,
16,
203,
3639,
2254,
5034,
8526,
1311,
16,
2254,
5034,
8526,
30980,
1769,
203,
7010,
565,
871,
486,
814,
1133,
7843,
23461,
12,
2867,
7393,
16,
2254,
5034,
10267,
548,
16,
7010,
3639,
1731,
1578,
871,
2310,
16,
1731,
1578,
2477,
1769,
203,
203,
377,
203,
565,
445,
444,
1190,
9446,
287,
7009,
1359,
12,
2867,
16160,
16,
1758,
2893,
16,
2254,
5034,
30914,
16,
1731,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Un contrat de passeport animaliers
/// @author Théo, Streed, Nico, Mika
/// @notice Ce contrat permet d'associer des animaux à des utilisateurs via des vétérinaires
contract Noe is ERC721, Ownable {
using Counters for Counters.Counter; // Utilisation du contract Counter d'openzeppelin importait en ligne 6
Counters.Counter private _tokenIds; // Utilisation de la fonction Counter pour associer un _tokenIds
address payable private _superAdmin; // Adresse de la personne qui déploie
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
constructor(address payable superAdmin) public ERC721("Noe", "NOE") {
// Constucteur
transferFrom(superAdmin);
}
enum Animals {dog, cat, ferret} // Enumération
event MemberCreated(address indexed _address); // Event pour la créaction d'un membre
event VeterinaryCreated(address indexed _address); // Event pour la créaction d'un vétérinaire
event VeterinaryApprove(address indexed _address); // Event pour que superAdmin approuve un vétérinaire
event AnimalToken(address indexed _address); // Event pour qu'un vétérinaire crée un animal
struct Member {
// Structure membres
string name; // Nom du membre
string tel; // Numéro de téléphone du membre
bool isMember; // False par défaut, true si la pérsonne est déjà enregistré
}
struct Animal {
// Structure animales
string name; // Nom de l'animal
string dateBirth; // Date de naissance de l'animal
string sexe; // Sexe de l'animal
bool vaccin; // Si il est vacciné ou non
Animals animals; // Enumération de chien chat furret
}
struct Veterinary {
// Structure vétérinaire
string name; // Nom du vétérinaire
string tel; // Numéro de téléphone du vétérinaire
bool diploma; // False par defaut, le super admin approuve le vétérinaire une fois les diplomes valide
bool isVeterinary; // False par defaut, il devient vétérinaire une fois que le super admin approuve
}
uint256 public animalsCount; // Variable de statut pour compter le nombre d'animaux
/// @dev Mapping de la struct Animal
mapping(uint256 => Animal) private _animal;
/// @dev Mapping de la struct Member
mapping(address => Member) public member;
/// @dev Mapping de la struct Veterinary
mapping(address => Veterinary) public veterinary;
// This modifer, vérifie si c'est le super admin
modifier isSuperAdmin() {
require(msg.sender == _superAdmin, "Vous n'avez pas le droit d'utiliser cette fonction");
_;
}
// This modifer, vérifie si le membre est déjà enregistré
modifier onlyMember() {
require(member[msg.sender].isMember == true, "Vous n'étes pas membre");
_;
}
// This modifer, vérifie si le membre n'est pas déjà enregistré
modifier onlyNotMember() {
require(member[msg.sender].isMember == false, "Vous étes déjà membre");
_;
}
// This modifer, vérifie si le vétérinaire est déjà enregistré
modifier onlyVeterinary() {
require(veterinary[msg.sender].isVeterinary == true, "Vous n'étes pas vétérinaire");
_;
}
// This modifer, vérifie si le vétérinaire est déjà enregistré et approuvé
modifier onlyVeterinaryApprove() {
require(veterinary[msg.sender].diploma == true, "Vous n'étes pas un vétérinaire approuvé");
_;
}
// This modifer, vérifie si le vétérinaire n'est pas déjà enregistré
modifier onlyNotVeterinary() {
require(veterinary[msg.sender].isVeterinary == false, "Vous étes déjà vétérinaire");
_;
}
// This modifer, vérifie si l'animal éxiste ou pas
modifier animalIdCheck(uint256 animalId) {
require(animalId < animalsCount, "L'animal n'éxiste pas");
_;
}
/// @dev Permet de créer un nouveau membre en vérifiant qu'il n'est pas déjà membre
/// @param _name set le nom du membre dans la struct Member
/// @param _tel set le numéro de téléphone dans la struct Member
function createMember(string memory _name, string memory _tel) public onlyNotMember() {
member[msg.sender] = Member({name: _name, tel: _tel, isMember: true});
emit MemberCreated(msg.sender); /// emit de l'event MemberCreated
}
/// @dev Permet de récuperer les infos
function getMember() public view returns (Member memory) {
return member[msg.sender];
}
/// @dev Permet de créer un compte vétérinaire sous réserve de validation du diplôme par le super admin et la fonction approveVeterinary
/// @param _name set le nom du membre dans la struct vétérinaire
/// @param _tel set le nom du téléphone dans la struct vétérinaire
function createVeterinary(string memory _name, string memory _tel) public onlyNotVeterinary() {
veterinary[msg.sender] = Veterinary({name: _name, tel: _tel, diploma: false, isVeterinary: true});
emit VeterinaryCreated(msg.sender);
}
/// @dev Permet de récuperer les infos
function getVeterinary() public view returns (Veterinary memory) {
return veterinary[msg.sender];
}
/// @dev Permet de valider le compte vétérinaire après vérification du diplôme
/// @param _addr passe l'adresse du vétérinaire à approuver
function approveVeterinary(address _addr) public isSuperAdmin {
veterinary[_addr].diploma = true; // Set à true le diplome dans la struct Veterinary
emit VeterinaryApprove(msg.sender); /// emit de l'event VeterinaryApprove
}
/// @dev Crée un animal et lui associe un token ERC721
/// @param _member du membre à qui attibuer l'animal/token
/// @param _name le nom de l'animal
/// @param _dateBirth date de naissance de l'animal
/// @param _sexe le sex de l'animal
/// @param _vaccin si l'animal est vacciné ou non
/// @param animals_ le type d'animal de l'énunération
/// @return le numéro de token
function animalToken(
address _member,
string memory _name,
string memory _dateBirth,
string memory _sexe,
bool _vaccin,
Animals animals_
) public onlyVeterinaryApprove() returns (uint256) {
animalsCount++;
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
_mint(_member, newTokenId);
_animal[newTokenId] = Animal({
name: _name,
dateBirth: _dateBirth,
sexe: _sexe,
vaccin: _vaccin,
animals: animals_
});
emit AnimalToken(msg.sender); /// emit de l'event AnimalToken
return newTokenId;
}
/// @dev Permet de retrouver un animal en fonction de son numéro de token
/// @param tokenId retrouver un animal via son numéro de token
function getAnimalById(uint256 tokenId) public view returns (Animal memory) {
require(_exists(tokenId), "NOE: Animal query for no nexistent token");
return _animal[tokenId];
}
}
| @notice Name and symbol of the non fungible token, as defined in ERC721. Constucteur | constructor(address payable superAdmin) public ERC721("Noe", "NOE") {
transferFrom(superAdmin);
}
| 14,086,627 | [
1,
461,
471,
3273,
434,
326,
1661,
9831,
75,
1523,
1147,
16,
487,
2553,
316,
4232,
39,
27,
5340,
18,
9333,
853,
73,
295,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
2867,
8843,
429,
2240,
4446,
13,
1071,
4232,
39,
27,
5340,
2932,
2279,
73,
3113,
315,
3417,
41,
7923,
288,
203,
3639,
7412,
1265,
12,
9565,
4446,
1769,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-12-15
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
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 Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
contract KawsInu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Kaws Inu";
string private constant _symbol = "KAWS";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
//Buy Fee
uint256 private _redisFeeOnBuy = 2;
uint256 private _taxFeeOnBuy = 8;
//Sell Fee
uint256 private _redisFeeOnSell = 2;
uint256 private _taxFeeOnSell = 8;
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping (address => bool) public preTrader;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0x3648663d0EdEd9f553708ae7391B620FE7Ea5c70);
address payable private _marketingAddress = payable(0x3648663d0EdEd9f553708ae7391B620FE7Ea5c70);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 2500000000000 * 10**9; //0.25
uint256 public _maxWalletSize = 4500000000000 * 10**9; //0.45
uint256 public _swapTokensAtAmount = 1000000000000 * 10**9; //0.1
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
preTrader[owner()] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true;
bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true;
bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true;
bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true;
bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true;
bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true;
bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true;
bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true;
bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true;
bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true;
bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true;
bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true;
bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true;
bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true;
bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true;
bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true;
bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true;
bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true;
bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true;
bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true;
bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true;
bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true;
bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true;
bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true;
bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true;
bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true;
bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
//Trade start check
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set MAx transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function allowPreTrading(address account, bool allowed) public onlyOwner {
require(preTrader[account] != allowed, "TOKEN: Already enabled.");
preTrader[account] = allowed;
}
} | Buy FeeSell FeeOriginal Fee | contract KawsInu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Kaws Inu";
string private constant _symbol = "KAWS";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 2;
uint256 private _taxFeeOnBuy = 8;
uint256 private _redisFeeOnSell = 2;
uint256 private _taxFeeOnSell = 8;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping (address => bool) public preTrader;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0x3648663d0EdEd9f553708ae7391B620FE7Ea5c70);
address payable private _marketingAddress = payable(0x3648663d0EdEd9f553708ae7391B620FE7Ea5c70);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
preTrader[owner()] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true;
bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true;
bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true;
bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true;
bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true;
bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true;
bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true;
bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true;
bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true;
bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true;
bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true;
bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true;
bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true;
bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true;
bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true;
bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true;
bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true;
bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true;
bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true;
bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true;
bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true;
bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true;
bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true;
bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true;
bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true;
bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true;
bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function allowPreTrading(address account, bool allowed) public onlyOwner {
require(preTrader[account] != allowed, "TOKEN: Already enabled.");
preTrader[account] = allowed;
}
} | 15,169,925 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1475,
6850,
382,
89,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
377,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
47,
6850,
657,
89,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
47,
10800,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
2130,
12648,
11706,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
38,
9835,
273,
576,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
1725,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
55,
1165,
273,
576,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
55,
1165,
273,
1725,
31,
203,
377,
203,
565,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
//import "./Token.sol";
import "./Betting.sol";
contract Oracle {
// after each settlement, a new epoch commences. Bets cannot consummate on games referring to prior epochs
uint8 public betEpoch;
// This is true if there is a proposal under consideration, other proposals are not allowed while a current proposal
// is under review: 0 null, 1 init, 2 odds, 3 settle, 4 params
uint8 public underReview;
// result are coded where 2 is a tie/cancellation or postponement, 0 for home team win, 1 for away team win.
uint8[32] public propResults;
// this tracking number is for submissions, needed for tracking whether someone already voted on a data proposal
// incremented at each processing
uint16 public propNumber;
// propStartTime in UTC is used to stop active betting. No bets are taken after this time.
uint256[32] public propStartTime;
// odds are entered as probabilitie, such that 51000 is a 51.0% chance of winning
// This translates to decimal odds via 1/p, where p is in units like 0.51.
// a standard bet that pays out with decimale odds of 1.909 pays the better back his bet amount plus
// 0.909 times that amount as the bettor's winning.
// betAmount*(propOdds/1000 * 95/100 +1) is the gross payoff to bettor for a winning bet,
// betAmount*propOdds/1000 * 95/100 is the net payoff to bettor for a winning bet
uint256[32] public propOdds;
// this is the UTC at which LPs can no longer withdraw or deposit until the next settlement
// it is the time of the earliest game start. It is more efficient to load this in separately rather than
// take the minimum of the data in the propStartTime array
uint256 public earliestStart;
// timer is used so that each proposal has at least a 3 hours for voters to respond
uint256 public timer;
// tracks the current local token balance of active oracle contract administrators, as
// documented by the deposit of their tokens within this contract
uint256 public totKontractTokens;
// A proposal goes through via a simple rule of more yes than no votes. Thus, a trivial vote does not need more yes votes
// if a troll rejects a vote that has few Yes votes, a vote later than evening takes a large bond amount, so
// and submitters should anticipate such an event
uint256 public voteYes;
uint256 public voteNo;
uint256 public constant CURE_TIME = 5 hours;
uint256 public constant HOUR_START = 10;
uint256 public constant MIN_BOND = 100 ether;
uint256 public constant MIN_SUBMIT = 5000 ether;
/** the schedule is a record of "sport:home:away", such as "NFL:NYG:SF" for us football, New York Giants vs San Francisco */
string[32] public propSchedule;
// keeps track of those who supplied data proposals. Proposers have to deposit tokens as a bond, and if their
// proposal is rejected, they lose that bond.
address public proposer;
// this allows the oracle administrators to vote on new betting/oracle contracts without withdrawing their tokens
Token public token;
Betting public bettingContract;
uint256 public feePool;
mapping(address => AdminisStruct) public adminStruct;
struct AdminisStruct {
uint256 tokens;
uint16 voteTracker;
uint256 initFeePool;
}
event ResultsPosted(
bool indexed posted,
uint16 propnum,
uint8[32] winner,
uint8 epoch,
address proposer
);
event DecOddsPosted(
bool indexed posted,
uint16 propnum,
uint256[32] decOdds,
uint8 epoch,
address proposer
);
event ParamsPosted(
uint256 minBet,
uint256 concLimit,
uint8 epoch,
address proposer
);
event SchedulePosted(
bool indexed posted,
uint16 propnum,
string[32] sched,
uint8 epoch,
address proposer
);
event StartTimesPosted(
bool indexed posted,
uint16 propnum,
uint256[32] starttimes,
uint8 epoch,
address proposer
);
event Funding(
uint256 tokensChange,
uint256 etherChange,
address transactor
);
constructor(address payable bettingk, address _token) {
bettingContract = Betting(bettingk);
token = Token(_token);
timer = 2e9;
betEpoch = 1;
propNumber = 1;
feePool=0;
earliestStart = 2e9;
}
function vote(bool sendData) external {
// voter must have votes to allocate
require(adminStruct[msg.sender].tokens > 0);
// can only vote if there is a proposal
require(underReview != 0);
// voter must not have voted on this proposal
require(adminStruct[msg.sender].voteTracker != propNumber);
// this prevents this account from voting again on this data proposal (see above)
adminStruct[msg.sender].voteTracker = propNumber;
// votes are simply one's entire token balance deposited in this oracle contract
if (sendData) {
voteYes += adminStruct[msg.sender].tokens;
} else {
voteNo += adminStruct[msg.sender].tokens;
}
// 5e4 is 1/2 of the minted tokens, so this expedites data submissions
// if (voteYes > 5e4 ether && underReview != 3) timer = 0;
}
receive() external payable {}
function initPost(
string[32] memory teamsched,
uint256[32] memory starts,
uint256[32] memory decimalOdds,
uint256 earlyStart
) external {
// this requirement makes sure a post occurs only if there is not a current post under consideration, or
// it is an amend for an earlier post with these data
require(underReview == 0 && earliestStart == 2e9, "Already under Review");
underReview = 1;
post();
propSchedule = teamsched;
propStartTime = starts;
propOdds = decimalOdds;
earliestStart = earlyStart;
// this tells users that an inimtial proposal has been sent, which is useful for oracle administrators who are monitoring this contract
emit SchedulePosted(false, propNumber, teamsched, betEpoch, msg.sender);
emit StartTimesPosted(false, propNumber, starts, betEpoch, msg.sender);
emit DecOddsPosted(false, propNumber, decimalOdds, betEpoch, msg.sender);
}
function oddsPost(uint256[32] memory decimalOdds) external {
require(underReview == 0, "Already under Review");
underReview = 2;
post();
propOdds = decimalOdds;
emit DecOddsPosted(false, propNumber, propOdds, betEpoch, msg.sender);
}
function settlePost(uint8[32] memory resultVector) external {
// this prevents a settle post when other posts have been made
require(underReview == 0, "Already under Review");
underReview = 3;
post();
propResults = resultVector;
emit ResultsPosted(false, propNumber, propResults, betEpoch, msg.sender);
}
function initProcess() external {
// this prevents an odds or results proposal from being sent
require(underReview == 1, "wrong data");
// needs at least 3 hours or a clear majority decision
require (block.timestamp > timer, "too soon");
// only sent if 'null' vote does not win
if (voteYes > voteNo) {
// successful submitter gets their bonded tokens back
adminStruct[proposer].tokens += MIN_BOND;
// sends to the betting contract
bettingContract.transmitInit(
propSchedule,
propStartTime,
propOdds,
earliestStart
);
emit SchedulePosted(true, propNumber, propSchedule, betEpoch, proposer);
emit StartTimesPosted(true, propNumber, propStartTime, betEpoch, proposer);
emit DecOddsPosted(true, propNumber, propOdds, betEpoch, proposer);
}
// resets various data (eg, timer)
reset();
// resets data arrays for next submission
// delete propSchedule;
// delete propOdds;
// delete propStartTime;
// delete earliestStart;
}
// these have the same logic as for the initProcess, just for the different datasets
function oddsProcess() external {
// this prevents an 'initProcess' set being sent as an odds transmit
require(underReview == 2, "wrong data");
// needs at least 3 hours or a clear majority decision
require (block.timestamp > timer, "too soon");
if (voteYes > voteNo) {
// proposer gets back their bonding amount
adminStruct[proposer].tokens += MIN_BOND;
bettingContract.transmitOdds(propOdds);
emit DecOddsPosted(true, propNumber, propOdds, betEpoch, proposer);
}
// resets various data (eg, timer)
reset();
// delete propOdds;
}
function settleProcess() external {
require(underReview == 3, "wrong data");
// needs at least 3 hours or a clear majority decision
require (block.timestamp > timer, "too soon");
uint256 ethDividend;
if (voteYes > voteNo) {
// proposer gets back their bonding amount
adminStruct[proposer].tokens += MIN_BOND;
(betEpoch, ethDividend) = bettingContract.settle(propResults);
emit ResultsPosted(true, propNumber, propResults, betEpoch, proposer);
feePool += (ethDividend * 1e18 / totKontractTokens);
}
// resets various data (eg, timer)
reset();
earliestStart = 2e9;
// delete propResults;
}
function paramUpdate(uint256 minbet, uint256 concentrationLim) external {
// In the first case, an immediate send allows a simple way to protect against stale odds
// a high minimum bet would prevent new bets while odds are voted upon
// in the second case, a large token holder can make the contract able to take more more bets
require((minbet > 1e7 && adminStruct[msg.sender].tokens >= 1000 ether) || adminStruct[msg.sender].tokens >= 5000 ether, "Low Balance");
bettingContract.adjustParams(minbet, concentrationLim);
emit ParamsPosted(
minbet,
concentrationLim,
betEpoch,
msg.sender
);
}
function withdrawTokens(uint amtTokens) external {
require(amtTokens <= adminStruct[msg.sender].tokens,
"need tokens"
);
// this prevents voting more than once or oracle proposals with token balance.
require(underReview == 0, "no wd during vote");
uint ethBalance = address(this).balance;
uint userTokens = adminStruct[msg.sender].tokens;
uint ethClaim = (feePool - adminStruct[msg.sender].initFeePool ) * userTokens/ 1e18 ;
adminStruct[msg.sender].initFeePool = feePool;
totKontractTokens -= amtTokens;
adminStruct[msg.sender].tokens -= amtTokens;
if (ethBalance <= ethClaim) ethClaim = ethBalance;
payable(msg.sender).transfer(ethClaim);
token.transfer(msg.sender, amtTokens);
emit Funding(amtTokens, ethClaim, msg.sender);
}
function depositTokens(uint256 amt) external {
// Must own one thousandth of outstanding tokens (100,000 eth) to administer oracle
// and receive dividends. Prevents spamming by de minimus token holders
require(amt >= 100 ether);
if (adminStruct[msg.sender].tokens > 0) {
uint userTokens = adminStruct[msg.sender].tokens;
uint ethClaim = (feePool - adminStruct[msg.sender].initFeePool ) * userTokens/ 1e18 ;
uint ethBalance = address(this).balance;
if (ethBalance <= ethClaim) ethClaim = ethBalance;
payable(msg.sender).transfer(ethClaim);
}
token.transferFrom(msg.sender, address(this), amt);
adminStruct[msg.sender].tokens += amt;
totKontractTokens += amt;
adminStruct[msg.sender].initFeePool = feePool;
emit Funding(amt, 0, msg.sender);
}
function post() internal {
// constraining the hourOfDay to be > 10 gives users a block of time where they can be confident that their
// inattention to the contract poses no risk of a malicious data submission.
require(hourOfDay() >= HOUR_START, "hour");
// this ensures subtraction below is valid
// also that only significant token holders are making proposals
require(adminStruct[msg.sender].tokens >= MIN_SUBMIT, "Low Balance");
timer = block.timestamp + CURE_TIME;
voteYes = adminStruct[msg.sender].tokens;
// REMOVE AT USE
if (adminStruct[msg.sender].tokens > 5e4 ether) timer = 0;
// this prevents proposer from voting again with his tokens on this submission
adminStruct[msg.sender].voteTracker = propNumber;
// check above makes this safemath
adminStruct[msg.sender].tokens -= MIN_BOND;
proposer = msg.sender;
}
function reset() internal {
// if the collective has sufficient time, or the majority has a preference registered, one can submit asap
delete proposer;
voteYes = 0;
voteNo = 0;
underReview = 0;
propNumber++;
timer = 0;
}
// this is used so users do not have to delegate someone else to monitor the contract 24/7
// 86400 is seconds in a day, and 3600 is seconds in an hour
function hourOfDay() public view returns (uint256 hour1) {
hour1 = (block.timestamp - 7200) % 86400 / 3600;
}
}
| In the first case, an immediate send allows a simple way to protect against stale odds a high minimum bet would prevent new bets while odds are voted upon in the second case, a large token holder can make the contract able to take more more bets | function paramUpdate(uint256 minbet, uint256 concentrationLim) external {
require((minbet > 1e7 && adminStruct[msg.sender].tokens >= 1000 ether) || adminStruct[msg.sender].tokens >= 5000 ether, "Low Balance");
bettingContract.adjustParams(minbet, concentrationLim);
emit ParamsPosted(
minbet,
concentrationLim,
betEpoch,
msg.sender
);
}
| 12,878,196 | [
1,
382,
326,
1122,
648,
16,
392,
14483,
1366,
5360,
279,
4143,
4031,
358,
17151,
5314,
14067,
14800,
87,
279,
3551,
5224,
2701,
4102,
5309,
394,
324,
2413,
1323,
14800,
87,
854,
331,
16474,
12318,
316,
326,
2205,
648,
16,
279,
7876,
1147,
10438,
848,
1221,
326,
6835,
7752,
358,
4862,
1898,
1898,
324,
2413,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
579,
1891,
12,
11890,
5034,
1131,
70,
278,
16,
2254,
5034,
20570,
8230,
367,
48,
381,
13,
3903,
288,
203,
3639,
2583,
12443,
1154,
70,
278,
405,
404,
73,
27,
597,
3981,
3823,
63,
3576,
18,
15330,
8009,
7860,
1545,
4336,
225,
2437,
13,
747,
3981,
3823,
63,
3576,
18,
15330,
8009,
7860,
1545,
20190,
225,
2437,
16,
315,
10520,
30918,
8863,
203,
3639,
2701,
1787,
8924,
18,
13362,
1370,
12,
1154,
70,
278,
16,
20570,
8230,
367,
48,
381,
1769,
203,
3639,
3626,
8861,
3349,
329,
12,
203,
5411,
1131,
70,
278,
16,
203,
5411,
20570,
8230,
367,
48,
381,
16,
203,
5411,
2701,
14638,
16,
203,
5411,
1234,
18,
15330,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Правила для изменения достоверности распознавания конкретных словоформ в русском словаре.
// Обычное предназначение этих правил - изменить равновероятные распознавания
// омонимичных форм жаль(безличный глагол)>жаль(императив),
// либо повлиять на выбор многословных форм в противовес
// выбору отдельных слов: [слева от] <--> [слева] [от]
wordform_score смеси{глагол}=-10 // из чего смеси ?
wordform_score ага{ существительное }=-5
wordform_score малышки{ род:муж }=-10 // Малышки будут прыгать от радости!
wordform_score мебели{ число:мн }=-10 // Рвали обивку мебели.
wordform_score начало{ глагол }=-6 // Сегодня неплохое начало.
wordform_score воды{ род:муж }=-10 // мы приплывем в их воды
wordform_score скалы{ род:муж }=-10 // там должны быть скалы
wordform_score кафе{ род:муж }=-10 // в кафе
wordform_score скалы{ род:муж }=-10 // волны бились о скалы
wordform_score кроме{ существительное }=-10 // кроме этой вот ягоды
wordform_score жилище{ род:жен }=-10 // в ее жилище
wordform_score почитай{ наречие }=-4 // Ты лучше почитай.
wordform_score без{ существительное }=-10 // Без кладовок и гардеробных комнат
wordform_score бренды{род:жен}=-10 // Вообще-то перечисленные бренды давно уже избавились от налета местечковости.
wordform_score ярки{ существительное }=-10 // Глаза его были ярки
wordform_score голубей{ прилагательное }=-1 // Ты будешь Петькиных голубей подманивать.
wordform_score дело{ глагол }=-10 // Дело наше лесное.
wordform_score правило{ глагол }=-5 // Такое наше правило...
wordform_score карусель{ глагол }=-10 // Карусель начинается мировая.
wordform_score Германии{ число:мн }=-10 // В Германии беженец спрыгнул с поезда из-за угрозы депортации в Италию
wordform_score бусы { род:муж }=-5 // Весенние бусы персикового дерева разорвались.
wordform_score суеты { число:мн }=-10 // Завершился 26-ой тур российской премьер-лиги.
wordform_score метель { глагол }=-10 // На улице метель.
//wordform_score по-видимому { наречие }=2
//wordform_score по-видимому { вводное }=2 // Ему, по-видимому, не терпелось начать.
wordform_score энергии { существительное число:мн }=-2 // Ему и сейчас не занимать энергии.
wordform_score таки { существительное }=-5 // Ему-таки удалось ее завести.
wordform_score выстуживаем { прилагательное }=-1
wordform_score уполномочиваем { прилагательное }=-1
wordform_score кормим { прилагательное }=-1
wordform_score чиним { прилагательное }=-1
wordform_score заводим { прилагательное }=-1
wordform_score периодизируем { прилагательное }=-1
wordform_score завозим { прилагательное }=-1
wordform_score дегустируем { прилагательное }=-1
wordform_score увозим { прилагательное }=-1
wordform_score вообразим { прилагательное }=-1
wordform_score дробим { прилагательное }=-1
wordform_score таскаем { прилагательное }=-1
wordform_score превозносим { прилагательное }=-1
wordform_score потопляем { прилагательное }=-1
wordform_score волочим { прилагательное }=-1
wordform_score перевиваем { прилагательное }=-1
wordform_score засекречиваем { прилагательное }=-1
wordform_score храним { прилагательное }=-1
wordform_score уносим { прилагательное }=-1
wordform_score предводим { прилагательное }=-1
wordform_score мыслим { прилагательное }=-1
wordform_score проходим { прилагательное }=-1
wordform_score влачим { прилагательное }=-1
wordform_score творим { прилагательное }=-1
wordform_score сравним { прилагательное }=-1
wordform_score измерим { прилагательное }=-1
wordform_score душим { прилагательное }=-1
wordform_score сопоставим { прилагательное }=-1
wordform_score досягаем { прилагательное }=-1
wordform_score травим { прилагательное }=-1
wordform_score благоволим { прилагательное }=-1
wordform_score убеждаем { прилагательное }=-1
wordform_score слышим { прилагательное }=-1
wordform_score слышим { прилагательное }=-1
wordform_score подгружаем { прилагательное }=-1
wordform_score укрупняем { прилагательное }=-1
wordform_score взымаем { прилагательное }=-1
wordform_score зашвыриваем { прилагательное }=-1
wordform_score зависим { прилагательное }=-1
wordform_score ощутим { прилагательное }=-1
wordform_score громим { прилагательное }=-1
wordform_score застраиваем { прилагательное }=-1
wordform_score исправим { прилагательное }=-1
wordform_score выполним { прилагательное }=-1
wordform_score производим { прилагательное }=-1
wordform_score втемяшиваем { прилагательное }=-1
wordform_score содержим { прилагательное }=-1
wordform_score подносим { прилагательное }=-1
wordform_score вкраиваем { прилагательное }=-1
wordform_score беспокоим { прилагательное }=-1
wordform_score взнуздываем { прилагательное }=-1
wordform_score носим { прилагательное }=-1
wordform_score любим { прилагательное }=-1
wordform_score доносим { прилагательное }=-1
wordform_score уценяем { прилагательное }=-1
wordform_score ненавидим { прилагательное }=-1
wordform_score судим { прилагательное }=-1
wordform_score вмораживаем { прилагательное }=-1
wordform_score ввозим { прилагательное }=-1
wordform_score подвозим { прилагательное }=-1
wordform_score развозим { прилагательное }=-1
wordform_score привозим { прилагательное }=-1
wordform_score реструктурируем { прилагательное }=-1
wordform_score реструктурируем { прилагательное }=-1
wordform_score подтопляем { прилагательное }=-1
wordform_score перезаписываем { прилагательное }=-1
wordform_score ценим { прилагательное }=-1
wordform_score национализируем { прилагательное }=-1
wordform_score национализируем { прилагательное }=-1
wordform_score проминаем { прилагательное }=-1
wordform_score переносим { прилагательное }=-1
wordform_score возводим { прилагательное }=-1
wordform_score проницаем { прилагательное }=-1
wordform_score проводим { прилагательное }=-1
wordform_score проводим { прилагательное }=-1
wordform_score таим { прилагательное }=-1
wordform_score синхронизируем { прилагательное }=-1
wordform_score вводим { прилагательное }=-1
wordform_score гоним { прилагательное }=-1
wordform_score разделим { прилагательное }=-1
wordform_score ввариваем { прилагательное }=-1
wordform_score бороздим { прилагательное }=-1
wordform_score воспоминаем { прилагательное }=-1
wordform_score руководим { прилагательное }=-1
wordform_score сносим { прилагательное }=-1
wordform_score разносим { прилагательное }=-1
wordform_score стандартизируем { прилагательное }=-1
wordform_score терпим { прилагательное }=-1
wordform_score выносим { прилагательное }=-1
wordform_score выносим { прилагательное }=-1
wordform_score боготворим { прилагательное }=-1
wordform_score клоним { прилагательное }=-1
wordform_score прозываем { прилагательное }=-1
wordform_score привносим { прилагательное }=-1
wordform_score соизмерим { прилагательное }=-1
wordform_score компилируем { прилагательное }=-1
wordform_score централизуем { прилагательное }=-1
wordform_score упаковываем { прилагательное }=-1
wordform_score возбудим { прилагательное }=-1
wordform_score отделим { прилагательное }=-1
wordform_score ограбляем { прилагательное }=-1
wordform_score объясним { прилагательное }=-1
wordform_score наводим { прилагательное }=-1
wordform_score подводим { прилагательное }=-1
wordform_score исполним { прилагательное }=-1
wordform_score вычислим { прилагательное }=-1
wordform_score монетизируем { прилагательное }=-1
wordform_score отряжаем { прилагательное }=-1
wordform_score разъединим { прилагательное }=-1
wordform_score заменим { прилагательное }=-1
wordform_score охаиваем { прилагательное }=-1
wordform_score растворим { прилагательное }=-1
wordform_score наносим { прилагательное }=-1
wordform_score уничтожим { прилагательное }=-1
wordform_score томим { прилагательное }=-1
wordform_score заполним { прилагательное }=-1
wordform_score сводим { прилагательное }=-1
wordform_score выводим { прилагательное }=-1
wordform_score перевозим { прилагательное }=-1
wordform_score взаимозаменяем { прилагательное }=-1
wordform_score поносим { прилагательное }=-1
wordform_score вверстываем { прилагательное }=-1
wordform_score воспроизводим { прилагательное }=-1
wordform_score вывозим { прилагательное }=-1
wordform_score прорежаем { прилагательное }=-1
wordform_score дренируем { прилагательное }=-1
wordform_score разграбляем { прилагательное }=-1
wordform_score обеззараживаем { прилагательное }=-1
wordform_score тесним { прилагательное }=-1
wordform_score вносим { прилагательное }=-1
wordform_score разрешим { прилагательное }=-1
wordform_score подбодряем { прилагательное }=-1
wordform_score уловим { прилагательное }=-1
wordform_score вдергиваем { прилагательное }=-1
wordform_score автопилотируем { прилагательное }=-1
wordform_score автопилотируем { прилагательное }=-1
wordform_score воссоединяем { прилагательное }=-1
wordform_score фондируем { прилагательное }=-1
wordform_score зрим { прилагательное }=-1
wordform_score допустим { прилагательное }=-1
wordform_score преподносим { прилагательное }=-1
wordform_score устраним { прилагательное }=-1
wordform_score устрашим { прилагательное }=-1
wordform_score поправим { прилагательное }=-1
wordform_score нарезаем { прилагательное }=-1
wordform_score значим { прилагательное }=-1
wordform_score истребим { прилагательное }=-1
wordform_score окормляем { прилагательное }=-1
wordform_score воплотим { прилагательное }=-1
wordform_score будоражим { прилагательное }=-1
wordform_score тревожим { прилагательное }=-1
wordform_score применим { прилагательное }=-1
wordform_score дактилоскопируем { прилагательное }=-1
wordform_score дактилоскопируем { прилагательное }=-1
wordform_score браним { прилагательное }=-1
wordform_score провозим { прилагательное }=-1
wordform_score чтим { прилагательное }=-1
wordform_score приложим { прилагательное }=-1
wordform_score повторим { прилагательное }=-1
wordform_score вменяем { прилагательное }=-1
wordform_score раздробляем { прилагательное }=-1
wordform_score льготируем { прилагательное }=-1
wordform_score перезаправляем { прилагательное }=-1
wordform_score удовлетворим { прилагательное }=-1
wordform_score отводим { прилагательное }=-1
wordform_score переводим { прилагательное }=-1
wordform_score утапливаем { прилагательное }=-1
wordform_score предотвратим { прилагательное }=-1
wordform_score тормозим { прилагательное }=-1
wordform_score вербализуем { прилагательное }=-1
wordform_score тостуем { прилагательное }=-1
wordform_score разводим { прилагательное }=-1
wordform_score уводим { прилагательное }=-1
wordform_score искореним { прилагательное }=-1
wordform_score протапливаем { прилагательное }=-1
wordform_score изготавливаем { прилагательное }=-1
wordform_score изъясним { прилагательное }=-1
wordform_score употребим { прилагательное }=-1
wordform_score разложим { прилагательное }=-1
wordform_score возносим { прилагательное }=-1
wordform_score проносим { прилагательное }=-1
wordform_score предвидим { прилагательное }=-1
wordform_score полимеризуем { прилагательное }=-1
wordform_score полимеризуем { прилагательное }=-1
wordform_score исчислим { прилагательное }=-1
wordform_score погрешим { прилагательное }=-1
wordform_score совместим { прилагательное }=-1
wordform_score впериваем { прилагательное }=-1
wordform_score приносим { прилагательное }=-1
wordform_score доводим { прилагательное }=-1
wordform_score заносим { прилагательное }=-1
wordform_score вытаращиваем { прилагательное }=-1
wordform_score обоготворяем { прилагательное }=-1
wordform_score наметаем { прилагательное }=-1
wordform_score делим { прилагательное }=-1
wordform_score хвалим { прилагательное }=-1
wordform_score излечим { прилагательное }=-1
wordform_score обратим { прилагательное }=-1
wordform_score уязвим { прилагательное }=-1
wordform_score определим { прилагательное }=-1
wordform_score произносим { прилагательное }=-1
wordform_score возобновим { прилагательное }=-1
wordform_score соотносим { прилагательное }=-1
wordform_score победим { прилагательное }=-1
wordform_score раним { прилагательное }=-1
wordform_score отличим { прилагательное }=-1
wordform_score прокачиваем { прилагательное }=-1
wordform_score рейтингуем { прилагательное }=-1
wordform_score растравляем { прилагательное }=-1
wordform_score коров { род:муж } = -2 // Без коров мужчины погибли бы.
wordform_score ангел { род:жен } = -2 // А мисс Уиллоу была просто ангел.
wordform_score слаб { глагол } = -1 // Просто ты слаб!
//wordform_score писал { stress:"п^исал" } = -1 // Державин писал:
//wordform_score писала { stress:"п^исала" } = -1
wordform_score сердит { глагол } = -1 // Он очень сердит.
wordform_score ребят { падеж:зват } = -1 // Ребят пора вернуть
wordform_score помочь { существительное } = -10 // мы хотим вам помочь
wordform_score вон { существительное } = -1 // Я вон зарабатываю.
wordform_score скалами { род:муж } = -5 // Миновав Море Акул, путешественники оказались над Крабьими Скалами.
wordform_score воды { род:муж } = -5 // выпить воды
wordform_score воде { род:муж } = -5 // рожать в воде
wordform_score лук { род:жен } = -5 // возьми с собой лук
wordform_score базе { род:муж } = -5 // заправлять на базе
wordform_score порошки { род:жен } = -5 // Порошки не помогают...
wordform_score обезвреживания { число:мн } = -5 // Разработали план обезвреживания.
wordform_score трех { существительное } = -10 // Считаю до трех.
wordform_score метель { глагол } = -10 // На улице метель.
wordforms_score городской { существительное }=-1 // Существуют городские правила, касающиеся этих процедур.
wordforms_score утесать {глагол}=-5 // Я утешу тебя.
wordforms_score примереть {глагол}=-5 // Внутри пример
wordforms_score запоить {глагол}=-5 // Я запою
wordforms_score новое { существительное }=-5 // Начинаются поиски новых приемов, новых методов.
wordforms_score просек { существительное }=-5 // Матросы переползали просеку.
wordforms_score прививок { существительное }=-10
wordforms_score полок { существительное род:муж }=-5 // Началась переправа полков.
wordforms_score уток { существительное род:муж }=-10
wordforms_score юр { существительное }=-10
wordforms_score наркотика { существительное род:жен }=-10 // Одно время она даже пыталась бросить наркотики
wordforms_score полян { существительное род:муж }=-10
wordforms_score полянин { существительное род:муж }=-10
wordforms_score чужой { существительное }=-5 // голос ее стал чужим
wordforms_score живой { существительное }=-5 // но оно было живым!
wordforms_score пяток { существительное }=-5 // сверкать пятками
wordforms_score ложок { существительное }=-5 // звякнуть ложками
wordforms_score костра { существительное }=-5 // сжечь на костре
wordforms_score роить { глагол }=-10 // Я рою траншеи
wordforms_score ситце { род:ср }=-10 // шить из ситца
wordforms_score взяток { существительное }=-10 // Врач попался на взятке
wordforms_score сило { существительное }=-10 // Оставить в силе закон.
wordforms_score покадить { глагол }=-5 // Я после покажу...
wordforms_score выло { существительное }=-5 // Як не выл больше.
wordforms_score вылезть { глагол }=-1 // Я медленно вылез.
wordforms_score лунь { существительное }=-1 // Астронавты смогут оставаться на Луне в течение недели
wordforms_score закроить { глагол }=-1 // Я потом закрою.
wordforms_score вылезть { глагол }=-1 // Машинист вылез.
wordforms_score охаять { глагол }=-1 // Кто охает?
wordforms_score покадить { глагол }=-1 // Я покажу!
wordforms_score ила { существительное род:жен }=-5 // Я раскопал ил
wordforms_score ос { существительное род:муж }=-5 // В воздухе гудели мухи и осы.
wordforms_score прикроить { глагол }=-2 // Атакуй, прикрою.
wordforms_score ох { существительное }=-2 // Ей это ох как не нравилось.
wordforms_score кровяный { прилагательное }=-2 // Стимулирует кровообращение и снижает кровяное давление.
wordforms_score жило { существительное }=-5 // Именно так выглядит обычный кварц рудных жил.
wordforms_score крон { существительное } =-5 // Видите эти могучие кроны, тяжелые плоды?
wordforms_score утюжка { существительное }=-5
wordforms_score нар { существительное }=-2
wordforms_score подбора { существительное }=-10
wordforms_score кормило { существительное }=-10
wordforms_score дубка { существительное }=-2 // Сам горб порос крепкими дубками.
wordforms_score кода { существительное }=-5 // Серые ячейки указывают на неназначенные коды
wordforms_score песнь { существительное }=-1 // Проводится круглогодичный конкурс бардовской песни.
wordforms_score тоника { существительное }=-10
wordforms_score рака { существительное }=-10
wordforms_score бахчевый { прилагательное }=-5 // Особое внимание уделялось бахчевым культурам.
wordforms_score нецелевый { прилагательное }=-5 // Процветало нецелевое использование этих средств.
wordforms_score запасный { прилагательное }=-5 // Пятигорский вокзал был запасным вариантом.
wordforms_score бредовой { прилагательное }=-5 // Первая стопка содержала бредовые работы.
wordforms_score меньшой { прилагательное }=-5 // Такие передачи имеют меньшую аудиторию.
wordforms_score меховый { прилагательное }=-5 // Летняя распродажа меховых изделий продолжается!
wordforms_score заводский { прилагательное }=-10 // Существует заводская группа внутренних аудиторов.
wordforms_score щенка { существительное }=-10 // Продаются красивые щенки йоркширского терьера.
wordforms_score кур { существительное }=-10
wordforms_score любый { прилагательное }=-10 // Для него любая власть является раздражителем.
wordforms_score ванный { прилагательное }=-1 // большая ванная
wordforms_score плавной { прилагательное }=-10 // Такая конструкция обеспечивает плавное перемещение
wordforms_score санатория { существительное }=-10
wordforms_score шпалер { существительное }=-10
wordforms_score хромый { прилагательное }=-5 // Волшебный лепесток излечивает хромого мальчика.
wordforms_score газа { существительное }=-1 // Раскаленные газы с чудовищной силой вырываются
wordforms_score рейки { род:ср }=-10 // Многочисленные рейки стягивала стальная проволока.
wordforms_score протяжной { прилагательное }=-5 // Каменные своды отозвались протяжным эхом.
wordforms_score страстной { прилагательное }=-2 // Страстная любовь вызывает страстную борьбу.
wordforms_score дневный { прилагательное }=-2 // Дневная суета сменилась полной тишиной.
wordforms_score хромый { прилагательное }=-2 // Гони эту свору хромого горбуна!
wordforms_score восковой { прилагательное }=-5 // Восковые свечи разливали мягкое сияние.
wordforms_score угловый { прилагательное }=-5 // Угловая камера записала этот момент.
wordforms_score пестрить { глагол }=-10 // Мировая пресса пестрит сенсационными сообщениями.
wordforms_score чина { существительное }=-5 // Это требование поддержали высшие чины.
wordforms_score языковый { прилагательное }=-5
wordforms_score половый { прилагательное }=-5 // Переполненный желудок затрудняет половой акт.
wordforms_score шампанский { прилагательное }=-5
wordforms_score замок { глагол }=-10 // Замок небольшой и необычный.
wordforms_score синоптика { существительное }=-5 // Русский сухогруз утопили турецкие синоптики.
wordforms_score корректив { существительное род:муж }=-10 // Президентские выборы вносят определенные коррективы.
wordforms_score поджога { существительное род:жен }=-10 // Умышленные поджоги стали доходным бизнесом.
wordforms_score матерь { существительное }=-1
wordforms_score плюсовый { прилагательное }=-1
wordforms_score экой { прилагательное }=-1 // Экую несуразицу плетет этот мужик.
wordforms_score овсяной { прилагательное }=-5 // Сморщенный чиновник жует овсяную лепешку.
wordforms_score хмельный { прилагательное }=-1 // Остался ровный шелест хмельных кипарисов.
wordforms_score спазма { существительное }=-10 // Пустой желудок разрывали болезненные спазмы.
wordforms_score мазка { существительное }=-10 // Замельтешили нервные мазки ярких красок...
wordforms_score громовый { прилагательное }=-5 // Эти вспышки сопровождались громовыми ударами.
wordforms_score зарев { существительное }=-10 // Длинные пальцы налились красноватым заревом.
wordforms_score шара { существительное }=-5 // Латунные шары заполнялись керосиновой смесью.
wordforms_score корн { существительное }=-5 // в корне мандрагоры содержится наркотический сок
wordforms_score справа { существительное }=-10 // Справа Дэни разглядела маленькое каменное святилище.
wordforms_score теля { существительное }=-5 // Было чувство клаустрофобии в собственном теле.
wordforms_score коленной { прилагательное }=-5 // 26-летний футболист получил растяжение коленного сустава.
wordforms_score полом { существительное }=-5 // Бойцы рыли под полом окопы.
wordforms_score бород { существительное }=-5 // Елена просит молодого мужа сбрить бороду.
wordform_score присутствия { число:мн }=-5 // // Ей стало не хватать его присутствия.
wordform_score косы { род:муж число:мн }=-10 // Ее косы были убраны под шапку.
wordform_score обожания { число:мн }=-10 // Изливают любвеобильные лучи обожания
wordform_score смелости { число:мн }=-10 // Ей просто недоставало смелости его сделать.
wordform_score ясности { число:мн }=-10 // Черные ящики не добавили ясности.
wordform_score с { частица }=-2 // // Загадали желания – ждем-с!
wordform_score "ей-богу"{} = 10 // Ей-богу, отлично выйдет.
wordform_score дыхания { число:мн }=-2 // Ее подключили к аппарату искусственного дыхания.
wordform_score реставрации { число:мн }=-2 // Ее не ремонтировали со времен Реставрации.
wordform_score бересты { число:мн }=-10 // Сверху настелили большие куски бересты.
wordform_score охоты { число:мн }=-10 // Сезон охоты откроют 25 августа.
wordform_score развития { существительное число:мн }=-10 // В Чувашии обсуждают проблемы инновационного развития регионов
wordform_score наглости { существительное число:мн }=-10 // противопоставить наглости
wordform_score еды { существительное число:мн }=-5 // хозяин должен дать еды
wordform_score безопасности { существительное число:мн }=-5 // Его обвинили в пренебрежении вопросами безопасности.
wordform_score выдержки { существительное число:мн }=-5 // Если хватит выдержки...
wordform_score истерик { существительное }=-2 // И хватит истерик!
wordform_score послезавтра { существительное }=-5 // Послезавтра утром проверю...
wordform_score дискриминации { число:мн }=-5 // Его называли анахронизмом и признаком дискриминации.
wordform_score полиции { число:мн }=-5 // Его доставили в 20-й отдел полиции.
wordform_score уверенности { число:мн }=-10 // Его немое обожание придавало Анне уверенности.
wordform_score насилия { число:мн }=-5 // А насилия Рекс никогда не совершит.
wordform_score болтовни { число:мн }=-10 // А теперь хватит болтовни, Кейн.
wordform_score оружия { число:мн }=-10 // А Филип вообще не любит оружия.
wordform_score внимания { число:мн }=-10 // А на брата не обращай внимания.
wordform_score бытия { число:мн }=-10 // Имеют телесную форму предшествовавшего бытия.
wordform_score сочувствия { число:мн }=-5 // А вот Мария действительно заслуживает сочувствия.
wordform_score разнообразия { число:мн }=-5 // Болото хотело разнообразия в компании.
wordform_score ним { существительное }=-5 // А вместе с ним и свою душу.
wordform_score ник { глагол }=-5 // А ты как думаешь, Ник?
wordform_score тете { одуш:неодуш }=-1 // А перед этим послал тете цветы.
wordform_score гораздо { прилагательное }=-5 // А кажется, что гораздо больше.
wordform_score Калифорнии { число:мн }=-10 // А в Калифорнии сейчас цветет мимоза.
wordform_score замок { глагол }=-10 // А на краю леса красивый замок.
wordform_score мирке { род:жен }=-5 // В их мирке вдруг оказался третий.
wordform_score жалости { число:мн }=-5 // В этом деле не знают жалости.
wordform_score орала { существительное }=-5 // Я била подушки и орала в ярости.
wordform_score яркости { число:мн }=-2 // Второй цвет добавляет яркости и выразительности.
wordform_score выразительности { число:мн }=-10 // Второй цвет добавляет яркости и выразительности.
wordform_score македонии { число:мн }=-10 // Встретились главы МИД России и Македонии.
wordform_score бочками { род:муж }=-5 // Грузить апельсины бочками?
wordform_score полдня { существительное }=-5 // Полдня шел дождь.
wordform_score пол { падеж:род }=-5 // Меряю шагами пол.
wordform_score правей { глагол }=-10 // Еще чуть правей...
wordform_score чуточку { существительное }=-10 // Самолет чуточку подбросило.
wordform_score правосудья { число:мн }=-10 // Жид хочет правосудья
wordform_score единства { число:мн }=-10 // Партия хочет единства.
wordform_score счастья { число:мн }=-10 // Все хотят счастья.
wordform_score агрессии { число:мн }=-10 // Фашизм хочет агрессии?..
wordform_score горючки { число:мн }=-10 // Не хватило горючки.
wordform_score усмирения { число:мн }=-10 // Потребовать усмирения Петрограда.
wordform_score метель { глагол }=-15 // На улице метель.
wordform_score ясней { глагол }=-10 // Куда уж ясней.
wordform_score штурману { глагол }=-10 // Штурману тоже трудно.
wordform_score целиком { существительное }=-10 // Скука съела целиком.
wordform_score хмелю { глагол }=-10
wordform_score четкой { существительное }=-2 // Работа персонала была четкой
wordform_score милую { глагол }=-10
wordform_score гордости { число:мн }=-10 // Есть другие предметы, достойные гордости.
wordform_score тих { глагол }=-10
wordform_score инфраструктуры { число:мн }=-2 // РАЗРАБОТАЮТ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ЭЛЕКТРОННОЙ ИНФРАСТРУКТУРЫ.
wordform_score ангелы { род:жен }=-5
wordform_score большие { СТЕПЕНЬ:СРАВН }=-10 // большие отели
wordform_score больших { СТЕПЕНЬ:СРАВН }=-10
wordform_score большим { СТЕПЕНЬ:СРАВН }=-10
wordform_score большими { СТЕПЕНЬ:СРАВН }=-10
wordform_score физики { род:жен } =-5 // Волгоградские Физики совершили научную революцию.
wordform_score хорошей { глагол }=-10 // хорошей душевой кабиной
wordform_score стиле { существительное род:ср }=-2 // Продам свадебное платье в греческом стиле
wordform_score молока { род:жен падеж:им }=-2
wordform_score Турции { число:мн }=-5 // В Турции муллы провозглашают священную войну.
wordform_score гости { глагол }=-5 // В саду могут оказаться и гости.
wordform_score администрации { число:мн }=-5 // Структуру администрации Краснодара изменят
wordform_score горячим { глагол }=-5
wordform_score свежую { глагол }=-5 // свежую рыбу
wordform_score голубой { существительное }=-10 // за дверью жил голубой лев
wordform_score фанту { род:муж }=-5
wordform_score фанте { род:муж }=-5
wordform_score баню { ГЛАГОЛ }=-5
wordform_score бань { ГЛАГОЛ }=-5
wordform_score сласти { ГЛАГОЛ }=-10
wordform_score сыр { ПРИЛАГАТЕЛЬНОЕ }=-5
wordform_score сыра { ПРИЛАГАТЕЛЬНОЕ }=-5
wordform_score сыры { ПРИЛАГАТЕЛЬНОЕ }=-5
wordform_score альбом { ПАДЕЖ:ТВОР }=-5 // По запросу могу показать альбом.
wordform_score хоре { падеж:предл одуш:одуш }=-5 // подпевать в церковном хоре
wordform_score Европы { число:мн }=-5 // Ее считали прекраснейшей женщиной Европы.
wordform_score свежую { глагол }=-6 // свежую форель
wordform_score содействия { число:мн }=-5
wordform_score общества { число:мн }=-1 // Индивидуальную честность связали с прогрессивностью общества
wordform_score подготовки { число:мн }=-5 // Процесс подготовки спутника к запуску уместили в короткий видеоролик
wordform_score недвижимости { число:мн }=-10 // Тест: способны ли вы отличить рекламу недвижимости от рекламы презервативов?
wordform_score родины { число:мн }=-2 // Кандидата «Родины» уличили в получении поддельного военного билета
wordform_score защиты { число:мн }=-2 // Google просит защиты у Аркадия Дворковича
wordform_score освобождения { число:мн }=-5 // В Болгарии отпраздновали годовщину освобождения от османского ига
wordform_score веры { число:мн }=-5 // Папу Римского призвали отказаться от догмата своей непогрешимости в вопросах веры
wordforms_score гнома { существительное }=-10 // Но гномы начали погоню
wordform_score рада { существительное }=-2
wordform_score полон { существительное }=-10 // а этот полон ненависти
wordform_score Марин { существительное }=-2 // Алла отпустила Марину
wordforms_score снимка { существительное }=-5
wordforms_score ям { существительное }=-5
wordforms_score купа { существительное }=-5 // мы нашли в его купе
wordforms_score половый { прилагательное }=-5
wordforms_score теста { существительное }=-5 // выявляться тестами
wordforms_score гриба { существительное }=-5 // отравиться грибами
wordforms_score босый { прилагательное }=-5 // ноги ее были босые
wordforms_score арен { существительное }=-5
wordforms_score плат { существительное }=-5
wordforms_score теста { существительное род:жен }=-5
wordforms_score бара { существительное род:жен }=1 // праздновать в баре
wordform_score погиб { существительное }=-5
wordforms_score хора { существительное }=-5
wordforms_score дворовой { прилагательное }=-5
wordforms_score сводной { прилагательное }=-5
wordforms_score шпор { существительное }=-5
wordform_score сдачи { число:мн }=-2 // Сдачи не надо.
wordforms_score комара { существительное }=-5
wordforms_score бара { существительное }=-5
wordforms_score теста { существительное }=-5
wordforms_score венка { существительное }=-5
wordforms_score метода { существительное }=-5
wordforms_score мор { существительное }=-5
wordforms_score мора { существительное }=-5 // Море достаточно холодное
wordform_score трое { существительное }=-5 // трое из мира людей
wordform_score повезло { глагол }=-2 // - Не повезло тебе.
wordforms_score распоряженье { существительное }=-5 // Полицейские стали ждать дальнейших распоряжений.
wordforms_score варианта { существительное род:жен }=-10 // Для разных ситуаций есть предпочтительные варианты.
wordforms_score лангуста { существительное }=-10 // В рыбном купила огромного сырокопченого лангуста.
wordforms_score верховый { прилагательное }=-5 // Бывало, возьмут верховых лошадей и уедут в поле.
wordforms_score об { существительное }=-10
wordforms_score слушанье { существительное }=-5 // Регламент проведения публичных слушаний утверждается постановлением городского парламента.
wordforms_score леса { существительное }=-5 // В алтайских лесах истребили сибирского коконопряда, объедающего хвою
wordforms_score рельса { существительное }=-1 // В основном были подорваны рельсы на второстепенных запасных путях.
wordforms_score перекрытье { существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными.
wordforms_score бракосочетанье { существительное }=-5 // Но в понедельник во Дворце бракосочетания был выходной.
wordforms_score благополучье { существительное } =-5 // В полном благополучии путешественники достигли Вефиля.
wordforms_score лет { род:муж }=-5 // Летом в этой бухте собиралась целая флотилия яхт.
wordforms_score снов { существительное }=-10
wordforms_score така { существительное }=-5 // Сигнал бедствия от лыжницы так и не поступил.
wordforms_score корпусный { прилагательное }=-5 // Снаряд выпустила наша батарея 5-го корпусного артиллерийского полка.
wordforms_score окружный { прилагательное }=-5 // В Агинском округе началась внеочередная сессия окружной думы.
wordforms_score входный { прилагательное }=-5 // Для делегатов напечатали специальные входные билеты.
wordforms_score образной { прилагательное }=-5 // Образное выражение, однако, отражает реальную жизнь.
wordforms_score окружный { прилагательное }=-5 // Финансирование осуществлялось из окружного бюджета.
wordforms_score дверный { прилагательное }=-5
wordforms_score личной{ прилагательное }=-5 // - А ты пробовал концентрировать свои личные мысли?
wordforms_score основный{ прилагательное }=-5 // Основные "боевые" мероприятия проходят в Самаре.
wordforms_score мирной{ прилагательное }=-5 // Уже в мирное время миссии тачали хорошие сапоги;
wordforms_score ЧЕСТНОЙ{ прилагательное }=-5 // Это было хорошее, честное, благородное желание.
wordforms_score РОДНЫЙ{ прилагательное }=-5 // Израильские танкисты приняли меня как родного.
wordforms_score назначенье{ существительное }=-5 // В администрации Алтайского края произошел ряд отставок и назначений
wordforms_score кадра{ существительное }=-5
wordforms_score перекрытье{ существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными.
wordforms_score увечье{ существительное }=-5 // Жертва аварии скончалась в больнице от полученных увечий.
wordforms_score исключенье{ существительное }=-5 // Однако из этого правила существует несколько исключений.
wordforms_score подкрепленье{ существительное }=-5 // При этом используется вероятностная схема подкреплений.
wordforms_score нет{ существительное }=-5 // решение жениться или нет можешь принять только ты сам.
wordforms_score признанье{ существительное }=-5 //
wordforms_score втора{ существительное }=-5
wordforms_score настроенье{ существительное }=-5 // Но антироссийских настроений вы в Грузии не найдете.
wordforms_score заседанье{ существительное }=-5 // Семеро акционеров не были допущены в зал заседаний.
wordforms_score сбора{ существительное }=-5 // В ближайшее время Денис улетает на очередные сборы.
wordforms_score предложенье{ существительное }=-5 // Вячеслав Евгеньевич готовит свой пакет предложений.
wordforms_score свитка{ существительное }=-5 // В кумранских свитках нередко встречается тайнопись
wordforms_score носка{ существительное }=-5 // Из-под подола выглядывали белые спортивные носки.
wordforms_score дыханье{ существительное }=-5 // При виде обнажившихся грудей перехватило дыхание.
wordforms_score усилье{ существительное }=-5 // Бесконечная борьба требовала беспрестанных усилий.
wordforms_score помещенье{ существительное }=-5 // Для обработки помещений ядами привлекают бомжей.
wordforms_score до{ существительное }=-5 // Санкционированная акция прошла с 16 до 17 часов.
wordforms_score ПАРКА{ существительное }=-5 // Королевские парки занимали обширную территорию.
wordforms_score НИМ{ существительное }=-5 // Василий, не отрываясь, следит за ним взглядом.
wordforms_score СТОЛА{ существительное }=-5 // На столе могут вырастать лужайки зеленой пищи.
wordforms_score низка { существительное }=-5
wordforms_score мешка{ существительное }=-5 // Мешки с углем один за другим полетели в темную воду.
wordforms_score стен { существительное }=-5 // По стенам развеваются блестящие знамена света.
wordforms_score ряда { существительное }=-5
wordforms_score так { существительное }=-5
wordforms_score снова { существительное }=-5
wordforms_score лагер { существительное }=-5
wordforms_score гор { существительное }=-5
wordforms_score карт { существительное }=-5 // Военные топографы и геодезисты сверяют карты.
wordforms_score зала { существительное }=-5
wordforms_score зало { существительное }=-5
wordforms_score миро { существительное }=-5 // В макротеле Мира отпечатывается мировая душа.
wordforms_score мира { существительное }=-5
wordforms_score облак { существительное }=-5 // По ночным облакам зарумянилось дымное зарево.
wordforms_score троп { существительное }=-5 // По берегу идут нерегулярные туристские тропы.
wordforms_score пещер { существительное }=-5
wordforms_score ко{ существительное }=-10 // Разумеется, ко мне он больше не показывался.
wordforms_score суда{ существительное }=-5 // В ближайшее время начнется его рассмотрение в суде.
wordform_score "то и дело" { наречие }=5 // Во всяком случае, не придется то и дело нагибаться.
wordform_score "воды" { число:мн } =-1 // они дали ему воды
wordform_score "лицо" { одуш:одуш } =-1
wordform_score "лица" { одуш:одуш } =-1 // Ему даже делают специальный массаж лица.
wordform_score "лицу" { одуш:одуш } =-1
wordform_score "лице" { одуш:одуш } =-1
wordform_score "лицом" { одуш:одуш } =-1
wordform_score "замок" { глагол } =-5 // замок на горе
wordform_score "самогонки" { число:мн } = -1 // Пришлось добавить самогонки.
wordform_score "интуиции" { число:мн } = -1 // Больше доверяют интуиции.
wordform_score "воды" { число:мн } = -1 // Джек добавил воды.
wordform_score "во" { вводное } = -2 // В детях эта программа усиливается во много раз.
wordform_score "на" { глагол } =-1 // В эфир выходили на несколько секунд.
wordform_score "веселей" { глагол } = -8 // В колонне веселей.
wordform_score "гранит" { глагол } = -3 // Почем гранит науки?
wordform_score "катя" { деепричастие } = -2 // Катя, давай!
wordform_score "прочь" { глагол } = -5 // пойти прочь
wordform_score "сволочь" { глагол } = -5 // - Сволочь!
wordform_score "юля" { деепричастие } = -2 // Юля, уважь человека.
wordform_score "катя" { деепричастие } = -2 // я направляюсь сюда, Катя.
wordform_score "женя" { деепричастие } = -2 // Я больше не буду, Женя.
wordform_score "нашей" { глагол } = -3 // - А вот и первые плоды нашей работы!
wordform_score "Камчатки" { число:мн } = -2 // К аварийной подстанции в столице Камчатки подключают новый трансформатор
wordform_score "воротам" { род:муж } = -2 // Беседуя, они подошли к воротам.
wordform_score "один" { существительное } = -5 // Значит, он не один.
wordform_score "то-то" { частица } = 2 // То-то выслуживается, вас гоняет.
wordform_score "погреб" { глагол } =-2 // А вот погреб...
wordform_score "просим" { прилагательное } = -5 // Просим всей группой.
wordform_score "крови" { число:мн } = -5 // Скорее разойдитесь, не проливая крови!
wordform_score "скоро" { прилагательное } = -4 // Скоро в строй?
wordform_score "подъем" { глагол } = -5 // Подъем, товарищ майор!
wordform_score "порой" { глагол } = -5 // И порой не без успеха.
wordform_score "порой" { существительное } = -1 // Они ворчат порой.
wordform_score "погоды" { число:мн } = -3 // По случаю чудной погоды Алексея тоже вывозили кататься.
wordform_score "дарим" { прилагательное} = -5 // - Решено, дарим один ящик командиру полка!
wordform_score "хватит" { глагол } = -1 // - На одну атаку хватит.
wordform_score "как ни в чем не бывало" { наречие } = 1 // Ординарец в сенях спал как ни в чем не бывало.
wordform_score "разве что" { наречие } = 1 // Так жарко бывает разве что перед грозой.
wordform_score "потому что" { союз } =5 // - Потому что мне так нравится.
wordform_score "на поводу у"{ предлог} = 1 // Нельзя идти на поводу у таких состояний
wordform_score "что" { наречие } = -8
wordform_score "так что" { наречие } = -5 // Ну, так что вы скажете?
wordform_score "вот" { наречие } = -3
wordform_score "Иду" { существительное } = -3 // - Иду к тебе!
wordform_score "хотите" { НАКЛОНЕНИЕ:ПОБУД } = -5
wordform_score "всего" { наречие } = -4 // Он всего боялся
wordform_score "всего лишь" { наречие } = 2
wordform_score "еле-еле" { наречие } = 2
wordform_score "туда-сюда" { наречие } = 2
wordform_score "туда-то" { наречие } = 2
wordform_score "отчего-то" { наречие } = 2
wordform_score "когда-то" { наречие } = 2
wordform_score "чуть-чуть" { наречие } = 2
wordform_score "так-то" { наречие } = 2
wordform_score "наконец-то" { наречие } = 2
wordform_score "туда-то" { наречие } = 2
wordform_score "тут-то" { наречие } = 2
wordform_score "Наконец-то" { наречие } = 2
wordform_score "добро" { наречие } = -4 // - Знаю я это добро.
wordform_score "должно" { наречие } = -5 // Но так и должно быть.
wordform_score "тем не менее" { наречие } = 1
wordform_score "прежде всего" { наречие } = 1 // Нужно прежде всего знать группу крови.
wordform_score "выходит" { наречие } = -2 // это из тебя страх так выходит
wordform_score "трибуны" { одуш:одуш } = -2 // Трибуны взрываются аплодисментами.
wordform_score "по прошествии" { предлог } = 5 // По прошествии двух дней следствие не может установить их личности.
wordform_score "сроком на" { предлог } = 2 // Аэропорт перешел в управление компании сроком на 30 лет.
// Я ничего подобного не видал
wordform_score "ничего" { наречие } = -5
// Не было таких прецедентов пока что.
// ^^^^^^^^
wordform_score "пока что" { наречие } = 1
wordform_score "приводим" { прилагательное } = -5 // Приводим полный текст этого заявления.
// Она поколебалась, прежде чем ответить.
// ^^^^^^^^^^
wordform_score "прежде чем" { союз } = 1
wordform_score "а то" { союз } = 1 // А то тебе плохо станет.
wordform_score "не то" { союз } = 1 // Вставай, не то опоздаем
wordform_score "а не то" { союз } = 1 // Сядь, а не то упадешь
// кости у всех одинаковые
// ^^^^^
wordform_score "кости" { глагол } = -3
wordform_score "чести" { глагол } = -3
// Мы знаем друг друга много лет
// ^^^^^^^^^^
wordform_score "друг друга" { существительное падеж:парт } = -1
// Текст речи премьер-министра
// ^^^^^^^^^^^^^^^^
wordform_score "премьер-министр" { существительное } = 1
wordform_score "премьер-министра" { существительное } = 1
wordform_score "премьер-министром" { существительное } = 1
wordform_score "премьер-министру" { существительное } = 1
wordform_score "премьер-министре" { существительное } = 1
wordform_score "премьер-министры" { существительное } = 1
wordform_score "премьер-министров" { существительное } = 1
wordform_score "премьер-министрами" { существительное } = 1
wordform_score "премьер-министрам" { существительное } = 1
wordform_score "премьер-министрах" { существительное } = 1
// Хотим получить максимум информации
// ^^^^^^^^^^
wordform_score "информации" { существительное число:мн } = -5
wordform_score "тому назад" { послелог } = 1
// Он просто вынужден закончить цикл историй, так как ограничены размеры книги.
wordform_score "так как" { союз } = 5
// Поможем ему сена накосить
// ^^^^
wordform_score "сена" { существительное число:мн } = -5
// Подавляем множественное число "ПУШОК":
// "Мы видели их пушки"
wordform_score "пушки" { существительное род:муж } = -5
wordform_score "это" { частица } = -2
// Кажется, вчера еще бродил я в этих рощах.
wordform_score "кажется" { наречие } = -2
wordform_score "лицом к лицу" { наречие } = 5
// из конюшни они возвращались бок о бок.
wordform_score "бок о бок" { наречие } = 2
// люди спят тем более.
wordform_score "тем более" { наречие } = 2
wordform_score "в связи с" { предлог } = 1
// то есть могла бы
wordform_score "то есть" { союз } = 3
// ПОКАДИТЬ(ПОКАЖУ)
// wordform_score "покажу" { глагол глагол:покадить{} } = -5
// ПРОПАСТЬ>ПРОПАЛИТЬ(ПРОПАЛИ)
wordform_score "пропали" { глагол наклонение:побуд } = -5
// ПОПАСТЬ > ПОПАЛИТЬ
wordform_score "попали" { глагол наклонение:побуд } = -5
// предпочитаем вариант безличного глагола:
//wordform_score "оставалось" { глагол } = -2
//wordform_score "остается" { глагол } = -2
//wordform_score "останется" { глагол } = -2
//wordform_score "осталось" { глагол } = -2
wordform_score "стали" { существительное число:мн } = -5
wordform_score "стали" { существительное падеж:род } = -3
// Жаль, если принятые обязательства не выполняются
// ^^^^
wordform_score "жаль" { глагол } = -3
wordform_score "давным-давно" { наречие } = 2
// Можно ли сейчас применять старые методы?
wordform_score "методам" { существительное род:жен } = -5
wordform_score "методах" { существительное род:жен } = -5
wordform_score "методу" { существительное род:жен } = -5
wordform_score "методе" { существительное род:жен } = -5
wordform_score "метода" { существительное род:жен } = -5
wordform_score "методы" { существительное род:жен } = -5
// Не вижу необходимости
// ^^^^^^^^^^^^^
wordform_score "необходимости" { число:мн } = -1
wordform_score "о" { частица } = -2
wordform_score "Спешите" { наклонение:побуд } = -1
// отдадим преимущество безличной форме:
// мне удалось поспать
// ^^^^^^^
wordform_score "удалось" { глагол } = -3
// Придавим вариант "ПАР^ОК"
// В парке был бассейн с золотыми рыбками.
// ^^^^^
wordform_score "парке" { ПЕРЕЧИСЛИМОСТЬ:НЕТ } = -10
// слово БЫЛО редко выступает в роли наречия, но иногда бывает:
// один из воинов пошел было к дверям
// ^^^^
wordform_score "было" { наречие } = -10
// Это было примерно месяц назад
wordform_score "примерно" { прилагательное } = -2
// чтобы подавить ВРЯД(ЛИ)
wordform_score "вряд ли" { наречие } = 2
// при помощи женской страсти?
// ^^^^^^^^^^
wordform_score "при помощи" { предлог } = 5
wordform_score "Владимиру" { существительное род:жен } = -2
wordform_score "Владимира" { существительное род:жен } = -2
wordform_score "Владимире" { существительное род:жен } = -2
// у тебя впереди серьезное дело
wordform_score "дело" { глагол } = -5
wordform_score "правды" { существительное число:мн } = -2
// ты сволочь
wordform_score "сволочь" { глагол } = -2
// во мне все же росло беспокойство
wordform_score "росло" { прилагательное } = -1
// конкуренция между ЗАБРАТЬ.гл и ЗАБРАЛО.сущ
wordform_score "забрала" { существительное } = -2
wordform_score "забрало" { существительное } = -2
wordform_score "забрал" { существительное } = -2
// обычно ЗАВТРА - наречие:
// можно зайти за этим завтра?
// ^^^^^^
wordform_score "завтра" { существительное } = -10
wordform_score "сегодня" { существительное } = -15
// взять деньги
wordform_score "деньги" { существительное падеж:род } = -10
// Подавляем просторечный вариант "Сашок"
// Сашка не знал
wordform_score "Сашка" { существительное падеж:вин } = -1
wordform_score "Сашка" { существительное падеж:род } = -1
// обычно это - прилагательное
wordform_score "простой" { глагол } = -1
// есть варианты ТУШЬ и ТУША (помимо глагола ТУШИТЬ). Вариант ТУШЬ гасим.
wordform_score "тушь" { существительное одуш:неодуш } = -5
// обычно ПОЧТИ - это наречие
// Почти совсем темно.
// ^^^^^
wordform_score "почти" { глагол } = -5
// теперь самое время бросить кости
wordform_score "кости" { глагол } = -5
wordform_score "брехло" { наречие } = -10
wordform_score "силой" { наречие } = -2
wordform_score "может" { вводное } = -1
// скорее доедай
wordform_score "скорее" { вводное } = -1
wordform_score "пять" { глагол } = -5
wordform_score "спины" { существительное род:муж } = -1
wordform_score "спинах" { существительное род:муж } = -1
wordform_score "спине" { существительное род:муж } = -1
// хозяин дает корм псам
wordform_score "корм" { существительное род:жен падеж:род } = -5
// несмотря на жару, солдаты носили шлемы и кирасы.
wordform_score "несмотря на" { предлог } = 10
// В соответствии с шариатом, свинину употреблять запрещено
// ^^^^^^^^^^^^^^^^
wordform_score "В соответствии с" { предлог } = 2
wordform_score "В соответствии со" { предлог } = 2
// В Дамаске в ходе ракетного обстрела погиб чиновник Евросоюза
// ^^^^^^
wordform_score "в ходе" { предлог } = 2
// Мы пошли вместе по направлению к городу.
// ^^^^^^^^^^^^^^^^
wordform_score "по направлению к" { предлог } = 2
wordform_score "по направлению ко" { предлог } = 2
// шеф просит еще раз проверить
// wordform_score "еще раз" { наречие } = 10
// очень трудно найти задачу по силам
wordform_score "по силам" { безлич_глагол } = -1
// есть все же средства
// ^^^^^^
wordform_score "все же" { наречие } = 10
// все время находился в командировках
// ^^^^^^^^^
//wordform_score "все время" { наречие } = 2
// Однако эти средства до сих пор не дошли до реального сектора экономики
wordform_score "до сих пор" { наречие } = 10
// сбыться на самом деле
wordform_score "на самом деле" { наречие } = 10
// Лошадь встала на дыбы.
wordform_score "встать на дыбы" { инфинитив } = 2
wordform_score "встала на дыбы" { глагол } = 2
wordform_score "встал на дыбы" { глагол } = 2
wordform_score "встали на дыбы" { глагол } = 2
wordform_score "встанет на дыбы" { глагол } = 2
wordform_score "пузырь" { глагол } = -2
// выражение его лица было довольно странным
wordform_score "довольно" { прилагательное } = -1
// они как будто пришли издалека
// ^^^^^^^^^
wordform_score "как будто" { наречие } = 2
// Лошадь встала на дыбы.
wordform_score "встать на дыбы" { глагол } = 2
// мой друг как всегда был прав
// ^^^^^^^^^^
wordform_score "как всегда" { наречие } = 2
// без кольца все стало как обычно
// ^^^^^^^^^^
wordform_score "как обычно" { наречие } = 2
// однако совершенно необходимо время от времени менять темп.
// ^^^^^^^^^^^^^^^^
wordform_score "время от времени" { наречие } = 5
// все равно уже сорвал
// ^^^^^^^^^
wordform_score "все равно" { наречие } = 10
// деревья полностью закрывают серое небо
// ^^^^^^^^^
wordform_score "полностью" { существительное } = -100
// волосы обоих были все еще мокрые.
// ^^^^^^^
wordform_score "все еще" { наречие } = 2
// всего один день.
wordform_score "день" { глагол } = -1
// ты все это прекрасно знаешь
// ^^^^^^^
wordform_score "все это" { местоим_сущ } = 1
// Андрюха хотел жить на отшибе
// ^^^^^^^^^
wordform_score "на отшибе" { наречие } = 1
// ПОЙМА vs ПОНЯТЬ
wordform_score "пойму" { существительное } = -1
// лучше всего сделать это сразу
// ^^^^^^^^^^^
wordform_score "лучше всего" { безлич_глагол } = 1
wordform_score "нахожусь" { глагол вид:соверш } = -2
wordform_score "находимся" { глагол вид:соверш } = -2
wordform_score "находится" { глагол вид:соверш } = -2
wordform_score "находитесь" { глагол вид:соверш } = -2
wordform_score "находился" { глагол вид:соверш } = -2
wordform_score "находилась" { глагол вид:соверш } = -2
wordform_score "находилось" { глагол вид:соверш } = -2
wordform_score "находились" { глагол вид:соверш } = -2
wordform_score "находим" { прилагательное } = -5 // В Полинезии находим культ черепов вождей.
wordform_score пошли { глагол время:прошедшее } = 1 // мы пошли домой
wordform_score пошли { глагол наклонение:побуд } = -1 // не пошли!
wordform_score спешить { инфинитив вид:несоверш } = 1 // спеш^ить (торопиться)
wordform_score спешил { глагол вид:несоверш }=1
wordform_score спешила { глагол вид:несоверш }=1
wordform_score спешили { глагол вид:несоверш }=1
wordform_score спеши { глагол вид:несоверш }=1
wordform_score спешить { инфинитив вид:соверш } =-2 // сп^ешить (спустить с коня на землю)
wordform_score спешил { глагол вид:соверш }=-2
wordform_score спешила { глагол вид:соверш }=-2
wordform_score спешили { глагол вид:соверш }=-2
wordform_score лето { существительное род:ср } = 1
wordform_score лёт { существительное род:муж } = -5
// Коля, давай-ка выпей молока
wordform_score выпей { глагол } = 1
wordform_score выпей { существительное } = -2
wordform_score видно { наречие } = -3
//wordform_score видно { прилагательное } = 0
//wordform_score видно { вводное } = -1
//wordform_score времени { существительное } = 1
wordform_score времени { глагол } = -5 // О факторе времени.
//wordform_score перед { предлог } = 1
wordform_score перед { существительное } = -2
wordform_score на { предлог } = 1
wordform_score на { частица } = -10
wordform_score жил { существительное } = -1 // жила
wordform_score жил { глагол } = 1 // жить
wordform_score любой { существительное } = -1 // Люба
wordform_score жал { существительное } = -10 // жало
wordform_score жал { глагол } = 1 // жать
wordform_score велик { прилагательное } = -1 // великий
wordform_score велика { существительное } = -10
wordform_score велика { прилагательное } = 1 // великий
wordform_score велики { существительное } = -10
wordform_score велики { прилагательное } = 1 // великий
wordform_score были { существительное } = -10
wordform_score были { глагол } = 1
wordform_score весь { существительное } = -10
wordform_score весь { глагол } = -10
wordform_score весь { прилагательное } = 1
wordform_score вещей { существительное } = 1
wordform_score вещей { прилагательное } = -1
wordform_score времени { глагол } = -10
wordform_score времени { существительное } = 1
//wordform_score все { местоим_сущ } = 1
//wordform_score все { прилагательное } = 1
wordform_score все { наречие } = -2
wordform_score все { частица } = -2
wordform_score всей { глагол } = -10
wordform_score всей { прилагательное } = 1
//wordform_score дали { глагол } = 1
wordform_score дали { существительное } = -1
//wordform_score смог { глагол } = 1
wordform_score смог { существительное } = -1
wordform_score действительно { прилагательное } = -10
wordform_score действительно { наречие } = 1
// wordform_score дел { существительное } = 1
// wordform_score дел { глагол } = 1
wordform_score дело { существительное } = 1
wordform_score дело { глагол } = -1
// wordform_score дела { существительное } = 1
// wordform_score дела { глагол } = 1
wordform_score день { существительное } = 1
wordform_score день { глагол } = -10
wordform_score для { предлог } = 1
wordform_score для { деепричастие } = -10
wordform_score какая { прилагательное } = 1
wordform_score какая { деепричастие } = -10
wordform_score конечно { прилагательное } = -1
wordform_score конечно { наречие } = 1
wordform_score мая { существительное одуш:неодуш } = 1
wordform_score мая { существительное одуш:одуш } = -1
wordform_score моря { существительное } = 1
wordform_score моря { деепричастие } = -10
wordform_score моя { прилагательное } = 1
wordform_score моя { деепричастие } = -10
wordform_score особой { прилагательное } = 1
wordform_score особой { существительное } = -1
wordform_score пора { существительное } = -1
wordform_score пора { безлич_глагол } = 1
wordform_score при { предлог } = 1
wordform_score при { глагол } = -10
wordform_score разрыв { существительное } = 1
wordform_score разрыв { деепричастие } = -1
wordform_score совести { существительное число:ед } = 1
wordform_score совести { существительное число:мн } = -5
wordform_score совести { глагол } = -2
wordform_score хвои { глагол } = -2 // Кубдя подбросил хвои.
wordform_score споров { существительное } = 1
wordform_score споров { деепричастие } = -1
wordform_score стать { существительное } = -1
wordform_score стать { инфинитив } = 1
wordform_score такая { деепричастие } = -10 // такать
wordform_score такая { прилагательное } = 1
wordform_score три { глагол } = -1 // тереть
wordform_score три { числительное } = 1
wordform_score тут { существительное одуш:неодуш } = -10 // тут (тутовое дерево)
wordform_score тут { наречие } = 1
wordform_score уж { частица } = 1
wordform_score уж { наречие } = 1
wordform_score уж { существительное } = -2
wordform_score уже { наречие степень:атриб } = 1
wordform_score уже { прилагательное } = -3 // узкий
wordform_score уже { существительное } = -2
wordform_score уже { наречие степень:сравн } = -5 // узко
wordform_score хотя { деепричастие } = -10 // хотеть
wordform_score хотя { союз } = 1
// краткие формы среднего рода прилагательных используются очень редко, в отличие
// от буквально совпадающих с ними наречий
#define PreferAdverb(x) \
#begin
//wordform_score x { наречие } = 2000000
wordform_score x { прилагательное } = -2
#end
PreferAdverb( "абсолютно" )
PreferAdverb( "абстрактно" )
PreferAdverb( "абсурдно" )
PreferAdverb( "аварийно" )
PreferAdverb( "автоматично" )
PreferAdverb( "авторитарно" )
PreferAdverb( "авторитетно" )
PreferAdverb( "азартно" )
PreferAdverb( "аккуратно" )
PreferAdverb( "активно" )
PreferAdverb( "актуально" )
PreferAdverb( "алогично" )
PreferAdverb( "амбивалентно" )
PreferAdverb( "аномально" )
PreferAdverb( "анонимно" )
PreferAdverb( "аргументировано" )
PreferAdverb( "аристократично" )
PreferAdverb( "архиважно" )
PreferAdverb( "аскетично" )
PreferAdverb( "афористично" )
PreferAdverb( "капризно" )
PreferAdverb( "кардинально" )
PreferAdverb( "карикатурно" )
PreferAdverb( "категорично" )
PreferAdverb( "качественно" )
PreferAdverb( "классно" )
PreferAdverb( "комично" )
PreferAdverb( "комфортабельно" )
PreferAdverb( "комфортно" )
PreferAdverb( "конвульсивно" )
PreferAdverb( "конечно" )
PreferAdverb( "конкретно" )
PreferAdverb( "конструктивно" )
PreferAdverb( "контрастно" )
PreferAdverb( "концептуально" )
PreferAdverb( "корректно" )
PreferAdverb( "кратковременно" )
PreferAdverb( "крестообразно" )
PreferAdverb( "кристально" )
PreferAdverb( "круглосуточно" )
PreferAdverb( "курьезно" )
PreferAdverb( "кучно" )
PreferAdverb( "комплиментарно" )
PreferAdverb( "агрессивно" )
PreferAdverb( "адекватно" )
PreferAdverb( "алчно" )
PreferAdverb( "амбициозно" )
PreferAdverb( "аморально" )
PreferAdverb( "аналогично" )
PreferAdverb( "анекдотично" )
PreferAdverb( "апатично" )
PreferAdverb( "аполитично" )
PreferAdverb( "артистично" )
PreferAdverb( "асимметрично" )
PreferAdverb( "ассоциативно" )
PreferAdverb( "красно" )
PreferAdverb( "конфиденциально" )
PreferAdverb( "клятвенно" )
PreferAdverb( "краткосрочно" )
PreferAdverb( "круглогодично" )
PreferAdverb( "когерентно" )
PreferAdverb( "конъюнктурно" )
PreferAdverb( "конформно" )
PreferAdverb( "асинхронно" )
PreferAdverb( "аритмично" )
PreferAdverb( "альтруистично" )
PreferAdverb( "критично" )
PreferAdverb( "авантюрно" )
PreferAdverb( "автобиографично" )
PreferAdverb( "автономно" )
PreferAdverb( "аддитивно" )
PreferAdverb( "ажурно" )
PreferAdverb( "азбучно" )
PreferAdverb( "академично" )
PreferAdverb( "аллегорично" )
PreferAdverb( "альтернативно" )
PreferAdverb( "аморфно" )
PreferAdverb( "антагонистично" )
PreferAdverb( "антинаучно" )
PreferAdverb( "антиобщественно" )
PreferAdverb( "аппетитно" )
PreferAdverb( "ароматно" )
PreferAdverb( "архаично" )
PreferAdverb( "атипично" )
PreferAdverb( "аутентично" )
PreferAdverb( "каверзно" )
PreferAdverb( "капитально" )
PreferAdverb( "каплеобразно" )
PreferAdverb( "катастрофично" )
PreferAdverb( "келейно" )
PreferAdverb( "клешнеобразно" )
PreferAdverb( "клиновидно" )
PreferAdverb( "клинообразно" )
PreferAdverb( "коварно" )
PreferAdverb( "комедийно" )
PreferAdverb( "консервативно" )
PreferAdverb( "конституционно" )
PreferAdverb( "конусовидно" )
PreferAdverb( "конусообразно" )
PreferAdverb( "корыстно" )
PreferAdverb( "косвенно" )
PreferAdverb( "косноязычно" )
PreferAdverb( "кошмарно" )
PreferAdverb( "кощунственно" )
PreferAdverb( "красочно" )
PreferAdverb( "криводушно" )
PreferAdverb( "кровожадно" )
PreferAdverb( "крохотно" )
PreferAdverb( "крупно" )
PreferAdverb( "культурно" )
PreferAdverb( "куполообразно" )
PreferAdverb( "кустарно" )
PreferAdverb( "акцентировано" )
/*-----------------------
select F1.name as word, Concat( '// ', C1.name, ':', E1.name, '{} и ', C2.name, ':', E2.name, '{}' )
from sg_entry E1, sg_entry E2, sg_form F1, sg_form F2, sg_class C1, sg_class C2
where E1.id_class!=E2.id_class and E1.name!='???' and
F1.id_entry=E1.id and F2.id_entry=E2.id and F1.name=F2.name and C1.id=E1.id_class and C2.id=E2.id_class and
E1.id<E2.id
order by F1.name
-------------------------*/
wordform_score "атакуем" { глагол } = 1 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{}
wordform_score "атакуем" { прилагательное } = -10 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{}
wordform_score "классифицируем" { глагол } = 1 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{}
wordform_score "классифицируем" { прилагательное } = -10 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{}
wordform_score "компенсируем" { глагол } = 1 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{}
wordform_score "компенсируем" { прилагательное } = -10 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{}
wordform_score "Коля" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ДЕЕПРИЧАСТИЕ:коля{}
wordform_score "Коля" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Коли" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и СОЮЗ:коли{}
wordform_score "Коли" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Колю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Колю" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Кати" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{}
wordform_score "Кати" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{}
wordform_score "куплю" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{}
wordform_score "куплю" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{}
wordform_score "крали" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{}
wordform_score "крали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{}
wordform_score "крести" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{}
wordform_score "крести" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{}
wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыло" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыла" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыла" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыло" { ГЛАГОЛ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "ком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "ком" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кому" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "Костя" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{}
wordform_score "Костя" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{}
wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{}
wordform_score "кувырком" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{}
wordform_score "колея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{}
wordform_score "колея" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{}
wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "канал" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "канала" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "автостопом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{}
wordform_score "автостопом" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{}
wordform_score "Ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{}
wordform_score "Ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{}
wordform_score "кладу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{}
wordform_score "кладу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{}
wordform_score "клей" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{}
wordform_score "клей" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{}
wordform_score "клея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{}
wordform_score "клея" { ДЕЕПРИЧАСТИЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{}
wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{}
wordform_score "кубарем" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{}
wordform_score "калачиком" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{}
wordform_score "калачиком" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{}
wordform_score "ковали" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{}
wordform_score "ковали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{}
wordform_score "Алле" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{}
wordform_score "Алле" { ЧАСТИЦА } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{}
wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кому" { МЕСТОИМ_СУЩ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кисла" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "кисла" { ГЛАГОЛ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "кисло" { наречие } = 2
wordform_score "кисло" { ПРИЛАГАТЕЛЬНОЕ } = -2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "кисло" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "конвертируем" { ПРИЛАГАТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{}
wordform_score "конвертируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{}
wordform_score "клади" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{}
wordform_score "клади" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{}
wordform_score "копи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{}
wordform_score "копи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{}
wordform_score "крепи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{}
wordform_score "крепи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{}
wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{}
wordform_score "крошку" { НАРЕЧИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{}
wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "какой" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
//wordform_score "какой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
wordform_score "какою" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
wordform_score "какою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
// СУЩЕСТВИТЕЛЬНОЕ:кака{} и СОЮЗ:как{}
wordform_score "как" { СОЮЗ } = 3
wordform_score "как" { НАРЕЧИЕ } = 2
wordform_score "как" { ЧАСТИЦА } = 1
wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10
wordform_score "ковка" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{}
wordform_score "ковка" { ПРИЛАГАТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{}
wordform_score "кучу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{}
wordform_score "кучу" { ГЛАГОЛ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{}
wordform_score "кручу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{}
wordform_score "кручу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{}
wordform_score "круче" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{}
wordform_score "круче" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{}
wordform_score "круче" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ПРИЛАГАТЕЛЬНОЕ:крутой{}
wordform_score "как" { СОЮЗ } = 3 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{}
wordform_score "как" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{}
wordform_score "как" { ЧАСТИЦА } = 0 // НАРЕЧИЕ:как{} и СОЮЗ:как{}
wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:как{} и ЧАСТИЦА:как{}
wordform_score "кругом" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{}
wordform_score "кругом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{}
wordform_score "кувырком" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{}
wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{}
wordform_score "каплю" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{}
wordform_score "каплю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{}
wordform_score "крошечку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{}
wordform_score "крошечку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{}
wordform_score "крошку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{}
wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{}
wordform_score "кубарем" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{}
wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{}
wordform_score "кипуче" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{}
wordform_score "кипуче" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{}
wordform_score "куце" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{}
wordform_score "куце" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{}
wordform_score "антенной" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{}
wordform_score "антенной" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{}
wordform_score "анализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{}
wordform_score "анализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{}
wordform_score "ассоциируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{}
wordform_score "ассоциируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{}
wordform_score "культивируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:культивируемый{} и ГЛАГОЛ:культивировать{}
wordform_score "контролируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:контролируемый{} и ГЛАГОЛ:контролировать{}
wordform_score "автоматизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{}
wordform_score "автоматизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{}
wordform_score "адаптируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{}
wordform_score "адаптируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{}
wordform_score "адресуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{}
wordform_score "адресуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{}
wordform_score "аккумулируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{}
wordform_score "аккумулируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{}
wordform_score "акцептуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{}
wordform_score "акцептуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{}
wordform_score "акционируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{}
wordform_score "акционируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{}
wordform_score "амортизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{}
wordform_score "амортизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{}
wordform_score "арендуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{}
wordform_score "арендуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{}
wordform_score "афишируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{}
wordform_score "афишируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{}
wordform_score "капитализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{}
wordform_score "капитализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{}
wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "комментируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{}
wordform_score "комментируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{}
wordform_score "коммутируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{}
wordform_score "коммутируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{}
wordform_score "конвоируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{}
wordform_score "конвоируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{}
wordform_score "координируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{}
wordform_score "координируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{}
wordform_score "котируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{}
wordform_score "котируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{}
wordform_score "кредитуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{}
wordform_score "кредитуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{}
wordform_score "критикуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{}
wordform_score "критикуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{}
wordform_score "курируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{}
wordform_score "курируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{}
wordform_score "корректируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{}
wordform_score "корректируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{}
wordform_score "ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{}
wordform_score "ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{}
wordform_score "кочевым" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{}
wordform_score "кочевым" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{}
wordform_score "атакуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{}
wordform_score "атакуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{}
wordform_score "казним" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{}
wordform_score "казним" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{}
wordform_score "качаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{}
wordform_score "качаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{}
wordform_score "кусаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{}
wordform_score "кусаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{}
wordform_score "компенсируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{}
wordform_score "компенсируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{}
wordform_score "караем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{}
wordform_score "караем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{}
wordform_score "командируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{}
wordform_score "командируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{}
wordform_score "конструируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{}
wordform_score "конструируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{}
wordform_score "консультируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{}
wordform_score "консультируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{}
wordform_score "кидаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{}
wordform_score "кидаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{}
wordform_score "акцентируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{}
wordform_score "акцентируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{}
wordform_score "колонизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{}
wordform_score "колонизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{}
wordform_score "крымском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{}
wordform_score "крымском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{}
wordform_score "каспийском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{}
wordform_score "каспийском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{}
wordform_score "амурском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{}
wordform_score "амурском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{}
wordform_score "архангельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{}
wordform_score "архангельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{}
wordform_score "курильском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{}
wordform_score "курильском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{}
wordform_score "кировском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{}
wordform_score "кировском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{}
wordform_score "козельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{}
wordform_score "козельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{}
wordform_score "курском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{}
wordform_score "курском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{}
wordform_score "калининском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{}
wordform_score "калининском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{}
wordform_score "красноярском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{}
wordform_score "красноярском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{}
wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качкою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качкою" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{}
wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{}
wordform_score "адыгейском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{}
wordform_score "адыгейском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{}
wordform_score "комсомольском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{}
wordform_score "комсомольском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{}
wordform_score "апшеронском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{}
wordform_score "апшеронском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{}
wordform_score "тайна" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:тайный{}
wordform_score "тайна" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:тайна{}
wordform_score "коробило" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "коробило" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "коробит" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "коробит" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "казалось" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{}
wordform_score "казалось" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{}
wordform_score "канал" { ГЛАГОЛ } = -5 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "канала" { ГЛАГОЛ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "чай" { ГЛАГОЛ } = -10 // чаять
wordform_score "чай" { СУЩЕСТВИТЕЛЬНОЕ } = 0 // чай
wordform_score "чай" { частица } = -2 // чай
wordform_score "чай" { наречие } = -5
wordform_score "готов" { прилагательное } = 1
wordform_score "готов" { существительное } = -1
wordform_score "извести" { инфинитив } = -1
wordform_score "извести" { существительное } = 1
wordform_score "нашли" { наклонение:изъяв } = 1
wordform_score "нашли" { наклонение:побуд } = -5
// ----
wordform_score "брехни" { глагол } = -1 // брехня брехни --> брехнуть брехни
wordform_score "бузил" { существительное } = -1 // бузила бузил --> бузить бузил
wordform_score "бурей" { глагол } = -1 // буря бурей --> буреть бурей
wordform_score "бюллетень" { глагол } = -1 // бюллетень бюллетень --> бюллетенить бюллетень
wordform_score "возрасту" { глагол } = -1 // возраст возрасту --> возрасти возрасту
wordform_score "воплю" { глагол } = -1 // вопль воплю --> вопить воплю
wordform_score "врали" { существительное } = -1 // враль врали --> врать врали
wordform_score "гвозди" { глагол } = -1 // гвоздь гвозди --> гвоздить гвозди
wordform_score "Глашу" { глагол } = -1 // Глаша Глашу --> гласить глашу
wordform_score "голубей" { глагол } = -1 // голубь голубей --> голубеть голубей
wordform_score "гряду" { глагол } = -1 // гряда гряду --> грясти гряду
wordform_score "Дорою" { существительное } = -1 // Дора Дорою --> дорыть дорою
wordform_score "дох" { глагол } = -1 // доха дох --> дохнуть дох
wordform_score "драконят" { существительное } = -1 // драконенок драконят --> драконить драконят
wordform_score "дублю" { глагол } = -1 // дубль дублю --> дубить дублю
wordform_score "дули" { существительное } = -1 // дуля дули --> дуть дули
wordform_score "ежу" { глагол } = -1 // еж ежу --> ежить ежу
wordform_score "жал" { существительное } = -1 // жало жал --> жать жал
wordform_score "жигану" { глагол } = -1 // жиган жигану --> жигануть жигану
wordform_score "завали" { существительное } = -1 // заваль завали --> завалить завали
wordform_score "замшей" { глагол } = -1 // замша замшей --> замшеть замшей
wordform_score "зарей" { глагол } = -1 // заря зарей --> зареять зарей
wordform_score "затей" { глагол } = -1 // затея затей --> затеять затей
wordform_score "затею" { глагол } = -1 // затея затею --> затеять затею
wordform_score "затону" { существительное } = -1 // затон затону --> затонуть затону
wordform_score "знахарю" { глагол } = -1 // знахарь знахарю --> знахарить знахарю
wordform_score "изморозь" { глагол } = -1 // изморозь изморозь --> изморозить изморозь
wordform_score "канитель" { глагол } = -1 // канитель канитель --> канителить канитель
wordform_score "ковали" { существительное } = -1 // коваль ковали --> ковать ковали
wordform_score "кучу" { глагол } = -1 // куча кучу --> кутить кучу
wordform_score "лохмачу" { существительное } = -1 // лохмач лохмачу --> лохматить лохмачу
wordform_score "матерей" { глагол } = -5 // мать матерей --> матереть матерей
wordform_score "матери" { глагол } = -5 // мать матери --> материть матери
wordform_score "метель" { глагол } = -1 // метель метель --> метелить метель
wordform_score "мини" { глагол } = -1 // мини мини --> минуть мини
wordform_score "минут" { глагол } = -1 // минута минут --> минуть минут
wordform_score "молоди" { глагол } = -1 // молодь молоди --> молодить молоди
wordform_score "батрачат" { существительное } = -1 // батрачонок батрачат --> батрачить батрачат
wordform_score "бузила" { существительное } = -1 // бузила бузила --> бузить бузила
wordform_score "времени" { глагол } = -1 // время времени --> временить времени
wordform_score "дурней" { глагол } = -1 // дурень дурней --> дурнеть дурней
wordform_score "наймите" { существительное } = -1 // наймит наймите --> нанять наймите
wordform_score "накипи" { глагол } = -1 // накипь накипи --> накипеть накипи
wordform_score "нарвал" { существительное } = -1 // нарвал нарвал --> нарвать нарвал
wordform_score "нарвала" { существительное } = -1 // нарвал нарвала --> нарвать нарвала
wordform_score "нарой" { существительное } = -1 // нара нарой --> нарыть нарой
wordform_score "пари" { глагол } = -1 // пари пари --> парить пари
wordform_score "пастушат" { глагол } = -1 // пастушонок пастушат --> пастушить пастушат
wordform_score "пасу" { существительное } = -1 // пас пасу --> пасти пасу
wordform_score "пень" { глагол } = -1 // пень пень --> пенить пень
wordform_score "пеню" { глагол } = -1 // пеня пеню --> пенить пеню
wordform_score "передам" { существительное } = -1 // перед передам --> передать передам
wordform_score "печаль" { глагол } = -1 // печаль печаль --> печалить печаль
wordform_score "подтеки" { глагол } = -1 // подтек подтеки --> подтечь подтеки
wordform_score "постригу" { существительное } = -1 // постриг постригу --> постричь постригу
wordform_score "проем" { глагол } = -1 // проем проем --> проесть проем
wordform_score "простой" { глагол } = -1 // простой простой --> простоять простой
wordform_score "пряди" { глагол } = -1 // прядь пряди --> прясть пряди
wordform_score "разъем" { глагол } = -1 // разъем разъем --> разъесть разъем
wordform_score "ржу" { существительное } = -1 // ржа ржу --> ржать ржу
wordform_score "ругани" { глагол } = -1 // ругань ругани --> ругануть ругани
wordform_score "сбои" { глагол } = -1 // сбой сбои --> сбоить сбои
wordform_score "секретарь" { глагол } = -1 // секретарь секретарь --> секретарить секретарь
wordform_score "скину" { существительное } = -1 // скин скину --> скинуть скину
wordform_score "слесарь" { глагол } = -1 // слесарь слесарь --> слесарить слесарь
wordform_score "случаем" { глагол } = -1 // случай случаем --> случать случаем
wordform_score "соловей" { глагол } = -1 // соловей соловей --> соловеть соловей
wordform_score "спирали" { глагол } = -1 // спираль спирали --> спирать спирали
wordform_score "старь" { глагол } = -1 // старь старь --> старить старь
wordform_score "струи" { глагол } = -1 // струя струи --> струить струи
wordform_score "такелажу" { глагол } = -1 // такелаж такелажу --> такелажить такелажу
wordform_score "участи" { глагол } = -1 // участь участи --> участить участи
wordform_score "хмелю" { глагол } = -10 // хмель хмелю --> хмелить хмелю
wordform_score "чаем" { глагол } = -10 // чай чаем --> чаять чаем
wordform_score "замшею" { глагол } = -1 // замша замшею --> замшеть замшею
wordform_score "зелени" { глагол } = -1 // зелень зелени --> зеленить зелени
wordform_score "знахарь" { глагол } = -1 // знахарь знахарь --> знахарить знахарь
wordform_score "канифоль" { глагол } = -1 // канифоль канифоль --> канифолить канифоль
wordform_score "лужу" { глагол } = -1 // лужа лужу --> лудить лужу
wordform_score "матерей" { глагол } = -1 // матерь матерей --> матереть матерей
wordform_score "матери" { глагол } = -1 // матерь матери --> материть матери
wordform_score "мелей" { глагол } = -1 // мель мелей --> мелеть мелей
wordform_score "мыло" { глагол } = -1 // мыло мыло --> мыть мыло
wordform_score "обезьянят" { существительное } = -1 // обезьяненок обезьянят --> обезьянить обезьянят
wordform_score "объем" { глагол } = -1 // объем объем --> объесть объем
wordform_score "осени" { глагол } = -1 // осень осени --> осенить осени
wordform_score "отмели" { глагол } = -1 // отмель отмели --> отмолоть отмели
wordform_score "перла" { существительное } = -1 // перл перла --> переть перла
wordform_score "пил" { существительное } = -1 // пила пил --> пить пил
wordform_score "пищали" { существительное } = -1 // пищаль пищали --> пищать пищали
wordform_score "поволок" { существительное } = -1 // поволока поволок --> поволочь поволок
wordform_score "поволоку" { существительное } = -1 // поволока поволоку --> поволочь поволоку
wordform_score "покой" { глагол } = -5 // покой покой --> покоить покой
wordform_score "покою" { глагол } = -5 // покой покою --> покоить покою
wordform_score "полет" { глагол } = -1 // полет полет --> полоть полет
wordform_score "полете" { глагол } = -1 // полет полете --> полоть полете
wordform_score "полю" { глагол } = -1 // поле полю --> полоть полю
wordform_score "примеси" { глагол } = -1 // примесь примеси --> примесить примеси
wordform_score "примету" { глагол } = -1 // примета примету --> примести примету
wordform_score "припас" { существительное } = -1 // припас припас --> припасти припас
wordform_score "продела" { существительное } = -1 // продел продела --> продеть продела
wordform_score "просек" { существительное } = -1 // просека просек --> просечь просек
wordform_score "пущу" { существительное } = -1 // пуща пущу --> пустить пущу
wordform_score "пьяни" { глагол } = -1 // пьянь пьяни --> пьянить пьяни
wordform_score "сбою" { глагол } = -1 // сбой сбою --> сбоить сбою
wordform_score "свечу" { глагол } = -1 // свеча свечу --> светить свечу
wordform_score "секретарю" { глагол } = -1 // секретарь секретарю --> секретарить секретарю
wordform_score "случай" { глагол } = -5 // случай случай --> случать случай
wordform_score "случаю" { глагол } = -5 // случай случаю --> случать случаю
wordform_score "слюни" { глагол } = -1 // слюна слюни --> слюнить слюни
wordform_score "смог" { существительное } = -1 // смог смог --> смочь смог
wordform_score "смогу" { существительное } = -1 // смог смогу --> смочь смогу
wordform_score "собачат" { существительное } = -1 // собаченок собачат --> собачить собачат
wordform_score "совести" { глагол } = -1 // совесть совести --> совестить совести
wordform_score "спас" { существительное } = -1 // спас спас --> спасти спас
wordform_score "стай" { глагол } = -1 // стая стай --> стаять стай
wordform_score "стаю" { глагол } = -1 // стая стаю --> стаять стаю
wordform_score "струю" { глагол } = -1 // струя струю --> струить струю
wordform_score "стужу" { глагол } = -1 // стужа стужу --> студить стужу
wordform_score "сучат" { существительное } = -1 // сучонок сучат --> сучить сучат
wordform_score "тлей" { глагол } = -1 // тля тлей --> тлеть тлей
wordform_score "толщу" { глагол } = -1 // толща толщу --> толстить толщу
wordform_score "царю" { глагол } = -4 // царь царю --> царить царю ==> Ну а поздно вечером довелось удивиться и царю.
wordform_score "чащу" { глагол } = -1 // чаща чащу --> частить чащу
wordform_score "чаю" { глагол } = -10 // чай чаю --> чаять чаю
wordform_score "ширь" { глагол } = -1 // ширь ширь --> ширить ширь
wordform_score "штурману" { глагол } = -1 // штурман штурману --> штурмануть штурману
wordform_score "щурят" { существительное } = -1 // щуренок щурят --> щурить щурят
wordform_score "гноя" { деепричастие } = -4 // гной гноя --> гноя гноя
wordform_score "гостя" { деепричастие } = -1 // гость гостя --> гостя гостя
wordform_score "душа" { деепричастие } = -1 // душ душа --> душа душа
wordform_score "катя" { деепричастие } = -4 // Катя Катя --> катя катя
wordform_score "колея" { деепричастие } = -1 // колея колея --> колея колея
wordform_score "костя" { деепричастие } = -1 // Костя Костя --> костя костя
wordform_score "нарыв" { деепричастие } = -1 // нарыв нарыв --> нарыв нарыв
wordform_score "отлив" { деепричастие } = -1 // отлив отлив --> отлив отлив
wordform_score "отпоров" { существительное } = -1 // отпор отпоров --> отпоров отпоров
wordform_score "отрыв" { деепричастие } = -1 // отрыв отрыв --> отрыв отрыв
wordform_score "подлив" { существительное } = -1 // подлива подлив --> подлив подлив
wordform_score "покоя" { деепричастие } = -1 // покой покоя --> покоя покоя
wordform_score "прилив" { деепричастие } = -1 // прилив прилив --> прилив прилив
wordform_score "пузыря" { деепричастие } = -1 // пузырь пузыря --> пузыря пузыря
wordform_score "руля" { деепричастие } = -1 // руль руля --> руля руля
wordform_score "селя" { деепричастие } = -1 // сель селя --> селя селя
wordform_score "случая" { деепричастие } = -1 // случай случая --> случая случая
wordform_score "сторожа" { деепричастие } = -1 // сторож сторожа --> сторожа сторожа
wordform_score "суша" { деепричастие } = -1 // суша суша --> суша суша
wordform_score "туша" { деепричастие } = -1 // туш туша --> туша туша
wordform_score "хмеля" { деепричастие } = -1 // хмель хмеля --> хмеля хмеля
wordform_score "валя" { деепричастие } = -1 // Валя Валя --> валя валя
wordform_score "варя" { деепричастие } = -1 // Варя Варя --> варя варя
wordform_score "гвоздя" { деепричастие } = -1 // гвоздь гвоздя --> гвоздя гвоздя
wordform_score "голубя" { деепричастие } = -1 // голубь голубя --> голубя голубя
wordform_score "горя" { деепричастие } = -1 // горе горя --> горя горя
wordform_score "клея" { деепричастие } = -1 // клей клея --> клея клея
wordform_score "неволя" { деепричастие } = -1 // неволя неволя --> неволя неволя
wordform_score "отколов" { существительное } = -1 // откол отколов --> отколов отколов
wordform_score "переборов" { существительное } = -1 // перебор переборов --> переборов переборов
wordform_score "подлив" { существительное } = -1 // подлив подлив --> подлив подлив
wordform_score "подрыв" { деепричастие } = -1 // подрыв подрыв --> подрыв подрыв
wordform_score "полив" { деепричастие } = -1 // полив полив --> полив полив
wordform_score "пошив" { деепричастие } = -1 // пошив пошив --> пошив пошив
wordform_score "чая" { деепричастие } = -10 // чай чая --> чая чая
wordform_score "струя" { деепричастие } = -1 // струя струя --> струя струя
wordform_score "белков" { прилагательное } = -1 // белок белков --> белковый белков
wordform_score "витой" { существительное } = -1 // Вита Витой --> витой витой
wordform_score "вожатом" { прилагательное } = -1 // вожатый вожатом --> вожатый вожатом
wordform_score "вожатым" { прилагательное } = -1 // вожатый вожатым --> вожатый вожатым
wordform_score "вожатых" { прилагательное } = -1 // вожатый вожатых --> вожатый вожатых
wordform_score "гола" { прилагательное } = -1 // гол гола --> голый гола
wordform_score "вороной" { прилагательное } = -1 // ворона вороной --> вороной вороной
wordform_score "голы" { прилагательное } = -1 // гол голы --> голый голы
wordform_score "гусиной" { существительное } = -1 // Гусина Гусиной --> гусиный гусиной
wordform_score "гусиным" { существительное } = -1 // Гусин Гусиным --> гусиный гусиным
wordform_score "гусиными" { существительное } = -1 // Гусин Гусиными --> гусиный гусиными
wordform_score "добро" { прилагательное } = -1 // добро добро --> добрый добро
wordform_score "долги" { прилагательное } = -1 // долг долги --> долгий долги
wordform_score "готов" { существительное } = -1 // гот готов --> готовый готов
wordform_score "звонки" { прилагательное } = -1 // звонок звонки --> звонкий звонки
wordform_score "звонок" { прилагательное } = -1 // звонок звонок --> звонкий звонок
wordform_score "лаком" { прилагательное } = -1 // лак лаком --> лакомый лаком
wordform_score "лев" { прилагательное } = -1 // лев лев --> левый лев
wordform_score "лишаем" { прилагательное } = -1 // лишай лишаем --> лишаемый лишаем
wordform_score "сладка" { существительное } = -10 // сладка сладка --> сладкий сладка
wordform_score "сладкой" { существительное } = -1 // сладка сладкой --> сладкий сладкой
wordform_score "сладкою" { существительное } = -1 // сладка сладкою --> сладкий сладкою
wordform_score "сладок" { существительное } = -1 // сладка сладок --> сладкий сладок
wordform_score "темен" { существительное } = -1 // темя темен --> темный темен
wordform_score "тонной" { прилагательное } = -1 // тонна тонной --> тонный тонной
wordform_score "ужат" { существительное } = -1 // ужонок ужат --> ужатый ужат
wordform_score "этой" { существительное } = -5 // эта этой --> этот этой
wordform_score "рада" { существительное } = -1 // Рада Рада --> рад рада
wordform_score "рады" { существительное } = -1 // Рада Рады --> рад рады
wordform_score "столиком" { прилагательное } = -1 // столик столиком --> столикий столиком
wordform_score "теми" { существительное } = -1 // темь теми --> тот теми
wordform_score "тонною" { прилагательное } = -1 // тонна тонною --> тонный тонною
wordform_score "ужата" { существительное } = -1 // ужонок ужата --> ужатый ужата
wordform_score "эта" { существительное } = -3 // эта эта --> этот эта
wordform_score "этою" { существительное } = -1 // эта этою --> этот этою
wordform_score "эту" { существительное } = -3 // эта эту --> этот эту
// ------------------------
// Для имен и некоторых существительных на -ИЕ варианты множественного числа
// обычно не употребляются, поэтому мы можем априори предположить пониженную достоверность.
// Этот макрос далее используется для перечисления таких слов.
#define DiscountPlural(w) wordform_score w { существительное число:мн } = -2
/*
-- список форм получен из SQL словаря запросом:
select distinct 'DiscountPlural('+F.name+')'
from sg_entry E, sg_link L, sg_entry E2, sg_entry_coord EC, sg_form F, sg_form_coord FC
where E.id_class=9 and
L.id_entry1=E.id and L.istate=50 and E2.id=L.id_entry2 and E2.name='ИМЯ' and
EC.id_entry=E.id and EC.icoord=14 and EC.istate=1 and
F.id_entry=E.id and
FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1
*/
DiscountPlural(Авдотий)
DiscountPlural(Авдотьи)
DiscountPlural(Авдотьям)
DiscountPlural(Авдотьями)
DiscountPlural(Авдотьях)
DiscountPlural(Агафий)
DiscountPlural(Агафьи)
DiscountPlural(Агафьям)
DiscountPlural(Агафьями)
DiscountPlural(Агафьях)
DiscountPlural(Агнии)
DiscountPlural(Агний)
DiscountPlural(Агниям)
DiscountPlural(Агниями)
DiscountPlural(Агниях)
DiscountPlural(Азалии)
DiscountPlural(Азалий)
DiscountPlural(Азалиям)
DiscountPlural(Азалиями)
DiscountPlural(Азалиях)
DiscountPlural(Аксиний)
DiscountPlural(Аксиньи)
DiscountPlural(Аксиньям)
DiscountPlural(Аксиньями)
DiscountPlural(Аксиньях)
DiscountPlural(Амалии)
DiscountPlural(Амалий)
DiscountPlural(Амалиям)
DiscountPlural(Амалиями)
DiscountPlural(Амалиях)
DiscountPlural(Анастасии)
DiscountPlural(Анастасий)
DiscountPlural(Анастасиям)
DiscountPlural(Анастасиями)
DiscountPlural(Анастасиях)
DiscountPlural(Анисий)
DiscountPlural(Анисьи)
DiscountPlural(Анисьям)
DiscountPlural(Анисьями)
DiscountPlural(Анисьях)
DiscountPlural(Аполлинарии)
DiscountPlural(Аполлинарий)
DiscountPlural(Аполлинариям)
DiscountPlural(Аполлинариями)
DiscountPlural(Аполлинариях)
DiscountPlural(Апраксии)
DiscountPlural(Апраксий)
DiscountPlural(Апраксиям)
DiscountPlural(Апраксиями)
DiscountPlural(Апраксиях)
DiscountPlural(Валерии)
DiscountPlural(Валерий)
DiscountPlural(Валериям)
DiscountPlural(Валериями)
DiscountPlural(Валериях)
DiscountPlural(Виктории)
DiscountPlural(Викторий)
DiscountPlural(Викториям)
DiscountPlural(Викториями)
DiscountPlural(Викториях)
DiscountPlural(Виргинии)
DiscountPlural(Виргиний)
DiscountPlural(Виргиниям)
DiscountPlural(Виргиниями)
DiscountPlural(Виргиниях)
DiscountPlural(Виталии)
DiscountPlural(Виталий)
DiscountPlural(Виталиям)
DiscountPlural(Виталиями)
DiscountPlural(Виталиях)
DiscountPlural(Гликерии)
DiscountPlural(Гликерий)
DiscountPlural(Гликериям)
DiscountPlural(Гликериями)
DiscountPlural(Гликериях)
DiscountPlural(Гортензии)
DiscountPlural(Гортензий)
DiscountPlural(Гортензиям)
DiscountPlural(Гортензиями)
DiscountPlural(Гортензиях)
DiscountPlural(Дарий)
DiscountPlural(Дарьи)
DiscountPlural(Дарьям)
DiscountPlural(Дарьями)
DiscountPlural(Дарьях)
DiscountPlural(Денисии)
DiscountPlural(Денисий)
DiscountPlural(Денисиям)
DiscountPlural(Денисиями)
DiscountPlural(Денисиях)
DiscountPlural(Евгении)
DiscountPlural(Евгений)
DiscountPlural(Евгениям)
DiscountPlural(Евгениями)
DiscountPlural(Евгениях)
DiscountPlural(Евдокии)
DiscountPlural(Евдокий)
DiscountPlural(Евдокиям)
DiscountPlural(Евдокиями)
DiscountPlural(Евдокиях)
DiscountPlural(Евдоксии)
DiscountPlural(Евдоксий)
DiscountPlural(Евдоксиям)
DiscountPlural(Евдоксиями)
DiscountPlural(Евдоксиях)
DiscountPlural(Евлалии)
DiscountPlural(Евлалий)
DiscountPlural(Евлалиям)
DiscountPlural(Евлалиями)
DiscountPlural(Евлалиях)
DiscountPlural(Евлампии)
DiscountPlural(Евлампий)
DiscountPlural(Евлампиям)
DiscountPlural(Евлампиями)
DiscountPlural(Евлампиях)
DiscountPlural(Евпраксии)
DiscountPlural(Евпраксий)
DiscountPlural(Евпраксиям)
DiscountPlural(Евпраксиями)
DiscountPlural(Евпраксиях)
DiscountPlural(Евстолии)
DiscountPlural(Евстолий)
DiscountPlural(Евстолиям)
DiscountPlural(Евстолиями)
DiscountPlural(Евстолиях)
DiscountPlural(Евфимии)
DiscountPlural(Евфимий)
DiscountPlural(Евфимиям)
DiscountPlural(Евфимиями)
DiscountPlural(Евфимиях)
DiscountPlural(Евфросинии)
DiscountPlural(Евфросиний)
DiscountPlural(Евфросиниям)
DiscountPlural(Евфросиниями)
DiscountPlural(Евфросиниях)
DiscountPlural(Епистимии)
DiscountPlural(Епистимий)
DiscountPlural(Епистимиям)
DiscountPlural(Епистимиями)
DiscountPlural(Епистимиях)
DiscountPlural(Ефимии)
DiscountPlural(Ефимий)
DiscountPlural(Ефимиям)
DiscountPlural(Ефимиями)
DiscountPlural(Ефимиях)
DiscountPlural(Ефросинии)
DiscountPlural(Ефросиний)
DiscountPlural(Ефросиниям)
DiscountPlural(Ефросиниями)
DiscountPlural(Ефросиниях)
DiscountPlural(Ефросиньи)
DiscountPlural(Ефросиньям)
DiscountPlural(Ефросиньями)
DiscountPlural(Ефросиньях)
DiscountPlural(Зиновии)
DiscountPlural(Зиновий)
DiscountPlural(Зиновиям)
DiscountPlural(Зиновиями)
DiscountPlural(Зиновиях)
DiscountPlural(Ии)
DiscountPlural(Ий)
DiscountPlural(Иям)
DiscountPlural(Иями)
DiscountPlural(Иях)
DiscountPlural(Калерии)
DiscountPlural(Калерий)
DiscountPlural(Калериям)
DiscountPlural(Калериями)
DiscountPlural(Калериях)
DiscountPlural(Клавдии)
DiscountPlural(Клавдий)
DiscountPlural(Клавдиям)
DiscountPlural(Клавдиями)
DiscountPlural(Клавдиях)
DiscountPlural(Конкордии)
DiscountPlural(Конкордий)
DiscountPlural(Конкордиям)
DiscountPlural(Конкордиями)
DiscountPlural(Конкордиях)
DiscountPlural(Констанции)
DiscountPlural(Констанций)
DiscountPlural(Констанциям)
DiscountPlural(Констанциями)
DiscountPlural(Констанциях)
DiscountPlural(Корнелии)
DiscountPlural(Корнелий)
DiscountPlural(Корнелиям)
DiscountPlural(Корнелиями)
DiscountPlural(Корнелиях)
DiscountPlural(Ксении)
DiscountPlural(Ксений)
DiscountPlural(Ксениям)
DiscountPlural(Ксениями)
DiscountPlural(Ксениях)
DiscountPlural(Леокадии)
DiscountPlural(Леокадий)
DiscountPlural(Леокадиям)
DiscountPlural(Леокадиями)
DiscountPlural(Леокадиях)
DiscountPlural(Лидии)
DiscountPlural(Лидий)
DiscountPlural(Лидиям)
DiscountPlural(Лидиями)
DiscountPlural(Лидиях)
DiscountPlural(Лии)
DiscountPlural(Лий)
DiscountPlural(Лилии)
DiscountPlural(Лилий)
DiscountPlural(Лилиям)
DiscountPlural(Лилиями)
DiscountPlural(Лилиях)
DiscountPlural(Лиям)
DiscountPlural(Лиями)
DiscountPlural(Лиях)
DiscountPlural(Лукерий)
DiscountPlural(Лукерьи)
DiscountPlural(Лукерьям)
DiscountPlural(Лукерьями)
DiscountPlural(Лукерьях)
DiscountPlural(Лукреции)
DiscountPlural(Лукреций)
DiscountPlural(Лукрециям)
DiscountPlural(Лукрециями)
DiscountPlural(Лукрециях)
DiscountPlural(Малании)
DiscountPlural(Маланий)
DiscountPlural(Маланиям)
DiscountPlural(Маланиями)
DiscountPlural(Маланиях)
DiscountPlural(Маланьи)
DiscountPlural(Маланьям)
DiscountPlural(Маланьями)
DiscountPlural(Маланьях)
DiscountPlural(Марии)
DiscountPlural(Марий)
DiscountPlural(Мариям)
DiscountPlural(Мариями)
DiscountPlural(Мариях)
DiscountPlural(Марьи)
DiscountPlural(Марьям)
DiscountPlural(Марьями)
DiscountPlural(Марьях)
DiscountPlural(матрон)
DiscountPlural(матронам)
DiscountPlural(матронами)
DiscountPlural(матронах)
DiscountPlural(матроны)
DiscountPlural(Мелании)
DiscountPlural(Меланий)
DiscountPlural(Меланиям)
DiscountPlural(Меланиями)
DiscountPlural(Меланиях)
DiscountPlural(Настасии)
DiscountPlural(Настасий)
DiscountPlural(Настасиям)
DiscountPlural(Настасиями)
DiscountPlural(Настасиях)
DiscountPlural(Настасьи)
DiscountPlural(Настасьям)
DiscountPlural(Настасьями)
DiscountPlural(Настасьях)
DiscountPlural(Наталии)
DiscountPlural(Наталий)
DiscountPlural(Наталиям)
DiscountPlural(Наталиями)
DiscountPlural(Наталиях)
DiscountPlural(Натальи)
DiscountPlural(Натальям)
DiscountPlural(Натальями)
DiscountPlural(Натальях)
DiscountPlural(Оливии)
DiscountPlural(Оливий)
DiscountPlural(Оливиям)
DiscountPlural(Оливиями)
DiscountPlural(Оливиях)
DiscountPlural(Олимпии)
DiscountPlural(Олимпий)
DiscountPlural(Олимпиям)
DiscountPlural(Олимпиями)
DiscountPlural(Олимпиях)
DiscountPlural(Поликсении)
DiscountPlural(Поликсений)
DiscountPlural(Поликсениям)
DiscountPlural(Поликсениями)
DiscountPlural(Поликсениях)
DiscountPlural(Прасковий)
DiscountPlural(Прасковьи)
DiscountPlural(Прасковьям)
DiscountPlural(Прасковьями)
DiscountPlural(Прасковьях)
DiscountPlural(Пульхерии)
DiscountPlural(Пульхерий)
DiscountPlural(Пульхериям)
DiscountPlural(Пульхериями)
DiscountPlural(Пульхериях)
DiscountPlural(Розалии)
DiscountPlural(Розалий)
DiscountPlural(Розалиям)
DiscountPlural(Розалиями)
DiscountPlural(Розалиях)
DiscountPlural(светкам)
DiscountPlural(светками)
DiscountPlural(светках)
DiscountPlural(светки)
DiscountPlural(светок)
DiscountPlural(Сильвии)
DiscountPlural(Сильвий)
DiscountPlural(Сильвиям)
DiscountPlural(Сильвиями)
DiscountPlural(Сильвиях)
DiscountPlural(Соломонии)
DiscountPlural(Соломоний)
DiscountPlural(Соломониям)
DiscountPlural(Соломониями)
DiscountPlural(Соломониях)
DiscountPlural(Софии)
DiscountPlural(Софий)
DiscountPlural(Софиям)
DiscountPlural(Софиями)
DiscountPlural(Софиях)
DiscountPlural(Стефании)
DiscountPlural(Стефаний)
DiscountPlural(Стефаниям)
DiscountPlural(Стефаниями)
DiscountPlural(Стефаниях)
DiscountPlural(Таисии)
DiscountPlural(Таисий)
DiscountPlural(Таисиям)
DiscountPlural(Таисиями)
DiscountPlural(Таисиях)
DiscountPlural(Таисьи)
DiscountPlural(Таисьям)
DiscountPlural(Таисьями)
DiscountPlural(Таисьях)
DiscountPlural(томкам)
DiscountPlural(томками)
DiscountPlural(томках)
DiscountPlural(томки)
DiscountPlural(томок)
DiscountPlural(Устинии)
DiscountPlural(Устиний)
DiscountPlural(Устиниям)
DiscountPlural(Устиниями)
DiscountPlural(Устиниях)
DiscountPlural(Устиньи)
DiscountPlural(Устиньям)
DiscountPlural(Устиньями)
DiscountPlural(Устиньях)
DiscountPlural(Февронии)
DiscountPlural(Февроний)
DiscountPlural(Феврониям)
DiscountPlural(Феврониями)
DiscountPlural(Феврониях)
DiscountPlural(Февроньи)
DiscountPlural(Февроньям)
DiscountPlural(Февроньями)
DiscountPlural(Февроньях)
DiscountPlural(Федосии)
DiscountPlural(Федосий)
DiscountPlural(Федосиям)
DiscountPlural(Федосиями)
DiscountPlural(Федосиях)
DiscountPlural(Федосьи)
DiscountPlural(Федосьям)
DiscountPlural(Федосьями)
DiscountPlural(Федосьях)
DiscountPlural(Федотии)
DiscountPlural(Федотий)
DiscountPlural(Федотиям)
DiscountPlural(Федотиями)
DiscountPlural(Федотиях)
DiscountPlural(Федотьи)
DiscountPlural(Федотьям)
DiscountPlural(Федотьями)
DiscountPlural(Федотьях)
DiscountPlural(Фелиции)
DiscountPlural(Фелиций)
DiscountPlural(Фелициям)
DiscountPlural(Фелициями)
DiscountPlural(Фелициях)
DiscountPlural(Феодосии)
DiscountPlural(Феодосий)
DiscountPlural(Феодосиям)
DiscountPlural(Феодосиями)
DiscountPlural(Феодосиях)
DiscountPlural(Феодотии)
DiscountPlural(Феодотий)
DiscountPlural(Феодотиям)
DiscountPlural(Феодотиями)
DiscountPlural(Феодотиях)
DiscountPlural(Феофании)
DiscountPlural(Феофаний)
DiscountPlural(Феофаниям)
DiscountPlural(Феофаниями)
DiscountPlural(Феофаниях)
DiscountPlural(Фетинии)
DiscountPlural(Фетиний)
DiscountPlural(Фетиниям)
DiscountPlural(Фетиниями)
DiscountPlural(Фетиниях)
DiscountPlural(Фетиньи)
DiscountPlural(Фетиньям)
DiscountPlural(Фетиньями)
DiscountPlural(Фетиньях)
DiscountPlural(Хавронии)
DiscountPlural(Хавроний)
DiscountPlural(Хаврониям)
DiscountPlural(Хаврониями)
DiscountPlural(Хаврониях)
DiscountPlural(Цецилии)
DiscountPlural(Цецилий)
DiscountPlural(Цецилиям)
DiscountPlural(Цецилиями)
DiscountPlural(Цецилиях)
DiscountPlural(Эмилии)
DiscountPlural(Эмилий)
DiscountPlural(Эмилиям)
DiscountPlural(Эмилиями)
DiscountPlural(Эмилиях)
DiscountPlural(Юлиании)
DiscountPlural(Юлианий)
DiscountPlural(Юлианиям)
DiscountPlural(Юлианиями)
DiscountPlural(Юлианиях)
DiscountPlural(Юлии)
DiscountPlural(Юлий)
DiscountPlural(Юлиям)
DiscountPlural(Юлиями)
DiscountPlural(Юлиях)
/*
подавляем формы множ. числа для существительных на -ОСТЬ и -ИЕ
список форм получен из SQL словаря запросом:
select distinct 'DiscountPlural('+F.name+')'
from sg_entry E, sg_form F, sg_form_coord FC, sg_form_coord FC2
where E.id_class=9 and
F.id_entry=E.id and
FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 and
FC2.id_entry=E.id and FC2.iform=F.iform and FC2.icoord=24 and FC2.istate in (0,6)
and (E.name like '%ИЕ' or E.name like '%ЬЕ' or E.name like '%ОСТЬ')
*/
DiscountPlural(абсолютизирования)
DiscountPlural(абсолютизированья)
DiscountPlural(абстрагирования)
DiscountPlural(абстрагированья)
DiscountPlural(авансирования)
DiscountPlural(авансированья)
DiscountPlural(авиапредприятия)
DiscountPlural(авиапутешествия)
DiscountPlural(авиасоединения)
//DiscountPlural(автоколебания)
//DiscountPlural(автопредприятия)
//DiscountPlural(агропредприятия)
DiscountPlural(активирования)
DiscountPlural(активности)
DiscountPlural(акционирования)
DiscountPlural(анкетирования)
DiscountPlural(аномальности)
DiscountPlural(архиглупости)
DiscountPlural(ассигнования)
//DiscountPlural(ателье)
//DiscountPlural(аудиосообщения)
DiscountPlural(ауканья)
DiscountPlural(аханья)
DiscountPlural(бальзамирования)
//DiscountPlural(банальности)
DiscountPlural(бандподполья)
//DiscountPlural(бандформирования)
DiscountPlural(барахтания)
DiscountPlural(бдения)
//DiscountPlural(бедствия)
DiscountPlural(бедствования)
DiscountPlural(бездарности)
DiscountPlural(беззакония)
//DiscountPlural(безобразия)
DiscountPlural(безумия)
DiscountPlural(безумствования)
DiscountPlural(беременности)
DiscountPlural(бесконечности)
DiscountPlural(бескрайности)
DiscountPlural(бестактности)
DiscountPlural(бесцеремонности)
DiscountPlural(бибиканья)
//DiscountPlural(биения)
DiscountPlural(биоизлучения)
DiscountPlural(биоизмерения)
DiscountPlural(благовещения)
DiscountPlural(благовещенья)
DiscountPlural(благоволения)
//DiscountPlural(благовония)
//DiscountPlural(благовонья)
DiscountPlural(благовремения)
DiscountPlural(благовременья)
DiscountPlural(благоглупости)
DiscountPlural(благоговения)
DiscountPlural(благоговенья)
DiscountPlural(благодарения)
DiscountPlural(благодарности)
DiscountPlural(благодеяния)
DiscountPlural(благодеянья)
DiscountPlural(благозвучия)
DiscountPlural(благозвучья)
DiscountPlural(благолепия)
DiscountPlural(благолепья)
DiscountPlural(благоприличия)
DiscountPlural(благоприличья)
DiscountPlural(благородия)
DiscountPlural(благородья)
DiscountPlural(благословения)
DiscountPlural(благословенья)
DiscountPlural(благосостояния)
DiscountPlural(благосостоянья)
DiscountPlural(благости)
DiscountPlural(благоухания)
DiscountPlural(благоуханья)
DiscountPlural(близости)
//DiscountPlural(блуждания)
//DiscountPlural(блужданья)
DiscountPlural(богопочитания)
DiscountPlural(богослужения)
DiscountPlural(бодания)
DiscountPlural(боестолкновения)
DiscountPlural(болтания)
DiscountPlural(бомбометания)
DiscountPlural(бормотания)
DiscountPlural(бормотанья)
DiscountPlural(боронования)
DiscountPlural(боронованья)
DiscountPlural(бравирования)
DiscountPlural(бравированья)
DiscountPlural(бракосочетания)
DiscountPlural(бракосочетанья)
DiscountPlural(братания)
DiscountPlural(братанья)
DiscountPlural(брожения)
DiscountPlural(броженья)
DiscountPlural(бросания)
DiscountPlural(брыкания)
DiscountPlural(брыканья)
DiscountPlural(брюзжания)
DiscountPlural(брюзжанья)
//DiscountPlural(буквосочетания)
DiscountPlural(бурления)
DiscountPlural(бурленья)
DiscountPlural(бурчания)
DiscountPlural(бурчанья)
DiscountPlural(бухтения)
DiscountPlural(бытописания)
DiscountPlural(бытописанья)
DiscountPlural(валентности)
DiscountPlural(валяния)
DiscountPlural(варенья)
DiscountPlural(ваяния)
DiscountPlural(вбивания)
DiscountPlural(вбирания)
DiscountPlural(вбрасывания)
DiscountPlural(вбухивания)
DiscountPlural(вваливания)
DiscountPlural(введения)
DiscountPlural(ввертывания)
DiscountPlural(ввертыванья)
DiscountPlural(ввинчивания)
DiscountPlural(ввинчиванья)
DiscountPlural(вгрызания)
DiscountPlural(вдавливания)
DiscountPlural(вдевания)
DiscountPlural(вдергивания)
DiscountPlural(вдохновения)
DiscountPlural(вдохновенья)
DiscountPlural(вдувания)
DiscountPlural(ведомости)
DiscountPlural(вежливости)
DiscountPlural(везения)
DiscountPlural(везенья)
DiscountPlural(веления)
DiscountPlural(венеротрясения)
DiscountPlural(венчания)
DiscountPlural(венчанья)
//DiscountPlural(верования)
DiscountPlural(вероисповедания)
//DiscountPlural(вероучения)
//DiscountPlural(вероученья)
DiscountPlural(вероятности)
//DiscountPlural(верховья)
//DiscountPlural(ветвления)
//DiscountPlural(ветвленья)
DiscountPlural(ветшания)
DiscountPlural(вечности)
DiscountPlural(вещания)
//DiscountPlural(веяния)
DiscountPlural(вживления)
DiscountPlural(взаимовлияния)
DiscountPlural(взаимодействия)
//DiscountPlural(взаимозависимости)
//DiscountPlural(взаимоотношения)
DiscountPlural(взаимоположения)
DiscountPlural(взаимопревращения)
DiscountPlural(взаимопроникновения)
DiscountPlural(взбивания)
DiscountPlural(взбрыкивания)
DiscountPlural(взбухания)
DiscountPlural(взвевания)
DiscountPlural(взвешивания)
DiscountPlural(взвизгивания)
DiscountPlural(взвывания)
DiscountPlural(взгорья)
DiscountPlural(взгромождения)
DiscountPlural(вздевания)
DiscountPlural(вздрагивания)
DiscountPlural(вздувания)
DiscountPlural(вздутия)
DiscountPlural(вздыбливания)
DiscountPlural(вздымания)
DiscountPlural(взлаивания)
DiscountPlural(взмахивания)
DiscountPlural(взмывания)
DiscountPlural(взыскания)
DiscountPlural(взятия)
//DiscountPlural(видения)
//DiscountPlural(виденья)
DiscountPlural(видеоизображения)
DiscountPlural(видеонаблюдения)
//DiscountPlural(видеопослания)
DiscountPlural(видеоприложения)
DiscountPlural(видимости)
DiscountPlural(видоизменения)
DiscountPlural(визжания)
DiscountPlural(визжанья)
DiscountPlural(виляния)
DiscountPlural(висения)
DiscountPlural(вихляния)
DiscountPlural(вклинивания)
DiscountPlural(включения)
DiscountPlural(вкрапления)
DiscountPlural(вкручивания)
DiscountPlural(вкусности)
DiscountPlural(владения)
DiscountPlural(влезания)
DiscountPlural(влечения)
//DiscountPlural(вливания)
//DiscountPlural(влияния)
//DiscountPlural(вложения)
DiscountPlural(влюбленности)
DiscountPlural(внедрения)
DiscountPlural(внезапности)
DiscountPlural(внесения)
DiscountPlural(внешности)
//DiscountPlural(внутренности)
DiscountPlural(внушения)
DiscountPlural(водопользования)
DiscountPlural(водопользованья)
DiscountPlural(водружения)
DiscountPlural(вожделения)
DiscountPlural(вожделенья)
DiscountPlural(возвращения)
DiscountPlural(возвышения)
DiscountPlural(возвышенности)
DiscountPlural(возгорания)
DiscountPlural(воздаяния)
//DiscountPlural(воздействия)
//DiscountPlural(воззвания)
//DiscountPlural(воззрения)
//DiscountPlural(возлияния)
DiscountPlural(возмездия)
DiscountPlural(возможности)
DiscountPlural(возмущения)
DiscountPlural(вознаграждения)
//DiscountPlural(возражения)
DiscountPlural(волеизъявления)
//DiscountPlural(волнения)
DiscountPlural(волненья)
DiscountPlural(волости)
DiscountPlural(вольности)
DiscountPlural(вооружения)
DiscountPlural(воплощения)
DiscountPlural(воплощенья)
//DiscountPlural(восклицания)
DiscountPlural(воскресения)
DiscountPlural(воскресенья)
DiscountPlural(воскрешения)
DiscountPlural(воспаления)
DiscountPlural(воспевания)
//DiscountPlural(воспоминания)
//DiscountPlural(воспоминанья)
DiscountPlural(восприятия)
DiscountPlural(воспроизведения)
DiscountPlural(восславления)
DiscountPlural(воссоединения)
//DiscountPlural(восстания)
DiscountPlural(восстановления)
DiscountPlural(восхваления)
DiscountPlural(восхищения)
DiscountPlural(восхождения)
DiscountPlural(восьмидесятилетия)
DiscountPlural(восьмистишия)
//DiscountPlural(впечатления)
//DiscountPlural(впечатленья)
DiscountPlural(впрыскивания)
DiscountPlural(времяисчисления)
DiscountPlural(вручения)
DiscountPlural(вселения)
DiscountPlural(вскрикивания)
DiscountPlural(вскрытия)
DiscountPlural(всплытия)
DiscountPlural(вспрыгивания)
DiscountPlural(вспухания)
DiscountPlural(вспучивания)
DiscountPlural(вспушивания)
DiscountPlural(вставления)
DiscountPlural(встревания)
DiscountPlural(встряхивания)
DiscountPlural(вступления)
DiscountPlural(всучивания)
DiscountPlural(всхлипывания)
DiscountPlural(всхрапывания)
DiscountPlural(всыпания)
DiscountPlural(вталкивания)
DiscountPlural(втирания)
DiscountPlural(вторжения)
DiscountPlural(втравливания)
DiscountPlural(вульгарности)
//DiscountPlural(вхождения)
DiscountPlural(выбывания)
DiscountPlural(выбытия)
DiscountPlural(выведывания)
DiscountPlural(выдвижения)
DiscountPlural(выделения)
DiscountPlural(выделывания)
DiscountPlural(выдумывания)
DiscountPlural(выздоравливания)
DiscountPlural(выискивания)
DiscountPlural(выказывания)
DiscountPlural(выключения)
DiscountPlural(выковывания)
DiscountPlural(выкорчевывания)
DiscountPlural(выкручивания)
DiscountPlural(вылечивания)
DiscountPlural(выпадения)
DiscountPlural(выпекания)
DiscountPlural(выполнения)
DiscountPlural(выпрастывания)
//DiscountPlural(выпуклости)
DiscountPlural(выравнивания)
//DiscountPlural(выражения)
//DiscountPlural(выраженья)
DiscountPlural(высвистывания)
DiscountPlural(выселения)
DiscountPlural(высечения)
//DiscountPlural(высказывания)
DiscountPlural(высокоблагородия)
DiscountPlural(высокогорья)
DiscountPlural(выстуживания)
DiscountPlural(выступления)
//DiscountPlural(высыпания)
DiscountPlural(вычеркивания)
//DiscountPlural(вычисления)
DiscountPlural(вычитания)
DiscountPlural(вычитывания)
DiscountPlural(вышагивания)
DiscountPlural(вышивания)
DiscountPlural(вышучивания)
DiscountPlural(выявления)
DiscountPlural(выяснения)
DiscountPlural(вяканья)
DiscountPlural(гадания)
//DiscountPlural(гадости)
DiscountPlural(гашения)
//DiscountPlural(гидросооружения)
//DiscountPlural(гиперплоскости)
DiscountPlural(гипноизлучения)
DiscountPlural(главнокомандования)
DiscountPlural(глиссирования)
DiscountPlural(глиссированья)
DiscountPlural(глумления)
DiscountPlural(глумленья)
//DiscountPlural(глупости)
DiscountPlural(гнездования)
DiscountPlural(гнездованья)
//DiscountPlural(гнездовья)
DiscountPlural(гноения)
//DiscountPlural(гнусности)
DiscountPlural(говенья)
DiscountPlural(головокружения)
DiscountPlural(головокруженья)
DiscountPlural(голосования)
//DiscountPlural(гонения)
//DiscountPlural(госпредприятия)
DiscountPlural(госсобственности)
//DiscountPlural(гостей)
//DiscountPlural(гости)
//DiscountPlural(госучреждения)
DiscountPlural(грехопадения)
DiscountPlural(грубости)
DiscountPlural(группирования)
//DiscountPlural(гуляния)
//DiscountPlural(гулянья)
DiscountPlural(давления)
DiscountPlural(давности)
DiscountPlural(дактилоскопирования)
DiscountPlural(данности)
DiscountPlural(дарения)
DiscountPlural(дарования)
DiscountPlural(датирования)
DiscountPlural(двенадцатилетия)
//DiscountPlural(движения)
//DiscountPlural(движенья)
DiscountPlural(двоеточия)
//DiscountPlural(двусмысленности)
//DiscountPlural(двустишия)
DiscountPlural(двухсотлетия)
DiscountPlural(девяностолетия)
DiscountPlural(деепричастия)
//DiscountPlural(действия)
DiscountPlural(деления)
DiscountPlural(деликатности)
DiscountPlural(демонстрирования)
DiscountPlural(дергания)
DiscountPlural(дерганья)
DiscountPlural(держания)
DiscountPlural(дерзания)
DiscountPlural(дерзновения)
DiscountPlural(дерзости)
DiscountPlural(десятиборья)
DiscountPlural(десятилетия)
//DiscountPlural(деяния)
//DiscountPlural(деянья)
DiscountPlural(деятельности) // являются высшим критерием и конечной целью профессиональной деятельности госслужащего
DiscountPlural(диагностирования)
DiscountPlural(дикости)
//DiscountPlural(дипотношения)
DiscountPlural(добавления)
DiscountPlural(добродетельности)
//DiscountPlural(доверенности)
DiscountPlural(доворачивания)
DiscountPlural(договоренности)
DiscountPlural(дозволения)
DiscountPlural(долечивания)
//DiscountPlural(должности)
//DiscountPlural(домовладения)
DiscountPlural(домоправления)
//DiscountPlural(домостроения)
DiscountPlural(домоуправления)
DiscountPlural(домысливания)
DiscountPlural(донесения)
DiscountPlural(доперечисления)
DiscountPlural(дописывания)
//DiscountPlural(дополнения)
DiscountPlural(допрашивания)
//DiscountPlural(допущения)
DiscountPlural(доставания)
DiscountPlural(доставления)
//DiscountPlural(достижения)
DiscountPlural(достоверности)
DiscountPlural(достопамятности)
DiscountPlural(достояния)
//DiscountPlural(досье)
DiscountPlural(дотрагивания)
DiscountPlural(доукомплектования)
//DiscountPlural(драгоценности)
//DiscountPlural(древности)
//DiscountPlural(дрыганья)
DiscountPlural(дудения)
//DiscountPlural(дуновения)
DiscountPlural(дуракаваляния)
DiscountPlural(дурновкусия)
DiscountPlural(дурости)
DiscountPlural(единообразия)
DiscountPlural(еканья)
//DiscountPlural(емкости)
DiscountPlural(ерзанья)
DiscountPlural(жалования)
DiscountPlural(жалованья)
//DiscountPlural(желания)
//DiscountPlural(желанья)
DiscountPlural(жертвоприношения)
DiscountPlural(жестокости)
DiscountPlural(живописания)
DiscountPlural(живописанья)
//DiscountPlural(жидкости)
DiscountPlural(жизнеописания)
DiscountPlural(жизнепонимания)
//DiscountPlural(жития)
DiscountPlural(жонглирования)
DiscountPlural(жонглированья)
//DiscountPlural(заблуждения)
//DiscountPlural(заблужденья)
//DiscountPlural(заболевания)
//DiscountPlural(заведения)
//DiscountPlural(заведенья)
//DiscountPlural(заверения)
DiscountPlural(завершения)
DiscountPlural(завещания)
DiscountPlural(завещанья)
DiscountPlural(зависания)
//DiscountPlural(зависимости)
//DiscountPlural(завихрения)
//DiscountPlural(завоевания)
//DiscountPlural(завывания)
//DiscountPlural(завыванья)
DiscountPlural(завышения)
DiscountPlural(заглавия)
DiscountPlural(заглубления)
DiscountPlural(заглушения)
DiscountPlural(заграждения)
DiscountPlural(загромождения)
DiscountPlural(загрубения)
DiscountPlural(загрязнения)
DiscountPlural(загрязненности)
DiscountPlural(загустевания)
//DiscountPlural(задания)
DiscountPlural(задержания)
DiscountPlural(задолженности)
DiscountPlural(задымления)
DiscountPlural(зажатия)
DiscountPlural(зажатости)
DiscountPlural(зазрения)
DiscountPlural(зазывания)
DiscountPlural(заигрывания)
DiscountPlural(заикания)
//DiscountPlural(заимствования)
DiscountPlural(закаливания)
//DiscountPlural(заклинания)
//DiscountPlural(заклинанья)
DiscountPlural(заключения)
//DiscountPlural(заклятия)
//DiscountPlural(заклятья)
//DiscountPlural(закономерности)
DiscountPlural(законопослушания)
DiscountPlural(закрашивания)
//DiscountPlural(закругления)
//DiscountPlural(закругленности)
DiscountPlural(закручивания)
DiscountPlural(закрытия)
DiscountPlural(заксобрания)
DiscountPlural(залегания)
DiscountPlural(заледенения)
DiscountPlural(залития)
//DiscountPlural(замечания)
DiscountPlural(замирения)
//DiscountPlural(замыкания)
DiscountPlural(замысловатости)
DiscountPlural(замятия)
DiscountPlural(занижения)
DiscountPlural(занимания)
//DiscountPlural(занятия)
//DiscountPlural(занятья)
DiscountPlural(западания)
DiscountPlural(западения)
DiscountPlural(запаздывания)
DiscountPlural(заполнения)
DiscountPlural(заполняемости)
DiscountPlural(запугивания)
DiscountPlural(запутанности)
//DiscountPlural(запястья)
DiscountPlural(заседания)
DiscountPlural(засорения)
DiscountPlural(застолья)
DiscountPlural(застревания)
DiscountPlural(затмения)
DiscountPlural(заточения)
//DiscountPlural(затруднения)
DiscountPlural(затушевывания)
DiscountPlural(заумности)
DiscountPlural(захватывания)
DiscountPlural(захмеления)
DiscountPlural(захолустья)
DiscountPlural(зацикливания)
DiscountPlural(зачатия)
DiscountPlural(зачерствения)
DiscountPlural(зачисления)
//DiscountPlural(заявления)
//DiscountPlural(звания)
DiscountPlural(званья)
DiscountPlural(звукоподражания)
DiscountPlural(звукосочетания)
//DiscountPlural(здания)
DiscountPlural(здоровья)
DiscountPlural(зелья)
DiscountPlural(землевладения)
DiscountPlural(землетрясения)
//DiscountPlural(зимовья)
DiscountPlural(зияния)
//DiscountPlural(злодеяния)
//DiscountPlural(злоключения)
//DiscountPlural(злоупотребления)
//DiscountPlural(знаменитости)
//DiscountPlural(знамения)
//DiscountPlural(знаменья)
//DiscountPlural(знания)
//DiscountPlural(значения)
//DiscountPlural(значенья)
DiscountPlural(значимости)
DiscountPlural(избавленья)
DiscountPlural(избивания)
DiscountPlural(избиения)
DiscountPlural(избрания)
//DiscountPlural(изваяния)
//DiscountPlural(изваянья)
DiscountPlural(изведения)
//DiscountPlural(извержения)
//DiscountPlural(известия)
//DiscountPlural(извещения)
//DiscountPlural(извинения)
DiscountPlural(извлечения)
DiscountPlural(изволения)
//DiscountPlural(извращения)
DiscountPlural(изгнания)
DiscountPlural(изгнанья)
DiscountPlural(изголовья)
//DiscountPlural(издания)
//DiscountPlural(изделия)
DiscountPlural(излития)
DiscountPlural(излияния)
DiscountPlural(изложения)
DiscountPlural(излучения)
DiscountPlural(изменения)
DiscountPlural(измерения)
DiscountPlural(измышления)
//DiscountPlural(изнасилования)
DiscountPlural(изобличения)
//DiscountPlural(изображения)
//DiscountPlural(изобретения)
//DiscountPlural(изречения)
DiscountPlural(изъявления)
DiscountPlural(изъязвления)
//DiscountPlural(изъятия)
DiscountPlural(изысканности)
DiscountPlural(изящности)
DiscountPlural(иконопочитания)
DiscountPlural(именитости)
//DiscountPlural(имения)
//DiscountPlural(именья)
DiscountPlural(имитирования)
DiscountPlural(индивидуальности)
DiscountPlural(индуктивности)
DiscountPlural(инкассирования)
DiscountPlural(иносказания)
DiscountPlural(интимности)
DiscountPlural(инцидентности)
//DiscountPlural(искажения)
//DiscountPlural(искания)
//DiscountPlural(исключения)
DiscountPlural(искрения)
//DiscountPlural(искривления)
DiscountPlural(искушения)
//DiscountPlural(испарения)
DiscountPlural(исповедания)
DiscountPlural(испоганивания)
//DiscountPlural(исправления)
//DiscountPlural(испражнения)
//DiscountPlural(испытания)
DiscountPlural(иссечения)
//DiscountPlural(исследования)
DiscountPlural(Универсиады)
| мы нашли в его купе
| wordforms_score купа { существительное }=-5 | 7,303,393 | [
1,
145,
125,
146,
238,
225,
145,
126,
145,
113,
146,
235,
145,
124,
145,
121,
225,
145,
115,
225,
145,
118,
145,
116,
145,
127,
225,
145,
123,
146,
230,
145,
128,
145,
118,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1095,
9741,
67,
6355,
225,
145,
123,
146,
230,
145,
128,
145,
113,
288,
225,
146,
228,
146,
230,
146,
236,
145,
118,
146,
228,
146,
229,
145,
115,
145,
121,
146,
229,
145,
118,
145,
124,
146,
239,
145,
126,
145,
127,
145,
118,
289,
29711,
25,
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
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.