file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
// SPDX-License-Identifier: MIT-open-group pragma solidity >=0.5.15; import "lib/ds-test/test.sol"; import "src/QueueLibrary.sol"; contract QueueLibraryTest is DSTest { using QueueLibrary for QueueLibrary.Queue; QueueLibrary.Queue queue; // Here is where real tests start function testInitialization() public { assertEq(queue.size(), 0); } function testEnqueue1() public { queue.enqueue(address(1)); assertEq(queue.size(), 1); } function testEnqueue2() public { queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.size(), 2); } function testEnqueue3() public { queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.size(), 3); } function testDequeue1() public { queue.enqueue(address(1)); assertEq(queue.dequeue(), address(1)); assertEq(queue.size(), 0); } function testDequeue2() public { queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.size(), 0); } function testDequeue3() public { queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.dequeue(), address(3)); assertEq(queue.size(), 0); } function testRequeue1() public { queue.enqueue(address(1)); assertEq(queue.dequeue(), address(1)); assertEq(queue.size(), 0); queue.enqueue(address(1)); assertEq(queue.size(), 1); } function testRequeue2() public { queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.size(), 0); queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.size(), 2); } function testRequeue3() public { queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.dequeue(), address(3)); queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.size(), 3); } function testFailEnqueueDuplicate() public { address fakeId = address(13); queue.enqueue(fakeId); assertEq(queue.size(), 1); queue.enqueue(fakeId); } function testEnqueueGood() public { queue.enqueue(address(1)); assertEq(queue.size(), 1); queue.enqueue(address(2)); queue.enqueue(address(3)); queue.enqueue(address(4)); assertEq(queue.size(), 4); queue.enqueue(address(5)); assertEq(queue.size(), 5); } function testFailDequeueEmpty() public { assertEq(queue.size(), 0); queue.dequeue(); } function testDequeueGood() public { address a = address(1); address b = address(2); address c = address(3); queue.enqueue(a); queue.enqueue(b); queue.enqueue(c); assertEq(queue.dequeue(), a); assertEq(queue.dequeue(), b); } function testQueueDequeue() public { address a = address(1); assertEq(queue.size(), 0); queue.enqueue(a); assertEq(queue.size(), 1); queue.dequeue(); assertEq(queue.size(), 0); queue.enqueue(a); assertEq(queue.size(), 1); } }
Here is where real tests start
contract QueueLibraryTest is DSTest { using QueueLibrary for QueueLibrary.Queue; QueueLibrary.Queue queue; pragma solidity >=0.5.15; function testInitialization() public { assertEq(queue.size(), 0); } function testEnqueue1() public { queue.enqueue(address(1)); assertEq(queue.size(), 1); } function testEnqueue2() public { queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.size(), 2); } function testEnqueue3() public { queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.size(), 3); } function testDequeue1() public { queue.enqueue(address(1)); assertEq(queue.dequeue(), address(1)); assertEq(queue.size(), 0); } function testDequeue2() public { queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.size(), 0); } function testDequeue3() public { queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.dequeue(), address(3)); assertEq(queue.size(), 0); } function testRequeue1() public { queue.enqueue(address(1)); assertEq(queue.dequeue(), address(1)); assertEq(queue.size(), 0); queue.enqueue(address(1)); assertEq(queue.size(), 1); } function testRequeue2() public { queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.size(), 0); queue.enqueue(address(1)); queue.enqueue(address(2)); assertEq(queue.size(), 2); } function testRequeue3() public { queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.dequeue(), address(1)); assertEq(queue.dequeue(), address(2)); assertEq(queue.dequeue(), address(3)); queue.enqueue(address(1)); queue.enqueue(address(2)); queue.enqueue(address(3)); assertEq(queue.size(), 3); } function testFailEnqueueDuplicate() public { address fakeId = address(13); queue.enqueue(fakeId); assertEq(queue.size(), 1); queue.enqueue(fakeId); } function testEnqueueGood() public { queue.enqueue(address(1)); assertEq(queue.size(), 1); queue.enqueue(address(2)); queue.enqueue(address(3)); queue.enqueue(address(4)); assertEq(queue.size(), 4); queue.enqueue(address(5)); assertEq(queue.size(), 5); } function testFailDequeueEmpty() public { assertEq(queue.size(), 0); queue.dequeue(); } function testDequeueGood() public { address a = address(1); address b = address(2); address c = address(3); queue.enqueue(a); queue.enqueue(b); queue.enqueue(c); assertEq(queue.dequeue(), a); assertEq(queue.dequeue(), b); } function testQueueDequeue() public { address a = address(1); assertEq(queue.size(), 0); queue.enqueue(a); assertEq(queue.size(), 1); queue.dequeue(); assertEq(queue.size(), 0); queue.enqueue(a); assertEq(queue.size(), 1); } }
14,093,674
[ 1, 4625, 348, 7953, 560, 30, 225, 13743, 353, 1625, 2863, 7434, 787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7530, 9313, 4709, 353, 463, 882, 395, 288, 203, 203, 565, 1450, 7530, 9313, 364, 7530, 9313, 18, 3183, 31, 203, 203, 565, 7530, 9313, 18, 3183, 2389, 31, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 3600, 31, 203, 565, 445, 1842, 17701, 1435, 1071, 288, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 374, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 25327, 21, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 404, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 25327, 22, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 576, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 25327, 23, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 23, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 890, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 758, 4000, 21, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 21, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 374, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 758, 4000, 22, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 22, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 374, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 758, 4000, 23, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 23, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 22, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 23, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 374, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 426, 4000, 21, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 374, 1769, 203, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 404, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 426, 4000, 22, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 22, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 374, 1769, 203, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 576, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 426, 4000, 23, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 23, 10019, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 22, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 1758, 12, 23, 10019, 203, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 23, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 890, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 3754, 25327, 11826, 1435, 1071, 288, 203, 203, 3639, 1758, 10517, 548, 273, 1758, 12, 3437, 1769, 203, 203, 3639, 2389, 18, 21798, 12, 28395, 548, 1769, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 404, 1769, 203, 203, 3639, 2389, 18, 21798, 12, 28395, 548, 1769, 203, 203, 565, 289, 203, 203, 565, 445, 1842, 25327, 18195, 1435, 1071, 288, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 21, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 404, 1769, 203, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 22, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 23, 10019, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 24, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 1059, 1769, 203, 203, 3639, 2389, 18, 21798, 12, 2867, 12, 25, 10019, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 1381, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 3754, 758, 4000, 1921, 1435, 1071, 288, 203, 3639, 1815, 19508, 12, 4000, 18, 1467, 9334, 374, 1769, 203, 203, 3639, 2389, 18, 323, 4000, 5621, 203, 565, 289, 203, 203, 565, 445, 1842, 758, 4000, 18195, 1435, 1071, 288, 203, 3639, 1758, 279, 273, 1758, 12, 21, 1769, 203, 3639, 1758, 324, 273, 1758, 12, 22, 1769, 203, 3639, 1758, 276, 273, 1758, 12, 23, 1769, 203, 203, 3639, 2389, 18, 21798, 12, 69, 1769, 203, 3639, 2389, 18, 21798, 12, 70, 1769, 203, 3639, 2389, 18, 21798, 12, 71, 1769, 203, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 279, 1769, 203, 3639, 1815, 19508, 12, 4000, 18, 323, 4000, 9334, 324, 1769, 203, 565, 289, 203, 203, 565, 445, 1842, 3183, 758, 4000, 1435, 1071, 288, 203, 2 ]
./partial_match/42/0x61803c77605d7b383f7C2750973063668c251DF7/sources/HodlerPool.sol
TODO: ADD EXTERNAL FUNCTION SO THAT IF THE TOP 40 STAKERS HAS LESS THAN 40, WHOEVER IS INTERESTED CAN CALL IT TO PUSH THE TOP FOLLOWER (1) TO THE TOP LIST...emit Log("call function: unstake");printArray(); TODO: comment it out!emit Log(strConcat("sinceBlockNumber: ", uint2str(sinceBlockNumber),"","","")); delete _allStakers[account]; delete account from mapping emit Log("account deleted");emit Log(strConcat("first40BlockNumbers.length: ", uint2str(first40BlockNumbers.length),"","",""));emit Log(strConcat("first40BlockNumbers[first40BlockNumbers.length -1]: ", uint2str(first40BlockNumbers[first40BlockNumbers.length -1]),"","",""));emit Log("sinceBlockNumber < first40BlockNumbers[first40BlockNumbers.length]"); if sinceBlockNumber is within the top 40 it means that: * we need to remove it from the top 40 array * it will get some rewards depeding in the level :)uint index = getElementPositionInArray(first40BlockNumbers, sinceBlockNumber);emit Log(strConcat("index: ", uint2str(index),"","","")); add staker from _allStakers (followers) to both first40BlockNumbers and first40Addressesemit Log(strConcat("followers.count(): ", uint2str(followers.count()),"","","")); try max 10 times...ifemit Log("foundOne == true");emit Log("foundOne == false");emit Log("sinceBlockNumber NOT < first40BlockNumbers[first40BlockNumbers.length]");emit Log(strConcat("this account was removed from followers list", "","","",""));emit Log(strConcat("account ", addressToString(follower)," was removed from followers list","",""));
function unstake() private returns (uint) { address account = msg.sender; uint stakerLevel = 0; uint sinceBlockNumber = _allStakers[account].sinceBlockNumber; if (sinceBlockNumber <= first40BlockNumbers[first40BlockNumbers.length -1]) { uint index = getElementPositionInArray(first40Addresses, account); removeElementFromArray(index); if (index < 10) { } else if (index < 20) { } else if (index < 30) { stakerLevel = 2; } else { stakerLevel = 1; } if (followers.count() > 0) { address follower; bool foundOne = false; for (uint i = 0; i < 10; i++){ follower = followers.dequeue(); if (_allStakers[follower].exists) { foundOne = true; break; } } if (foundOne) { first40BlockNumbers.push(_allStakers[follower].sinceBlockNumber); first40Addresses.push(follower); } else { } } else { followers.dequeue(); } return stakerLevel; }
3,394,466
[ 1, 4625, 348, 7953, 560, 30, 225, 2660, 30, 11689, 5675, 11702, 13690, 7460, 7662, 789, 11083, 12786, 18680, 8063, 2347, 14607, 11367, 21641, 21216, 7662, 1258, 8063, 16, 678, 7995, 41, 2204, 4437, 11391, 11027, 2056, 22709, 22753, 24142, 8493, 28591, 12786, 18680, 6531, 654, 261, 21, 13, 8493, 12786, 18680, 15130, 2777, 18356, 1827, 2932, 1991, 445, 30, 640, 334, 911, 8863, 1188, 1076, 5621, 225, 2660, 30, 2879, 518, 596, 5, 18356, 1827, 12, 701, 15113, 2932, 9256, 1768, 1854, 30, 3104, 2254, 22, 701, 12, 9256, 1768, 1854, 3631, 6, 15937, 3113, 3660, 10019, 1430, 389, 454, 510, 581, 414, 63, 4631, 15533, 225, 1430, 2236, 628, 2874, 3626, 1827, 2932, 4631, 4282, 8863, 18356, 1827, 12, 701, 15113, 2932, 3645, 7132, 1768, 10072, 18, 2469, 30, 3104, 2254, 22, 701, 12, 3645, 7132, 1768, 10072, 18, 2469, 3631, 6, 15937, 3113, 3660, 10019, 18356, 1827, 12, 701, 15113, 2932, 3645, 7132, 1768, 10072, 63, 3645, 7132, 1768, 10072, 18, 2469, 300, 21, 14542, 3104, 2254, 22, 701, 12, 3645, 7132, 1768, 10072, 63, 3645, 7132, 1768, 10072, 18, 2469, 300, 21, 65, 3631, 6, 15937, 3113, 3660, 10019, 18356, 1827, 2932, 9256, 1768, 1854, 411, 1122, 7132, 1768, 10072, 63, 3645, 7132, 1768, 10072, 18, 2469, 4279, 1769, 309, 3241, 1768, 1854, 353, 3470, 326, 1760, 8063, 518, 4696, 716, 30, 225, 380, 732, 1608, 358, 1206, 518, 628, 326, 1760, 8063, 526, 225, 380, 518, 903, 336, 2690, 283, 6397, 443, 1845, 310, 316, 326, 1801, 294, 13, 11890, 770, 273, 7426, 2555, 382, 1076, 12, 3645, 7132, 1768, 10072, 16, 3241, 1768, 1854, 1769, 18356, 1827, 12, 701, 15113, 2932, 1615, 30, 3104, 2254, 22, 701, 12, 1615, 3631, 6, 15937, 3113, 3660, 10019, 527, 384, 6388, 628, 389, 454, 510, 581, 414, 261, 14641, 414, 13, 358, 3937, 1122, 7132, 1768, 10072, 471, 1122, 7132, 7148, 18356, 1827, 12, 701, 15113, 2932, 14641, 414, 18, 1883, 13332, 3104, 2254, 22, 701, 12, 14641, 414, 18, 1883, 1435, 3631, 6, 15937, 3113, 3660, 10019, 775, 943, 1728, 4124, 2777, 430, 18356, 1827, 2932, 7015, 3335, 422, 638, 8863, 18356, 1827, 2932, 7015, 3335, 422, 629, 8863, 18356, 1827, 2932, 9256, 1768, 1854, 4269, 411, 1122, 7132, 1768, 10072, 63, 3645, 7132, 1768, 10072, 18, 2469, 4279, 1769, 18356, 1827, 12, 701, 15113, 2932, 2211, 2236, 1703, 3723, 628, 2805, 414, 666, 3113, 1408, 10837, 15937, 3113, 3660, 10019, 18356, 1827, 12, 701, 15113, 2932, 4631, 3104, 1758, 5808, 12, 14641, 264, 3631, 6, 1703, 3723, 628, 2805, 414, 666, 15937, 3113, 3660, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 640, 334, 911, 1435, 3238, 1135, 261, 11890, 13, 288, 203, 3639, 1758, 2236, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 384, 6388, 2355, 273, 374, 31, 203, 3639, 2254, 3241, 1768, 1854, 273, 389, 454, 510, 581, 414, 63, 4631, 8009, 9256, 1768, 1854, 31, 203, 3639, 309, 261, 9256, 1768, 1854, 1648, 1122, 7132, 1768, 10072, 63, 3645, 7132, 1768, 10072, 18, 2469, 300, 21, 5717, 288, 203, 5411, 2254, 770, 273, 7426, 2555, 382, 1076, 12, 3645, 7132, 7148, 16, 2236, 1769, 203, 5411, 22015, 16638, 12, 1615, 1769, 203, 5411, 309, 261, 1615, 411, 1728, 13, 288, 203, 5411, 289, 203, 5411, 469, 309, 261, 1615, 411, 4200, 13, 288, 203, 5411, 289, 203, 5411, 469, 309, 261, 1615, 411, 5196, 13, 288, 203, 7734, 384, 6388, 2355, 273, 576, 31, 203, 5411, 289, 203, 5411, 469, 288, 203, 7734, 384, 6388, 2355, 273, 404, 31, 203, 5411, 289, 203, 203, 5411, 309, 261, 14641, 414, 18, 1883, 1435, 405, 374, 13, 288, 203, 7734, 1758, 2805, 264, 31, 203, 7734, 1426, 1392, 3335, 273, 629, 31, 203, 7734, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1728, 31, 277, 27245, 95, 203, 10792, 2805, 264, 273, 2805, 414, 18, 323, 4000, 5621, 203, 10792, 309, 261, 67, 454, 510, 581, 414, 63, 14641, 264, 8009, 1808, 13, 288, 203, 13491, 1392, 3335, 273, 638, 31, 203, 13491, 898, 31, 203, 10792, 289, 203, 7734, 289, 203, 7734, 309, 261, 7015, 3335, 13, 288, 203, 10792, 1122, 7132, 1768, 10072, 18, 6206, 24899, 454, 510, 581, 414, 63, 14641, 264, 8009, 9256, 1768, 1854, 1769, 203, 10792, 1122, 7132, 7148, 18, 6206, 12, 14641, 264, 1769, 203, 7734, 289, 203, 7734, 469, 288, 203, 7734, 289, 203, 5411, 289, 203, 3639, 469, 288, 203, 5411, 2805, 414, 18, 323, 4000, 5621, 203, 3639, 289, 203, 3639, 327, 384, 6388, 2355, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./amm/interfaces/ITempusAMM.sol"; import "./amm/interfaces/IVault.sol"; import "./ITempusPool.sol"; import "./math/Fixed256xVar.sol"; import "./utils/AMMBalancesHelper.sol"; import "./utils/UntrustedERC20.sol"; import "./utils/Ownable.sol"; import "./utils/Versioned.sol"; /// @dev TempusController singleton with a transferrable ownership and re-entrancy guards /// Owner is automatically set to the deployer of this contract contract TempusController is ReentrancyGuard, Ownable, Versioned { using Fixed256xVar for uint256; using SafeERC20 for IERC20; using UntrustedERC20 for IERC20; using AMMBalancesHelper for uint256[]; /// Registry for valid pools and AMM's to avoid fake address injection mapping(address => bool) private registry; /// @dev Event emitted on a successful BT/YBT deposit. /// @param pool The Tempus Pool to which assets were deposited /// @param depositor Address of the user who deposited Yield Bearing Tokens to mint /// Tempus Principal Share (TPS) and Tempus Yield Shares /// @param recipient Address of the recipient who will receive TPS and TYS tokens /// @param yieldTokenAmount Amount of yield tokens received from underlying pool /// @param backingTokenValue Value of @param yieldTokenAmount expressed in backing tokens /// @param shareAmounts Number of Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) granted to `recipient` /// @param interestRate Interest Rate of the underlying pool from Yield Bearing Tokens to the underlying asset /// @param fee The fee which was deducted (in terms of yield bearing tokens) event Deposited( address indexed pool, address indexed depositor, address indexed recipient, uint256 yieldTokenAmount, uint256 backingTokenValue, uint256 shareAmounts, uint256 interestRate, uint256 fee ); /// @dev Event emitted on a successful BT/YBT redemption. /// @param pool The Tempus Pool from which Tempus Shares were redeemed /// @param redeemer Address of the user whose Shares (Principals and Yields) are redeemed /// @param recipient Address of user that received Yield Bearing Tokens /// @param principalShareAmount Number of Tempus Principal Shares (TPS) to redeem into the Yield Bearing Token (YBT) /// @param yieldShareAmount Number of Tempus Yield Shares (TYS) to redeem into the Yield Bearing Token (YBT) /// @param yieldTokenAmount Number of Yield bearing tokens redeemed from the pool /// @param backingTokenValue Value of @param yieldTokenAmount expressed in backing tokens /// @param interestRate Interest Rate of the underlying pool from Yield Bearing Tokens to the underlying asset /// @param fee The fee which was deducted (in terms of yield bearing tokens) /// @param isEarlyRedeem True in case of early redemption, otherwise false event Redeemed( address indexed pool, address indexed redeemer, address indexed recipient, uint256 principalShareAmount, uint256 yieldShareAmount, uint256 yieldTokenAmount, uint256 backingTokenValue, uint256 interestRate, uint256 fee, bool isEarlyRedeem ); constructor() Versioned(1, 0, 0) {} /// @dev Registers a POOL or an AMM as valid or invalid to use with this Controller /// @param authorizedContract Contract which will be allowed to be used inside this Controller /// @param isValid If true, contract is valid to be used, if false, it's not allowed anymore function register(address authorizedContract, bool isValid) public onlyOwner { registry[authorizedContract] = isValid; } /// @dev Validates that the provided contract is registered to be used with this Controller /// @param authorizedContract Contract address to check function requireRegistered(address authorizedContract) private view { require(registry[authorizedContract], "Unauthorized contract address"); } /// @dev Atomically deposits YBT/BT to TempusPool and provides liquidity /// to the corresponding Tempus AMM with the issued TYS & TPS /// @param tempusAMM Tempus AMM to use to swap TYS for TPS /// @param tokenAmount Amount of YBT/BT to be deposited /// @param isBackingToken specifies whether the deposited asset is the Backing Token or Yield Bearing Token function depositAndProvideLiquidity( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken ) external payable nonReentrant { requireRegistered(address(tempusAMM)); _depositAndProvideLiquidity(tempusAMM, tokenAmount, isBackingToken); } /// @dev Adds liquidity to tempusAMM with ratio of shares that is equal to ratio in AMM /// @param tempusAMM Tempus AMM to provide liquidity to /// @param sharesAmount Amount of shares to be used to provide liquidity, one of the sahres will be partially used /// @notice If sharesAmount is 100 and amm balances ratio is 1 principal : 10 yields 90 principal will be "unused" /// So, liquidity will be provided with 10 principals and 100 yields /// @notice msg.sender needs to approve Controller for both Principals and Yields for @param sharesAmount function provideLiquidity(ITempusAMM tempusAMM, uint256 sharesAmount) external nonReentrant { requireRegistered(address(tempusAMM)); ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); _provideLiquidity(msg.sender, vault, poolId, ammTokens, ammBalances, sharesAmount, msg.sender); } /// @dev Atomically deposits YBT/BT to TempusPool and swaps TYS for TPS to get fixed yield /// See https://docs.balancer.fi/developers/guides/single-swaps#swap-overview /// @param tempusAMM Tempus AMM to use to swap TYS for TPS /// @param tokenAmount Amount of YBT/BT to be deposited in underlying YBT/BT decimal precision /// @param isBackingToken specifies whether the deposited asset is the Backing Token or Yield Bearing Token /// @param minTYSRate Minimum exchange rate of TYS (denominated in TPS) to receive in exchange for TPS /// @param deadline A timestamp by which the transaction must be completed, otherwise it would revert function depositAndFix( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken, uint256 minTYSRate, uint256 deadline ) external payable nonReentrant { requireRegistered(address(tempusAMM)); _depositAndFix(tempusAMM, tokenAmount, isBackingToken, minTYSRate, deadline); } /// @dev Deposits Yield Bearing Tokens to a Tempus Pool. /// @param targetPool The Tempus Pool to which tokens will be deposited /// @param yieldTokenAmount amount of Yield Bearing Tokens to be deposited /// in YBT Contract precision which can be 18 or 8 decimals /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) function depositYieldBearing( ITempusPool targetPool, uint256 yieldTokenAmount, address recipient ) external nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _depositYieldBearing(targetPool, yieldTokenAmount, recipient); } /// @dev Deposits Backing Tokens into the underlying protocol and /// then deposited the minted Yield Bearing Tokens to the Tempus Pool. /// @param targetPool The Tempus Pool to which tokens will be deposited /// @param backingTokenAmount amount of Backing Tokens to be deposited into the underlying protocol /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) function depositBacking( ITempusPool targetPool, uint256 backingTokenAmount, address recipient ) external payable nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _depositBacking(targetPool, backingTokenAmount, recipient); } /// @dev Redeem TPS+TYS held by msg.sender into Yield Bearing Tokens /// @notice `msg.sender` will receive yield bearing tokens /// @notice Before maturity, `principalAmount` must equal to `yieldAmount` /// @param targetPool The Tempus Pool from which to redeem Tempus Shares /// @param principalAmount Amount of Tempus Principals to redeem in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yields to redeem in YieldShare decimal precision /// @param recipient Address of user that will receive yield bearing tokens function redeemToYieldBearing( ITempusPool targetPool, uint256 principalAmount, uint256 yieldAmount, address recipient ) external nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _redeemToYieldBearing(targetPool, msg.sender, principalAmount, yieldAmount, recipient); } /// @dev Redeem TPS+TYS held by msg.sender into Backing Tokens /// @notice `recipient` will receive the backing tokens /// @notice Before maturity, `principalAmount` must equal to `yieldAmount` /// @param targetPool The Tempus Pool from which to redeem Tempus Shares /// @param principalAmount Amount of Tempus Principals to redeem in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yields to redeem in YieldShare decimal precision /// @param recipient Address of user that will receive yield bearing tokens function redeemToBacking( ITempusPool targetPool, uint256 principalAmount, uint256 yieldAmount, address recipient ) external nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _redeemToBacking(targetPool, msg.sender, principalAmount, yieldAmount, recipient); } /// @dev Withdraws liquidity from TempusAMM /// @notice `msg.sender` needs to approve controller for @param lpTokensAmount of LP tokens /// @notice Transfers LP tokens to controller and exiting tempusAmm with `msg.sender` as recipient /// @param tempusAMM Tempus AMM instance /// @param lpTokensAmount Amount of LP tokens to be withdrawn /// @param principalAmountOutMin Minimal amount of TPS to be withdrawn /// @param yieldAmountOutMin Minimal amount of TYS to be withdrawn /// @param toInternalBalances Withdrawing liquidity to internal balances function exitTempusAMM( ITempusAMM tempusAMM, uint256 lpTokensAmount, uint256 principalAmountOutMin, uint256 yieldAmountOutMin, bool toInternalBalances ) external nonReentrant { requireRegistered(address(tempusAMM)); _exitTempusAMM(tempusAMM, lpTokensAmount, principalAmountOutMin, yieldAmountOutMin, toInternalBalances); } /// @dev Withdraws liquidity from TempusAMM and redeems Shares to Yield Bearing or Backing Tokens /// Checks user's balance of principal shares and yield shares /// and exits AMM with exact amounts needed for redemption. /// @notice `msg.sender` needs to approve controller for whole balance of LP token /// @notice Transfers users' LP tokens to controller, then exits tempusAMM with `msg.sender` as recipient. /// After exit transfers remainder of LP tokens back to user /// @notice Can fail if there is not enough user balance /// @notice Only available before maturity since exiting AMM with exact amounts is disallowed after maturity /// @param tempusAMM TempusAMM instance to withdraw liquidity from /// @param principals Amount of Principals to redeem /// @param yields Amount of Yields to redeem /// @param principalsStaked Amount of staked principals (in TempusAMM) to redeem /// @param yieldsStaked Amount of staked yields (in TempusAMM) to redeem /// @param maxLpTokensToRedeem Maximum amount of LP tokens to spend for staked shares redemption /// @param toBackingToken If true redeems to backing token, otherwise redeems to yield bearing function exitAmmGivenAmountsOutAndEarlyRedeem( ITempusAMM tempusAMM, uint256 principals, uint256 yields, uint256 principalsStaked, uint256 yieldsStaked, uint256 maxLpTokensToRedeem, bool toBackingToken ) external nonReentrant { requireRegistered(address(tempusAMM)); _exitAmmGivenAmountsOutAndEarlyRedeem( tempusAMM, principals, yields, principalsStaked, yieldsStaked, maxLpTokensToRedeem, toBackingToken ); } /// @dev Withdraws ALL liquidity from TempusAMM and redeems Shares to Yield Bearing or Backing Tokens /// @notice `msg.sender` needs to approve controller for whole balance of LP token /// @notice Can fail if there is not enough user balance /// @param tempusAMM TempusAMM instance to withdraw liquidity from /// @param lpTokens Number of Lp tokens to redeem /// @param principals Number of Principals to redeem /// @param yields Number of Yields to redeem /// @param minPrincipalsStaked Minimum amount of staked principals to redeem for `lpTokens` /// @param minYieldsStaked Minimum amount of staked yields to redeem for `lpTokens` /// @param maxLeftoverShares Maximum amount of Principals or Yields to be left in case of early exit /// @param yieldsRate Base exchange rate of TYS (denominated in TPS) /// @param maxSlippage Maximum allowed change in the exchange rate from the base @param yieldsRate (1e18 precision) /// @param toBackingToken If true redeems to backing token, otherwise redeems to yield bearing /// @param deadline A timestamp by which, if a swap is necessary, the transaction must be completed, /// otherwise it would revert function exitAmmGivenLpAndRedeem( ITempusAMM tempusAMM, uint256 lpTokens, uint256 principals, uint256 yields, uint256 minPrincipalsStaked, uint256 minYieldsStaked, uint256 maxLeftoverShares, uint256 yieldsRate, uint256 maxSlippage, bool toBackingToken, uint256 deadline ) external nonReentrant { requireRegistered(address(tempusAMM)); if (lpTokens > 0) { // if there is LP balance, transfer to controller require(tempusAMM.transferFrom(msg.sender, address(this), lpTokens), "LP token transfer failed"); // exit amm and sent shares to controller uint256[] memory minAmountsOutFromLP = getAMMOrderedAmounts( tempusAMM, minPrincipalsStaked, minYieldsStaked ); _exitTempusAMMGivenLP(tempusAMM, address(this), address(this), lpTokens, minAmountsOutFromLP, false); } _redeemWithEqualShares( tempusAMM, principals, yields, maxLeftoverShares, yieldsRate, maxSlippage, deadline, toBackingToken ); } function swap( ITempusAMM tempusAMM, uint256 swapAmount, IERC20 tokenIn, IERC20 tokenOut, uint256 minReturn, uint256 deadline ) private { require(swapAmount > 0, "Invalid swap amount."); tokenIn.safeIncreaseAllowance(address(tempusAMM.getVault()), swapAmount); (IVault vault, bytes32 poolId, , ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.SingleSwap memory singleSwap = IVault.SingleSwap({ poolId: poolId, kind: IVault.SwapKind.GIVEN_IN, assetIn: tokenIn, assetOut: tokenOut, amount: swapAmount, userData: "" }); IVault.FundManagement memory fundManagement = IVault.FundManagement({ sender: address(this), fromInternalBalance: false, recipient: payable(address(this)), toInternalBalance: false }); vault.swap(singleSwap, fundManagement, minReturn, deadline); } function _depositAndProvideLiquidity( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken ) private { ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); uint256 mintedShares = _deposit(tempusAMM.tempusPool(), tokenAmount, isBackingToken); uint256[] memory sharesUsed = _provideLiquidity( address(this), vault, poolId, ammTokens, ammBalances, mintedShares, msg.sender ); // Send remaining Shares to user if (mintedShares > sharesUsed[0]) { ammTokens[0].safeTransfer(msg.sender, mintedShares - sharesUsed[0]); } if (mintedShares > sharesUsed[1]) { ammTokens[1].safeTransfer(msg.sender, mintedShares - sharesUsed[1]); } } function _provideLiquidity( address sender, IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances, uint256 sharesAmount, address recipient ) private returns (uint256[] memory) { uint256[] memory ammLiquidityProvisionAmounts = ammBalances.getLiquidityProvisionSharesAmounts(sharesAmount); if (sender != address(this)) { ammTokens[0].safeTransferFrom(sender, address(this), ammLiquidityProvisionAmounts[0]); ammTokens[1].safeTransferFrom(sender, address(this), ammLiquidityProvisionAmounts[1]); } ammTokens[0].safeIncreaseAllowance(address(vault), ammLiquidityProvisionAmounts[0]); ammTokens[1].safeIncreaseAllowance(address(vault), ammLiquidityProvisionAmounts[1]); IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: ammTokens, maxAmountsIn: ammLiquidityProvisionAmounts, userData: abi.encode(uint8(ITempusAMM.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT), ammLiquidityProvisionAmounts), fromInternalBalance: false }); // Provide TPS/TYS liquidity to TempusAMM vault.joinPool(poolId, address(this), recipient, request); return ammLiquidityProvisionAmounts; } function _depositAndFix( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken, uint256 minTYSRate, uint256 deadline ) private { ITempusPool targetPool = tempusAMM.tempusPool(); IERC20 principalShares = IERC20(address(targetPool.principalShare())); IERC20 yieldShares = IERC20(address(targetPool.yieldShare())); uint256 swapAmount = _deposit(targetPool, tokenAmount, isBackingToken); yieldShares.safeIncreaseAllowance(address(tempusAMM.getVault()), swapAmount); uint256 minReturn = swapAmount.mulfV(minTYSRate, targetPool.backingTokenONE()); swap(tempusAMM, swapAmount, yieldShares, principalShares, minReturn, deadline); // At this point all TYS must be swapped for TPS uint256 principalsBalance = principalShares.balanceOf(address(this)); assert(principalsBalance > 0); principalShares.safeTransfer(msg.sender, principalsBalance); } function _deposit( ITempusPool targetPool, uint256 tokenAmount, bool isBackingToken ) private returns (uint256 mintedShares) { mintedShares = isBackingToken ? _depositBacking(targetPool, tokenAmount, address(this)) : _depositYieldBearing(targetPool, tokenAmount, address(this)); } function _depositYieldBearing( ITempusPool targetPool, uint256 yieldTokenAmount, address recipient ) private returns (uint256) { require(yieldTokenAmount > 0, "yieldTokenAmount is 0"); IERC20 yieldBearingToken = IERC20(targetPool.yieldBearingToken()); // Transfer funds from msg.sender to targetPool uint transferredYBT = yieldBearingToken.untrustedTransferFrom( msg.sender, address(targetPool), yieldTokenAmount ); (uint mintedShares, uint depositedBT, uint fee, uint rate) = targetPool.onDepositYieldBearing( transferredYBT, recipient ); emit Deposited( address(targetPool), msg.sender, recipient, transferredYBT, depositedBT, mintedShares, rate, fee ); return mintedShares; } function _depositBacking( ITempusPool targetPool, uint256 backingTokenAmount, address recipient ) private returns (uint256) { require(backingTokenAmount > 0, "backingTokenAmount is 0"); IERC20 backingToken = IERC20(targetPool.backingToken()); // In case the underlying pool expects deposits in Ether (e.g. Lido), // it uses `backingToken = address(0)`. Since we disallow 0-value deposits, // and `msg.value == backingTokenAmount`, this check here can be used to // distinguish between the two pool types. if (msg.value == 0) { // NOTE: We need to have this check here to avoid calling transfer on address(0), // because that always succeeds. require(address(backingToken) != address(0), "Pool requires ETH deposits"); backingTokenAmount = backingToken.untrustedTransferFrom( msg.sender, address(targetPool), backingTokenAmount ); } else { require(address(backingToken) == address(0), "given TempusPool's Backing Token is not ETH"); require(msg.value == backingTokenAmount, "ETH value does not match provided amount"); } (uint256 mintedShares, uint256 depositedYBT, uint256 fee, uint256 interestRate) = targetPool.onDepositBacking{ value: msg.value }(backingTokenAmount, recipient); emit Deposited( address(targetPool), msg.sender, recipient, depositedYBT, backingTokenAmount, mintedShares, interestRate, fee ); return mintedShares; } function _redeemToYieldBearing( ITempusPool targetPool, address sender, uint256 principals, uint256 yields, address recipient ) private { require((principals > 0) || (yields > 0), "principalAmount and yieldAmount cannot both be 0"); (uint redeemedYBT, uint fee, uint interestRate) = targetPool.redeem(sender, principals, yields, recipient); uint redeemedBT = targetPool.numAssetsPerYieldToken(redeemedYBT, targetPool.currentInterestRate()); bool earlyRedeem = !targetPool.matured(); emit Redeemed( address(targetPool), sender, recipient, principals, yields, redeemedYBT, redeemedBT, fee, interestRate, earlyRedeem ); } function _redeemToBacking( ITempusPool targetPool, address sender, uint256 principals, uint256 yields, address recipient ) private { require((principals > 0) || (yields > 0), "principalAmount and yieldAmount cannot both be 0"); (uint redeemedYBT, uint redeemedBT, uint fee, uint rate) = targetPool.redeemToBacking( sender, principals, yields, recipient ); bool earlyRedeem = !targetPool.matured(); emit Redeemed( address(targetPool), sender, recipient, principals, yields, redeemedYBT, redeemedBT, fee, rate, earlyRedeem ); } function _exitTempusAMM( ITempusAMM tempusAMM, uint256 lpTokensAmount, uint256 principalAmountOutMin, uint256 yieldAmountOutMin, bool toInternalBalances ) private { require(tempusAMM.transferFrom(msg.sender, address(this), lpTokensAmount), "LP token transfer failed"); uint256[] memory amounts = getAMMOrderedAmounts(tempusAMM, principalAmountOutMin, yieldAmountOutMin); _exitTempusAMMGivenLP(tempusAMM, address(this), msg.sender, lpTokensAmount, amounts, toInternalBalances); } function _exitTempusAMMGivenLP( ITempusAMM tempusAMM, address sender, address recipient, uint256 lpTokensAmount, uint256[] memory minAmountsOut, bool toInternalBalances ) private { require(lpTokensAmount > 0, "LP token amount is 0"); (IVault vault, bytes32 poolId, IERC20[] memory ammTokens, ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.ExitPoolRequest memory request = IVault.ExitPoolRequest({ assets: ammTokens, minAmountsOut: minAmountsOut, userData: abi.encode(uint8(ITempusAMM.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT), lpTokensAmount), toInternalBalance: toInternalBalances }); vault.exitPool(poolId, sender, payable(recipient), request); } function _exitTempusAMMGivenAmountsOut( ITempusAMM tempusAMM, address sender, address recipient, uint256[] memory amountsOut, uint256 lpTokensAmountInMax, bool toInternalBalances ) private { (IVault vault, bytes32 poolId, IERC20[] memory ammTokens, ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.ExitPoolRequest memory request = IVault.ExitPoolRequest({ assets: ammTokens, minAmountsOut: amountsOut, userData: abi.encode( uint8(ITempusAMM.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT), amountsOut, lpTokensAmountInMax ), toInternalBalance: toInternalBalances }); vault.exitPool(poolId, sender, payable(recipient), request); } function _exitAmmGivenAmountsOutAndEarlyRedeem( ITempusAMM tempusAMM, uint256 principals, uint256 yields, uint256 principalsStaked, uint256 yieldsStaked, uint256 maxLpTokensToRedeem, bool toBackingToken ) private { ITempusPool tempusPool = tempusAMM.tempusPool(); require(!tempusPool.matured(), "Pool already finalized"); principals += principalsStaked; yields += yieldsStaked; require(principals == yields, "Needs equal amounts of shares before maturity"); // transfer LP tokens to controller require(tempusAMM.transferFrom(msg.sender, address(this), maxLpTokensToRedeem), "LP token transfer failed"); uint256[] memory amounts = getAMMOrderedAmounts(tempusAMM, principalsStaked, yieldsStaked); _exitTempusAMMGivenAmountsOut(tempusAMM, address(this), msg.sender, amounts, maxLpTokensToRedeem, false); // transfer remainder of LP tokens back to user uint256 lpTokenBalance = tempusAMM.balanceOf(address(this)); require(tempusAMM.transferFrom(address(this), msg.sender, lpTokenBalance), "LP token transfer failed"); if (toBackingToken) { _redeemToBacking(tempusPool, msg.sender, principals, yields, msg.sender); } else { _redeemToYieldBearing(tempusPool, msg.sender, principals, yields, msg.sender); } } function _redeemWithEqualShares( ITempusAMM tempusAMM, uint256 principals, uint256 yields, uint256 maxLeftoverShares, uint256 yieldsRate, uint256 maxSlippage, uint256 deadline, bool toBackingToken ) private { ITempusPool tempusPool = tempusAMM.tempusPool(); IERC20 principalShare = IERC20(address(tempusPool.principalShare())); IERC20 yieldShare = IERC20(address(tempusPool.yieldShare())); require(principalShare.transferFrom(msg.sender, address(this), principals), "Principals transfer failed"); require(yieldShare.transferFrom(msg.sender, address(this), yields), "Yields transfer failed"); require(yieldsRate > 0, "yieldsRate must be greater than 0"); require(maxSlippage <= 1e18, "maxSlippage can not be greater than 1e18"); principals = principalShare.balanceOf(address(this)); yields = yieldShare.balanceOf(address(this)); if (!tempusPool.matured()) { if (((yields > principals) ? (yields - principals) : (principals - yields)) >= maxLeftoverShares) { (uint256 swapAmount, bool yieldsIn) = tempusAMM.getSwapAmountToEndWithEqualShares( principals, yields, maxLeftoverShares ); uint256 minReturn = yieldsIn ? swapAmount.mulfV(yieldsRate, tempusPool.backingTokenONE()) : swapAmount.divfV(yieldsRate, tempusPool.backingTokenONE()); minReturn = minReturn.mulfV(1e18 - maxSlippage, 1e18); swap( tempusAMM, swapAmount, yieldsIn ? yieldShare : principalShare, yieldsIn ? principalShare : yieldShare, minReturn, deadline ); principals = principalShare.balanceOf(address(this)); yields = yieldShare.balanceOf(address(this)); } (yields, principals) = (principals <= yields) ? (principals, principals) : (yields, yields); } if (toBackingToken) { _redeemToBacking(tempusPool, address(this), principals, yields, msg.sender); } else { _redeemToYieldBearing(tempusPool, address(this), principals, yields, msg.sender); } } function _getAMMDetailsAndEnsureInitialized(ITempusAMM tempusAMM) private view returns ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) { vault = tempusAMM.getVault(); poolId = tempusAMM.getPoolId(); (ammTokens, ammBalances, ) = vault.getPoolTokens(poolId); require( ammTokens.length == 2 && ammBalances.length == 2 && ammBalances[0] > 0 && ammBalances[1] > 0, "AMM not initialized" ); } function getAMMOrderedAmounts( ITempusAMM tempusAMM, uint256 principalAmount, uint256 yieldAmount ) private view returns (uint256[] memory) { IVault vault = tempusAMM.getVault(); (IERC20[] memory ammTokens, , ) = vault.getPoolTokens(tempusAMM.getPoolId()); uint256[] memory amounts = new uint256[](2); (amounts[0], amounts[1]) = (address(tempusAMM.tempusPool().principalShare()) == address(ammTokens[0])) ? (principalAmount, yieldAmount) : (yieldAmount, principalAmount); return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' 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 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: BUSL-1.1 pragma solidity >=0.7.0; import "./IVault.sol"; import "./../../ITempusPool.sol"; interface ITempusAMM { enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } function getVault() external view returns (IVault); function getPoolId() external view returns (bytes32); function tempusPool() external view returns (ITempusPool); function balanceOf(address) external view returns (uint256); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /// Calculates the expected returned swap amount /// @param amount The given input amount of tokens /// @param yieldShareIn Specifies whether to calculate the swap from TYS to TPS (if true) or from TPS to TYS /// @return The expected returned amount of outToken function getExpectedReturnGivenIn(uint256 amount, bool yieldShareIn) external view returns (uint256); /// @dev Returns amount that user needs to swap to end up with almost the same amounts of Principals and Yields /// @param principals User's Principals balance /// @param yields User's Yields balance /// @param threshold Maximum difference between final balances of Principals and Yields /// @return amountIn Amount of Principals or Yields that user needs to swap to end with almost equal amounts /// @return yieldsIn Specifies the "direction" of the swap - /// whether Yields should be swapped for Principals (yieldsIn=true) or vice versa function getSwapAmountToEndWithEqualShares( uint256 principals, uint256 yields, uint256 threshold ) external view returns (uint256 amountIn, bool yieldsIn); /// @dev queries exiting TempusAMM with exact BPT tokens in /// @param bptAmountIn amount of LP tokens in /// @return principals Amount of principals that user would receive back /// @return yields Amount of yields that user would receive back function getExpectedTokensOutGivenBPTIn(uint256 bptAmountIn) external view returns (uint256 principals, uint256 yields); /// @dev queries exiting TempusAMM with exact tokens out /// @param principalsStaked amount of Principals to withdraw /// @param yieldsStaked amount of Yields to withdraw /// @return lpTokens Amount of Lp tokens that user would redeem function getExpectedBPTInGivenTokensOut(uint256 principalsStaked, uint256 yieldsStaked) external view returns (uint256 lpTokens); /// @dev queries joining TempusAMM with exact tokens in /// @param amountsIn amount of tokens to be added to the pool /// @return amount of LP tokens that could be received function getExpectedLPTokensForTokensIn(uint256[] memory amountsIn) external view returns (uint256); /// @dev This function returns the appreciation of one BPT relative to the /// underlying tokens. This starts at 1 when the pool is created and grows over time function getRate() external view returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVault { enum SwapKind { GIVEN_IN, GIVEN_OUT } struct SingleSwap { bytes32 poolId; SwapKind kind; IERC20 assetIn; IERC20 assetOut; uint256 amount; bytes userData; } struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } struct JoinPoolRequest { IERC20[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } struct ExitPoolRequest { IERC20[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.6 <0.9.0; pragma abicoder v2; import "./token/IPoolShare.sol"; import "./utils/IOwnable.sol"; import "./utils/IVersioned.sol"; /// Setting and transferring of fees are restricted to the owner. interface ITempusFees is IOwnable { /// The fees are in terms of yield bearing token (YBT). struct FeesConfig { uint256 depositPercent; uint256 earlyRedeemPercent; uint256 matureRedeemPercent; } /// Returns the current fee configuration. function getFeesConfig() external view returns (FeesConfig memory); /// Replace the current fee configuration with a new one. /// By default all the fees are expected to be set to zero. /// @notice This function can only be called by the owner. function setFeesConfig(FeesConfig calldata newFeesConfig) external; /// @return Maximum possible fee percentage that can be set for deposit function maxDepositFee() external view returns (uint256); /// @return Maximum possible fee percentage that can be set for early redeem function maxEarlyRedeemFee() external view returns (uint256); /// @return Maximum possible fee percentage that can be set for mature redeem function maxMatureRedeemFee() external view returns (uint256); /// Accumulated fees available for withdrawal. function totalFees() external view returns (uint256); /// Transfers accumulated Yield Bearing Token (YBT) fees /// from this pool contract to `recipient`. /// @param recipient Address which will receive the specified amount of YBT /// @notice This function can only be called by the owner. function transferFees(address recipient) external; } /// All state changing operations are restricted to the controller. interface ITempusPool is ITempusFees, IVersioned { /// @return The name of underlying protocol, for example "Aave" for Aave protocol function protocolName() external view returns (bytes32); /// This token will be used as a token that user can deposit to mint same amounts /// of principal and interest shares. /// @return The underlying yield bearing token. function yieldBearingToken() external view returns (address); /// This is the address of the actual backing asset token /// in the case of ETH, this address will be 0 /// @return Address of the Backing Token function backingToken() external view returns (address); /// @return uint256 value of one backing token, in case of 18 decimals 1e18 function backingTokenONE() external view returns (uint256); /// @return This TempusPool's Tempus Principal Share (TPS) function principalShare() external view returns (IPoolShare); /// @return This TempusPool's Tempus Yield Share (TYS) function yieldShare() external view returns (IPoolShare); /// @return The TempusController address that is authorized to perform restricted actions function controller() external view returns (address); /// @return Start time of the pool. function startTime() external view returns (uint256); /// @return Maturity time of the pool. function maturityTime() external view returns (uint256); /// @return Time of exceptional halting of the pool. /// In case the pool is still in operation, this must return type(uint256).max. function exceptionalHaltTime() external view returns (uint256); /// @return The maximum allowed time (in seconds) to pass with negative yield. function maximumNegativeYieldDuration() external view returns (uint256); /// @return True if maturity has been reached and the pool was finalized. /// This also includes the case when maturity was triggered due to /// exceptional conditions (negative yield periods). function matured() external view returns (bool); /// Finalizes the pool. This can only happen on or after `maturityTime`. /// Once finalized depositing is not possible anymore, and the behaviour /// redemption will change. /// /// Can be called by anyone and can be called multiple times. function finalize() external; /// Yield bearing tokens deposit hook. /// @notice Deposit will fail if maturity has been reached. /// @notice This function can only be called by TempusController /// @notice This function assumes funds were already transferred to the TempusPool from the TempusController /// @param yieldTokenAmount Amount of yield bearing tokens to deposit in YieldToken decimal precision /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) /// @return mintedShares Amount of TPS and TYS minted to `recipient` /// @return depositedBT The YBT value deposited, denominated as Backing Tokens /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the deposit function onDepositYieldBearing(uint256 yieldTokenAmount, address recipient) external returns ( uint256 mintedShares, uint256 depositedBT, uint256 fee, uint256 rate ); /// Backing tokens deposit hook. /// @notice Deposit will fail if maturity has been reached. /// @notice This function can only be called by TempusController /// @notice This function assumes funds were already transferred to the TempusPool from the TempusController /// @param backingTokenAmount amount of Backing Tokens to be deposited to underlying protocol in BackingToken decimal precision /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) /// @return mintedShares Amount of TPS and TYS minted to `recipient` /// @return depositedYBT The BT value deposited, denominated as Yield Bearing Tokens /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the deposit function onDepositBacking(uint256 backingTokenAmount, address recipient) external payable returns ( uint256 mintedShares, uint256 depositedYBT, uint256 fee, uint256 rate ); /// Redeems yield bearing tokens from this TempusPool /// msg.sender will receive the YBT /// NOTE #1 Before maturity, principalAmount must equal to yieldAmount. /// NOTE #2 This function can only be called by TempusController /// @param from Address to redeem its Tempus Shares /// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem for YBT in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem for YBT in YieldShare decimal precision /// @param recipient Address to which redeemed YBT will be sent /// @return redeemableYieldTokens Amount of Yield Bearing Tokens redeemed to `recipient` /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the redemption function redeem( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external returns ( uint256 redeemableYieldTokens, uint256 fee, uint256 rate ); /// Redeems TPS+TYS held by msg.sender into backing tokens /// `msg.sender` must approve TPS and TYS amounts to this TempusPool. /// `msg.sender` will receive the backing tokens /// NOTE #1 Before maturity, principalAmount must equal to yieldAmount. /// NOTE #2 This function can only be called by TempusController /// @param from Address to redeem its Tempus Shares /// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem in YieldShare decimal precision /// @param recipient Address to which redeemed BT will be sent /// @return redeemableYieldTokens Amount of Backing Tokens redeemed to `recipient`, denominated in YBT /// @return redeemableBackingTokens Amount of Backing Tokens redeemed to `recipient` /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the redemption function redeemToBacking( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external payable returns ( uint256 redeemableYieldTokens, uint256 redeemableBackingTokens, uint256 fee, uint256 rate ); /// Gets the estimated amount of Principals and Yields after a successful deposit /// @param amount Amount of BackingTokens or YieldBearingTokens that would be deposited /// @param isBackingToken If true, @param amount is in BackingTokens, otherwise YieldBearingTokens /// @return Amount of Principals (TPS) and Yields (TYS) in Principal/YieldShare decimal precision /// TPS and TYS are minted in 1:1 ratio, hence a single return value. function estimatedMintedShares(uint256 amount, bool isBackingToken) external view returns (uint256); /// Gets the estimated amount of YieldBearingTokens or BackingTokens received when calling `redeemXXX()` functions /// @param principals Amount of Principals (TPS) in PrincipalShare decimal precision /// @param yields Amount of Yields (TYS) in YieldShare decimal precision /// @param toBackingToken If true, redeem amount is estimated in BackingTokens instead of YieldBearingTokens /// @return Amount of YieldBearingTokens or BackingTokens in YBT/BT decimal precision function estimatedRedeem( uint256 principals, uint256 yields, bool toBackingToken ) external view returns (uint256); /// @dev This returns the stored Interest Rate of the YBT (Yield Bearing Token) pool /// it is safe to call this after updateInterestRate() was called /// @return Stored Interest Rate, decimal precision depends on specific TempusPool implementation function currentInterestRate() external view returns (uint256); /// @return Initial interest rate of the underlying pool, /// decimal precision depends on specific TempusPool implementation function initialInterestRate() external view returns (uint256); /// @return Interest rate at maturity of the underlying pool (or 0 if maturity not reached yet) /// decimal precision depends on specific TempusPool implementation function maturityInterestRate() external view returns (uint256); /// @return Rate of one Tempus Yield Share expressed in Asset Tokens function pricePerYieldShare() external returns (uint256); /// @return Rate of one Tempus Principal Share expressed in Asset Tokens function pricePerPrincipalShare() external returns (uint256); /// Calculated with stored interest rates /// @return Rate of one Tempus Yield Share expressed in Asset Tokens, function pricePerYieldShareStored() external view returns (uint256); /// Calculated with stored interest rates /// @return Rate of one Tempus Principal Share expressed in Asset Tokens function pricePerPrincipalShareStored() external view returns (uint256); /// @dev This returns actual Backing Token amount for amount of YBT (Yield Bearing Tokens) /// For example, in case of Aave and Lido the result is 1:1, /// and for compound is `yieldTokens * currentInterestRate` /// @param yieldTokens Amount of YBT in YBT decimal precision /// @param interestRate The current interest rate /// @return Amount of Backing Tokens for specified @param yieldTokens function numAssetsPerYieldToken(uint yieldTokens, uint interestRate) external view returns (uint); /// @dev This returns amount of YBT (Yield Bearing Tokens) that can be converted /// from @param backingTokens Backing Tokens /// @param backingTokens Amount of Backing Tokens in BT decimal precision /// @param interestRate The current interest rate /// @return Amount of YBT for specified @param backingTokens function numYieldTokensPerAsset(uint backingTokens, uint interestRate) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /// @dev Fixed Point decimal math utils for variable decimal point precision /// on 256-bit wide numbers library Fixed256xVar { /// @dev Multiplies two variable precision fixed point decimal numbers /// @param one 1.0 expressed in the base precision of `a` and `b` /// @return result = a * b function mulfV( uint256 a, uint256 b, uint256 one ) internal pure returns (uint256) { // result is always truncated return (a * b) / one; } /// @dev Divides two variable precision fixed point decimal numbers /// @param one 1.0 expressed in the base precision of `a` and `b` /// @return result = a / b function divfV( uint256 a, uint256 b, uint256 one ) internal pure returns (uint256) { // result is always truncated return (a * one) / b; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import "../math/Fixed256xVar.sol"; library AMMBalancesHelper { using Fixed256xVar for uint256; uint256 internal constant ONE = 1e18; function getLiquidityProvisionSharesAmounts(uint256[] memory ammBalances, uint256 shares) internal pure returns (uint256[] memory) { uint256[2] memory ammDepositPercentages = getAMMBalancesRatio(ammBalances); uint256[] memory ammLiquidityProvisionAmounts = new uint256[](2); (ammLiquidityProvisionAmounts[0], ammLiquidityProvisionAmounts[1]) = ( shares.mulfV(ammDepositPercentages[0], ONE), shares.mulfV(ammDepositPercentages[1], ONE) ); return ammLiquidityProvisionAmounts; } function getAMMBalancesRatio(uint256[] memory ammBalances) internal pure returns (uint256[2] memory balancesRatio) { uint256 rate = ammBalances[0].divfV(ammBalances[1], ONE); (balancesRatio[0], balancesRatio[1]) = rate > ONE ? (ONE, ONE.divfV(rate, ONE)) : (rate, ONE); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title UntrustedERC20 /// @dev Wrappers around ERC20 transfer operators that return the actual amount /// transferred. This means they are usable with tokens, which charge a fee or royalty on transfer. library UntrustedERC20 { using SafeERC20 for IERC20; /// Transfer tokens to a recipient. /// @param token The ERC20 token. /// @param to The recipient. /// @param value The requested amount. /// @return The actual amount of tokens transferred. function untrustedTransfer( IERC20 token, address to, uint256 value ) internal returns (uint256) { uint256 startBalance = token.balanceOf(to); token.safeTransfer(to, value); return token.balanceOf(to) - startBalance; } /// Transfer tokens to a recipient. /// @param token The ERC20 token. /// @param from The sender. /// @param to The recipient. /// @param value The requested amount. /// @return The actual amount of tokens transferred. function untrustedTransferFrom( IERC20 token, address from, address to, uint256 value ) internal returns (uint256) { uint256 startBalance = token.balanceOf(to); token.safeTransferFrom(from, to, value); return token.balanceOf(to) - startBalance; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./IOwnable.sol"; /// Implements Ownable with a two step transfer of ownership abstract contract Ownable is IOwnable { address private _owner; address private _proposedOwner; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Proposes a transfer of ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _proposedOwner = newOwner; emit OwnershipProposed(_owner, _proposedOwner); } /** * @dev Accepts ownership of the contract by a proposed account. * Can only be called by the proposed owner. */ function acceptOwnership() public virtual override { require(msg.sender == _proposedOwner, "Ownable: Only proposed owner can accept ownership"); _setOwner(_proposedOwner); _proposedOwner = address(0); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; import "./IVersioned.sol"; /// Implements versioning abstract contract Versioned is IVersioned { uint16 private immutable _major; uint16 private immutable _minor; uint16 private immutable _patch; constructor( uint16 major, uint16 minor, uint16 patch ) { _major = major; _minor = minor; _patch = patch; } function version() external view returns (Version memory) { return Version(_major, _minor, _patch); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.6 <0.9.0; import "../ITempusPool.sol"; /// Interface of Tokens representing the principal or yield shares of a pool. interface IPoolShare { enum ShareKind { Principal, Yield } /// @return The kind of the share. function kind() external view returns (ShareKind); /// @return The pool this share is part of. function pool() external view returns (ITempusPool); /// @dev Price per single share expressed in Backing Tokens of the underlying pool. /// This is for the purpose of TempusAMM api support. /// Example: exchanging Tempus Yield Share to DAI /// @return 1e18 decimal conversion rate per share function getPricePerFullShare() external returns (uint256); /// @return 1e18 decimal stored conversion rate per share function getPricePerFullShareStored() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; /// Implements Ownable with a two step transfer of ownership interface IOwnable { /** * @dev Change of ownership proposed. * @param currentOwner The current owner. * @param proposedOwner The proposed owner. */ event OwnershipProposed(address indexed currentOwner, address indexed proposedOwner); /** * @dev Ownership transferred. * @param previousOwner The previous owner. * @param newOwner The new owner. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current owner. */ function owner() external view returns (address); /** * @dev Proposes a transfer of ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external; /** * @dev Accepts ownership of the contract by a proposed account. * Can only be called by the proposed owner. */ function acceptOwnership() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; pragma abicoder v2; /// Implements versioning interface IVersioned { struct Version { uint16 major; uint16 minor; uint16 patch; } /// @return The version of the contract. function version() external view returns (Version memory); }
@dev Redeem TPS+TYS held by msg.sender into Backing Tokens @notice `recipient` will receive the backing tokens @notice Before maturity, `principalAmount` must equal to `yieldAmount` @param targetPool The Tempus Pool from which to redeem Tempus Shares @param principalAmount Amount of Tempus Principals to redeem in PrincipalShare decimal precision @param yieldAmount Amount of Tempus Yields to redeem in YieldShare decimal precision @param recipient Address of user that will receive yield bearing tokens
function redeemToBacking( ITempusPool targetPool, uint256 principalAmount, uint256 yieldAmount, address recipient ) external nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _redeemToBacking(targetPool, msg.sender, principalAmount, yieldAmount, recipient); }
1,804,480
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 868, 24903, 399, 5857, 15, 5538, 55, 15770, 635, 1234, 18, 15330, 1368, 4297, 310, 13899, 632, 20392, 1375, 20367, 68, 903, 6798, 326, 15394, 2430, 632, 20392, 11672, 29663, 16, 1375, 26138, 6275, 68, 1297, 3959, 358, 1375, 23604, 6275, 68, 632, 891, 1018, 2864, 1021, 3955, 9861, 8828, 628, 1492, 358, 283, 24903, 3955, 9861, 2638, 4807, 632, 891, 8897, 6275, 16811, 434, 3955, 9861, 2301, 14997, 358, 283, 24903, 316, 17010, 9535, 6970, 6039, 632, 891, 2824, 6275, 16811, 434, 3955, 9861, 31666, 87, 358, 283, 24903, 316, 31666, 9535, 6970, 6039, 632, 891, 8027, 5267, 434, 729, 716, 903, 6798, 2824, 30261, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 774, 2711, 310, 12, 203, 3639, 467, 7185, 407, 2864, 1018, 2864, 16, 203, 3639, 2254, 5034, 8897, 6275, 16, 203, 3639, 2254, 5034, 2824, 6275, 16, 203, 3639, 1758, 8027, 203, 565, 262, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 20367, 848, 486, 506, 374, 92, 20, 8863, 203, 3639, 2583, 10868, 12, 2867, 12, 3299, 2864, 10019, 203, 3639, 389, 266, 24903, 774, 2711, 310, 12, 3299, 2864, 16, 1234, 18, 15330, 16, 8897, 6275, 16, 2824, 6275, 16, 8027, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; //该合约参考自openzeppelin的开源代码 //1.使用SafeMath库防止运算溢出 //2.使用Ownable,Pausable合约来做权限控制 //3.ERC20Basic,ERC20都是接口,ERC20扩展了ERC20Basic,实现了授权转移 //4.BasicToken,StandardToken,PausableToken是具体实现 //5.BlackListToken加入黑名单方法 //6.合约所有者发行和赎回 // /** * * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ // function Ownable() public { // owner = msg.sender; // } constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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 Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract BlackListToken is PausableToken { function getBlackListStatus(address _maker) external constant returns (bool) { return isBlackListed[_maker]; } mapping (address => bool) public isBlackListed; function addBlackList (address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; emit AddedBlackList(_evilUser); } function removeBlackList (address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; emit RemovedBlackList(_clearedUser); } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; totalSupply_ = totalSupply_.sub(dirtyFunds); emit DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); } contract TCCToken is BlackListToken { string public constant name = "tenancy credit contract"; string public constant symbol = "TCC"; uint8 public constant decimals = 18; modifier validDestination( address to ) { require(to != address(0x0)); require(to != address(this)); _; } constructor ( uint _totalTokenAmount ) public { totalSupply_ = _totalTokenAmount; balances[msg.sender] = _totalTokenAmount; emit Transfer(address(0x0), msg.sender, _totalTokenAmount); } function transfer(address _to, uint _value) public validDestination(_to) returns (bool) { require(!isBlackListed[msg.sender]); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public validDestination(_to) returns (bool) { require(!isBlackListed[_from]); return super.transferFrom(_from, _to, _value); } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(uint _value) public onlyOwner { require(totalSupply_ + _value > totalSupply_); require(balances[owner] + _value > balances[owner]); totalSupply_ = totalSupply_.add(_value); balances[owner]=balances[owner].add(_value); emit Issue(_value); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(uint _value) public onlyOwner { require(totalSupply_ >= _value); require(balances[owner] >= _value); totalSupply_ = totalSupply_.sub(_value); balances[owner]=balances[owner].sub(_value); emit Redeem(_value); } // Called when new token are issued event Issue(uint _value); // Called when tokens are redeemed event Redeem(uint _value); }
Called when new token are issued
event Issue(uint _value);
11,935,373
[ 1, 4625, 348, 7953, 560, 30, 225, 11782, 1347, 394, 1147, 854, 16865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 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, 11820, 12, 11890, 389, 1132, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x15879074Bd6c89a8a5d88A7Be08fEfb174a54511/sources/ZKWRouterV2.sol
returns sorted token addresses, used to handle return values from pairs sorted in this order
library ZKWLibrary { using SafeMath for uint; function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'ZKWLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'ZKWLibrary: ZERO_ADDRESS'); } function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { pair = IZKWFactory(factory).getPair(tokenA, tokenB); } function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); pairFor(factory, tokenA, tokenB); (uint reserve0, uint reserve1,) = IZKWPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'ZKWLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'ZKWLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, address token0, address token1, address factory_) internal view returns (uint amountOut) { require(amountIn > 0, 'ZKWLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'ZKWLibrary: INSUFFICIENT_LIQUIDITY'); address pair = pairFor(factory_, token0, token1); (,,uint256 _totalFee) = IZKWFactory(factory_).feeList(pair); uint amountInWithFee = amountIn.mul(uint256(10000).sub(_totalFee)); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, address token0, address token1, address factory_) internal view returns (uint amountIn) { require(amountOut > 0, 'ZKWLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'ZKWLibrary: INSUFFICIENT_LIQUIDITY'); address pair = pairFor(factory_, token0, token1); (,,uint256 _totalFee) = IZKWFactory(factory_).feeList(pair); uint numerator = reserveIn.mul(amountOut).mul(10000); uint denominator = reserveOut.sub(amountOut).mul(uint256(10000).sub(_totalFee)); amountIn = (numerator / denominator).add(1); } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'ZKWLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, path[i], path[i + 1], factory); } } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'ZKWLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, path[i], path[i + 1], factory); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'ZKWLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, path[i - 1], path[i], factory); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'ZKWLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, path[i - 1], path[i], factory); } } }
16,794,070
[ 1, 4625, 348, 7953, 560, 30, 225, 1135, 3115, 1147, 6138, 16, 1399, 358, 1640, 327, 924, 628, 5574, 3115, 316, 333, 1353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 29878, 59, 9313, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 445, 1524, 5157, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 16618, 1135, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 288, 203, 3639, 2583, 12, 2316, 37, 480, 1147, 38, 16, 296, 62, 30134, 9313, 30, 19768, 10109, 67, 8355, 7031, 1090, 55, 8284, 203, 3639, 261, 2316, 20, 16, 1147, 21, 13, 273, 1147, 37, 411, 1147, 38, 692, 261, 2316, 37, 16, 1147, 38, 13, 294, 261, 2316, 38, 16, 1147, 37, 1769, 203, 3639, 2583, 12, 2316, 20, 480, 1758, 12, 20, 3631, 296, 62, 30134, 9313, 30, 18449, 67, 15140, 8284, 203, 565, 289, 203, 203, 203, 565, 445, 3082, 1290, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 1476, 1135, 261, 2867, 3082, 13, 288, 203, 3639, 3082, 273, 467, 62, 30134, 1733, 12, 6848, 2934, 588, 4154, 12, 2316, 37, 16, 1147, 38, 1769, 203, 565, 289, 203, 203, 565, 445, 31792, 264, 3324, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 1476, 1135, 261, 11890, 20501, 37, 16, 2254, 20501, 38, 13, 288, 203, 3639, 261, 2867, 1147, 20, 16, 13, 273, 1524, 5157, 12, 2316, 37, 16, 1147, 38, 1769, 203, 3639, 3082, 1290, 12, 6848, 16, 1147, 37, 16, 1147, 38, 1769, 203, 3639, 261, 11890, 20501, 20, 16, 2254, 20501, 21, 16, 13, 273, 467, 62, 30134, 4154, 12, 6017, 1290, 12, 6848, 16, 1147, 37, 16, 1147, 38, 13, 2934, 588, 607, 264, 3324, 5621, 203, 3639, 261, 455, 6527, 37, 16, 20501, 38, 13, 273, 1147, 37, 422, 1147, 20, 692, 261, 455, 6527, 20, 16, 20501, 21, 13, 294, 261, 455, 6527, 21, 16, 20501, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 3862, 12, 11890, 3844, 37, 16, 2254, 20501, 37, 16, 2254, 20501, 38, 13, 2713, 16618, 1135, 261, 11890, 3844, 38, 13, 288, 203, 3639, 2583, 12, 8949, 37, 405, 374, 16, 296, 62, 30134, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 455, 6527, 37, 405, 374, 597, 20501, 38, 405, 374, 16, 296, 62, 30134, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 3639, 3844, 38, 273, 3844, 37, 18, 16411, 12, 455, 6527, 38, 13, 342, 20501, 37, 31, 203, 565, 289, 203, 203, 565, 445, 24418, 1182, 12, 11890, 3844, 382, 16, 2254, 20501, 382, 16, 2254, 20501, 1182, 16, 1758, 1147, 20, 16, 1758, 1147, 21, 16, 1758, 3272, 67, 13, 2713, 1476, 1135, 261, 11890, 3844, 1182, 13, 288, 203, 3639, 2583, 12, 8949, 382, 405, 374, 16, 296, 62, 30134, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15934, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 455, 6527, 382, 405, 374, 597, 20501, 1182, 405, 374, 16, 296, 62, 30134, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 3639, 1758, 3082, 273, 3082, 1290, 12, 6848, 67, 16, 1147, 20, 16, 1147, 21, 1769, 203, 3639, 261, 16408, 11890, 5034, 389, 4963, 14667, 13, 273, 467, 62, 30134, 1733, 12, 6848, 67, 2934, 21386, 682, 12, 6017, 1769, 203, 3639, 2254, 3844, 382, 1190, 14667, 273, 3844, 382, 18, 16411, 12, 11890, 5034, 12, 23899, 2934, 1717, 24899, 4963, 14667, 10019, 203, 3639, 2254, 16730, 273, 3844, 382, 1190, 14667, 18, 16411, 12, 455, 6527, 1182, 1769, 203, 3639, 2254, 15030, 273, 20501, 382, 18, 16411, 12, 23899, 2934, 1289, 12, 8949, 382, 1190, 14667, 1769, 203, 3639, 3844, 1182, 273, 16730, 342, 15030, 31, 203, 565, 289, 203, 203, 565, 445, 24418, 382, 12, 11890, 3844, 1182, 16, 2254, 20501, 382, 16, 2254, 20501, 1182, 16, 1758, 1147, 20, 16, 1758, 1147, 21, 16, 1758, 3272, 67, 13, 2713, 1476, 1135, 261, 11890, 3844, 382, 13, 288, 203, 3639, 2583, 12, 8949, 1182, 405, 374, 16, 296, 62, 30134, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15527, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 455, 6527, 382, 405, 374, 597, 20501, 1182, 405, 374, 16, 296, 62, 30134, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 3639, 1758, 3082, 273, 3082, 1290, 12, 6848, 67, 16, 1147, 20, 16, 1147, 21, 1769, 203, 3639, 261, 16408, 11890, 5034, 389, 4963, 14667, 13, 273, 467, 62, 30134, 1733, 12, 6848, 67, 2934, 21386, 682, 12, 6017, 1769, 203, 3639, 2254, 16730, 273, 20501, 382, 18, 16411, 12, 8949, 1182, 2934, 16411, 12, 23899, 1769, 203, 3639, 2254, 15030, 273, 20501, 1182, 18, 1717, 12, 8949, 1182, 2934, 16411, 12, 11890, 5034, 12, 23899, 2934, 1717, 24899, 4963, 14667, 10019, 203, 3639, 3844, 382, 273, 261, 2107, 7385, 342, 15030, 2934, 1289, 12, 21, 1769, 203, 565, 289, 203, 203, 565, 445, 24418, 87, 1182, 12, 2867, 3272, 16, 2254, 3844, 382, 16, 1758, 8526, 3778, 589, 13, 2713, 1476, 1135, 261, 11890, 8526, 3778, 30980, 13, 288, 203, 3639, 2583, 12, 803, 18, 2469, 1545, 576, 16, 296, 62, 30134, 9313, 30, 10071, 67, 4211, 8284, 203, 3639, 30980, 273, 394, 2254, 8526, 12, 803, 18, 2469, 1769, 203, 3639, 30980, 63, 20, 65, 273, 3844, 382, 31, 203, 3639, 364, 261, 11890, 277, 31, 277, 411, 589, 18, 2469, 300, 404, 31, 277, 27245, 288, 203, 5411, 261, 11890, 20501, 382, 16, 2254, 20501, 1182, 13, 273, 31792, 264, 3324, 12, 6848, 16, 589, 63, 77, 6487, 589, 63, 77, 397, 404, 19226, 203, 5411, 30980, 63, 77, 397, 404, 65, 273, 24418, 1182, 12, 8949, 87, 63, 77, 6487, 20501, 382, 16, 20501, 1182, 16, 589, 63, 77, 6487, 589, 63, 77, 397, 404, 6487, 3272, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 24418, 87, 1182, 12, 2867, 3272, 16, 2254, 3844, 382, 16, 1758, 8526, 3778, 589, 13, 2713, 1476, 1135, 261, 11890, 8526, 3778, 30980, 13, 288, 203, 3639, 2583, 12, 803, 18, 2469, 1545, 576, 16, 296, 62, 30134, 9313, 30, 10071, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; /// @author jpegmint.xyz import "../token/ERC721/ERC721EnumerableOrdered.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; abstract contract ERC721Collectible is ERC721, ERC721EnumerableOrdered, Ownable { /// Variables /// bool internal _paused; uint256 internal _tokenMaxSupply; uint256 internal _tokenPrice; uint256 internal _tokenMaxPerTxn; uint256[] internal _tokenIdTracker; /// Events /// event SalePaused(address account); event SaleUnpaused(address account); //================================================================================ // Constructor //================================================================================ /** * @dev Starts paused and initializes metadata. */ constructor( string memory name, string memory symbol, uint256 tokenMaxSupply, uint256 tokenPrice, uint256 tokenMaxPerTxn ) ERC721(name, symbol) { _paused = true; _tokenMaxSupply = tokenMaxSupply; _tokenPrice = tokenPrice; _tokenMaxPerTxn = tokenMaxPerTxn; _tokenIdTracker = new uint256[](_tokenMaxSupply); } //================================================================================ // Hooks //================================================================================ /** * @dev Various lifecycle hooks to add checks or functionality. */ function _beforeStartingSale() internal virtual {} function _beforeBatchMint(address to, uint256 howMany) internal virtual {} function _beforeTokenMint(address to, uint256 tokenId, uint256 currentIndex) internal virtual {} function _afterTokenMint(address to, uint256 tokenId, uint256 currentIndex) internal virtual {} function _afterBatchMint(address to, uint256 howMany, uint256[] memory mintedTokenIds) internal virtual {} //================================================================================ // Sale Functions //================================================================================ function startSale() public virtual onlyOwner { require(_paused, "Collectible: Sale is already started"); _beforeStartingSale(); _paused = false; emit SaleUnpaused(msg.sender); } function pauseSale() public virtual onlyOwner { require(!_paused, "Collectible: Sale is already paused"); _paused = true; emit SalePaused(msg.sender); } function isPaused() public view returns (bool) { return _paused; } function isSoldOut() public view returns (bool) { return totalSupply() == _tokenMaxSupply; } function availableSupply() public view returns (uint256) { return _tokenMaxSupply - totalSupply(); } //================================================================================ // Minting Functions //================================================================================ /** * @dev Standard public sale minting function. Override to activate. */ function _purchase(uint256 howMany) internal virtual { require(!isPaused(), "Collectible: Sale is paused"); require(howMany <= _tokenMaxPerTxn, "Collectible: Qty exceed max per txn"); require(msg.value >= howMany * _tokenPrice, "Collectible: Not enough ether sent"); _mintCollectibles(msg.sender, howMany); } /** * @dev Core batch minting function. Checks key requirements and fires hooks. */ function _mintCollectibles(address to, uint256 howMany) internal virtual { require(!isSoldOut(), "Collectible: Contract is sold out"); require(availableSupply() >= howMany, "Collectible: Qty exceeds max supply"); _beforeBatchMint(to, howMany); uint256[] memory mintedTokenIds = new uint256[](howMany); for (uint256 i = 0; i < howMany; i++) { uint256 tokenId = _generateTokenId(to, howMany, i); _beforeTokenMint(to, tokenId, i); _safeMint(to, tokenId); _afterTokenMint(to, tokenId, i); mintedTokenIds[i] = tokenId; } _afterBatchMint(to, howMany, mintedTokenIds); } /** * @dev Generate random tokenIds using meebits random ID strategy. */ function _generateTokenId(address, uint256, uint256) internal virtual returns (uint256) { uint256 remainingQty = availableSupply(); uint256 randomNum = uint256(keccak256(abi.encodePacked(msg.sender, tx.gasprice, block.timestamp, remainingQty))); uint256 randomIndex = randomNum % remainingQty; // If array value exists, use, otherwise use generated random value. uint256 existingValue = _tokenIdTracker[randomIndex]; uint256 tokenId = existingValue != 0 ? existingValue : randomIndex; // Keep track of seen indexes for black magic. uint256 endIndex = remainingQty - 1; uint256 endValue = _tokenIdTracker[endIndex]; _tokenIdTracker[randomIndex] = endValue != 0 ? endValue : endIndex; return tokenId + 1; // Start tokens at #1 } //================================================================================ // Withdrawal Functions //================================================================================ /** * @dev Simple withdrawal implementation. Sends balance to msg.sender. */ function withdraw() external virtual onlyOwner { payable(msg.sender).transfer(address(this).balance); } //================================================================================ // Other Functions //================================================================================ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721EnumerableOrdered) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721EnumerableOrdered) returns (bool) { return super.supportsInterface(interfaceId); } }
* @dev Generate random tokenIds using meebits random ID strategy./ If array value exists, use, otherwise use generated random value. Keep track of seen indexes for black magic.
function _generateTokenId(address, uint256, uint256) internal virtual returns (uint256) { uint256 remainingQty = availableSupply(); uint256 randomNum = uint256(keccak256(abi.encodePacked(msg.sender, tx.gasprice, block.timestamp, remainingQty))); uint256 randomIndex = randomNum % remainingQty; uint256 existingValue = _tokenIdTracker[randomIndex]; uint256 tokenId = existingValue != 0 ? existingValue : randomIndex; uint256 endIndex = remainingQty - 1; uint256 endValue = _tokenIdTracker[endIndex]; _tokenIdTracker[randomIndex] = endValue != 0 ? endValue : endIndex; }
12,800,547
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 6654, 2744, 1147, 2673, 1450, 312, 1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, 12, 2867, 16, 2254, 5034, 16, 2254, 5034, 13, 2713, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 4463, 53, 4098, 273, 2319, 3088, 1283, 5621, 203, 3639, 2254, 5034, 2744, 2578, 273, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 16, 2229, 18, 31604, 8694, 16, 1203, 18, 5508, 16, 4463, 53, 4098, 3719, 1769, 203, 3639, 2254, 5034, 2744, 1016, 273, 2744, 2578, 738, 4463, 53, 4098, 31, 203, 203, 3639, 2254, 5034, 2062, 620, 273, 389, 2316, 548, 8135, 63, 9188, 1016, 15533, 203, 3639, 2254, 5034, 1147, 548, 273, 2062, 620, 480, 374, 692, 2062, 620, 294, 2744, 1016, 31, 203, 203, 3639, 2254, 5034, 13818, 273, 4463, 53, 4098, 300, 404, 31, 203, 3639, 2254, 5034, 30684, 273, 389, 2316, 548, 8135, 63, 409, 1016, 15533, 203, 3639, 389, 2316, 548, 8135, 63, 9188, 1016, 65, 273, 30684, 480, 374, 692, 30684, 294, 13818, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xc94E3Fd7270be44da019c8c3dB1D2e4d0064063A/sources/contracts/lib/ERC4626.sol
@notice Minimal ERC4626 tokenized Vault implementation. @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol)
abstract contract ERC4626 is ERC20, ReentrancyGuard { using SafeTransferLib for ERC20; using FixedPointMathLib for uint256; uint private constant MIN_DEPOSIT = 1E3; EVENTS event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); IMMUTABLES ERC20 public immutable asset; constructor( ERC20 _asset, string memory _name, string memory _symbol pragma solidity >=0.8.0; import {ERC20} from "./ERC20.sol"; import {SafeTransferLib} from "./SafeTransferLib.sol"; import {FixedPointMathLib} from "./FixedPointMathLib.sol"; ) ERC20(_name, _symbol, _asset.decimals()) { asset = _asset; } DEPOSIT/WITHDRAWAL LOGIC function deposit(uint256 assets, address receiver) public virtual nonReentrant returns (uint256 shares) { require(assets > MIN_DEPOSIT, 'ER043'); require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES"); asset.safeTransferFrom(msg.sender, address(this), assets); _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); afterDeposit(assets, shares); } function mint(uint256 shares, address receiver) public virtual nonReentrant returns (uint256 assets) { require(assets > MIN_DEPOSIT, 'ER043'); asset.safeTransferFrom(msg.sender, address(this), assets); _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); afterDeposit(assets, shares); } function withdraw( uint256 assets, address receiver, address owner ) public virtual nonReentrant returns (uint256 shares) { if (msg.sender != owner) { if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } beforeWithdraw(assets, shares); _burn(owner, shares); emit Withdraw(msg.sender, receiver, owner, assets, shares); asset.safeTransfer(receiver, assets); } function withdraw( uint256 assets, address receiver, address owner ) public virtual nonReentrant returns (uint256 shares) { if (msg.sender != owner) { if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } beforeWithdraw(assets, shares); _burn(owner, shares); emit Withdraw(msg.sender, receiver, owner, assets, shares); asset.safeTransfer(receiver, assets); } function redeem( uint256 shares, address receiver, address owner ) public virtual nonReentrant returns (uint256 assets) { if (msg.sender != owner) { if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } beforeWithdraw(assets, shares); _burn(owner, shares); emit Withdraw(msg.sender, receiver, owner, assets, shares); asset.safeTransfer(receiver, assets); } ACCOUNTING LOGIC function redeem( uint256 shares, address receiver, address owner ) public virtual nonReentrant returns (uint256 assets) { if (msg.sender != owner) { if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } beforeWithdraw(assets, shares); _burn(owner, shares); emit Withdraw(msg.sender, receiver, owner, assets, shares); asset.safeTransfer(receiver, assets); } ACCOUNTING LOGIC require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS"); function totalAssets() public view virtual returns (uint256); function convertToShares(uint256 assets) public view virtual returns (uint256) { return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets()); } function convertToAssets(uint256 shares) public view virtual returns (uint256) { return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply); } function previewDeposit(uint256 assets) public view virtual returns (uint256) { return convertToShares(assets); } function previewMint(uint256 shares) public view virtual returns (uint256) { return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply); } function previewWithdraw(uint256 assets) public view virtual returns (uint256) { return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets()); } function previewRedeem(uint256 shares) public view virtual returns (uint256) { return convertToAssets(shares); } DEPOSIT/WITHDRAWAL LIMIT LOGIC function maxDeposit(address) public view virtual returns (uint256) { return type(uint256).max; } function maxMint(address) public view virtual returns (uint256) { return type(uint256).max; } function maxWithdraw(address owner) public view virtual returns (uint256) { return convertToAssets(balanceOf[owner]); } function maxRedeem(address owner) public view virtual returns (uint256) { return balanceOf[owner]; } INTERNAL HOOKS LOGIC function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {} function afterDeposit(uint256 assets, uint256 shares) internal virtual {} }
3,007,964
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 5444, 2840, 4232, 39, 8749, 5558, 26073, 17329, 4471, 18, 632, 4161, 348, 355, 81, 340, 261, 4528, 2207, 6662, 18, 832, 19, 54, 12954, 17, 4664, 7053, 19, 18281, 81, 340, 19, 10721, 19, 5254, 19, 4816, 19, 14860, 2679, 19, 654, 39, 8749, 5558, 18, 18281, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 8749, 5558, 353, 4232, 39, 3462, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 5912, 5664, 364, 4232, 39, 3462, 31, 203, 565, 1450, 15038, 2148, 10477, 5664, 364, 2254, 5034, 31, 203, 203, 565, 2254, 3238, 5381, 6989, 67, 1639, 28284, 273, 404, 41, 23, 31, 203, 203, 4766, 9964, 55, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 4894, 16, 1758, 8808, 3410, 16, 2254, 5034, 7176, 16, 2254, 5034, 24123, 1769, 203, 203, 565, 871, 3423, 9446, 12, 203, 3639, 1758, 8808, 4894, 16, 203, 3639, 1758, 8808, 5971, 16, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 2254, 5034, 7176, 16, 203, 3639, 2254, 5034, 24123, 203, 565, 11272, 203, 203, 1171, 9079, 6246, 49, 1693, 2782, 55, 203, 203, 565, 4232, 39, 3462, 1071, 11732, 3310, 31, 203, 203, 565, 3885, 12, 203, 3639, 4232, 39, 3462, 389, 9406, 16, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 5666, 288, 654, 39, 3462, 97, 628, 25165, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 288, 9890, 5912, 5664, 97, 628, 25165, 9890, 5912, 5664, 18, 18281, 14432, 203, 5666, 288, 7505, 2148, 10477, 5664, 97, 628, 25165, 7505, 2148, 10477, 5664, 18, 18281, 14432, 203, 565, 262, 4232, 39, 3462, 24899, 529, 16, 389, 7175, 16, 389, 9406, 18, 31734, 10756, 288, 203, 3639, 3310, 273, 389, 9406, 31, 203, 565, 289, 203, 203, 13491, 2030, 28284, 19, 9147, 40, 10821, 1013, 2018, 2871, 203, 203, 565, 445, 443, 1724, 12, 11890, 5034, 7176, 16, 1758, 5971, 13, 1071, 5024, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 24123, 13, 288, 203, 3639, 2583, 12, 9971, 405, 6989, 67, 1639, 28284, 16, 296, 654, 3028, 23, 8284, 203, 203, 3639, 2583, 12443, 30720, 273, 10143, 758, 1724, 12, 9971, 3719, 480, 374, 16, 315, 24968, 67, 8325, 7031, 8863, 203, 203, 3639, 3310, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 7176, 1769, 203, 203, 3639, 389, 81, 474, 12, 24454, 16, 24123, 1769, 203, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 5971, 16, 7176, 16, 24123, 1769, 203, 203, 3639, 1839, 758, 1724, 12, 9971, 16, 24123, 1769, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 11890, 5034, 24123, 16, 1758, 5971, 13, 1071, 5024, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 7176, 13, 288, 203, 3639, 2583, 12, 9971, 405, 6989, 67, 1639, 28284, 16, 296, 654, 3028, 23, 8284, 203, 203, 3639, 3310, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 7176, 1769, 203, 203, 3639, 389, 81, 474, 12, 24454, 16, 24123, 1769, 203, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 5971, 16, 7176, 16, 24123, 1769, 203, 203, 3639, 1839, 758, 1724, 12, 9971, 16, 24123, 1769, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 12, 203, 3639, 2254, 5034, 7176, 16, 203, 3639, 1758, 5971, 16, 203, 3639, 1758, 3410, 203, 565, 262, 1071, 5024, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 24123, 13, 288, 203, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 203, 5411, 309, 261, 8151, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 1699, 1359, 63, 8443, 6362, 3576, 18, 15330, 65, 273, 2935, 300, 24123, 31, 203, 3639, 289, 203, 203, 3639, 1865, 1190, 9446, 12, 9971, 16, 24123, 1769, 203, 203, 3639, 389, 70, 321, 12, 8443, 16, 24123, 1769, 203, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 5971, 16, 3410, 16, 7176, 16, 24123, 1769, 203, 203, 3639, 3310, 18, 4626, 5912, 12, 24454, 16, 7176, 1769, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 12, 203, 3639, 2254, 5034, 7176, 16, 203, 3639, 1758, 5971, 16, 203, 3639, 1758, 3410, 203, 565, 262, 1071, 5024, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 24123, 13, 288, 203, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 203, 5411, 309, 261, 8151, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 1699, 1359, 63, 8443, 6362, 3576, 18, 15330, 65, 273, 2935, 300, 24123, 31, 203, 3639, 289, 203, 203, 3639, 1865, 1190, 9446, 12, 9971, 16, 24123, 1769, 203, 203, 3639, 389, 70, 321, 12, 8443, 16, 24123, 1769, 203, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 5971, 16, 3410, 16, 7176, 16, 24123, 1769, 203, 203, 3639, 3310, 18, 4626, 5912, 12, 24454, 16, 7176, 1769, 203, 565, 289, 203, 203, 565, 445, 283, 24903, 12, 203, 3639, 2254, 5034, 24123, 16, 203, 3639, 1758, 5971, 16, 203, 3639, 1758, 3410, 203, 565, 262, 1071, 5024, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 7176, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 203, 5411, 309, 261, 8151, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 1699, 1359, 63, 8443, 6362, 3576, 18, 15330, 65, 273, 2935, 300, 24123, 31, 203, 3639, 289, 203, 203, 203, 3639, 1865, 1190, 9446, 12, 9971, 16, 24123, 1769, 203, 203, 3639, 389, 70, 321, 12, 8443, 16, 24123, 1769, 203, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 5971, 16, 3410, 16, 7176, 16, 24123, 1769, 203, 203, 3639, 3310, 18, 4626, 5912, 12, 24454, 16, 7176, 1769, 203, 565, 289, 203, 203, 21821, 29437, 1360, 2018, 2871, 203, 565, 445, 283, 24903, 12, 203, 3639, 2254, 5034, 24123, 16, 203, 3639, 1758, 5971, 16, 203, 3639, 1758, 3410, 203, 565, 262, 1071, 5024, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 7176, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 203, 5411, 309, 261, 8151, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 1699, 1359, 63, 8443, 6362, 3576, 18, 15330, 65, 273, 2935, 300, 24123, 31, 203, 3639, 289, 203, 203, 203, 3639, 1865, 1190, 9446, 12, 9971, 16, 24123, 1769, 203, 203, 3639, 389, 70, 321, 12, 8443, 16, 24123, 1769, 203, 203, 3639, 3626, 3423, 2 ]
./partial_match/56/0x4cC0295a30C3c2eA5b0a76ac4BF75a7CFb423fA8/sources/TestyToken.sol
MasterChef is the master of TSTI. He can make TSTI and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once TSTI is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; struct UserInfo { } struct PoolInfo { } 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( TestyToken _TSTI, address _devaddr, address _feeAddress, uint256 _TSTIPerBlock, uint256 _startBlock TestyToken public TSTI; address public devaddr; uint256 public TSTIPerBlock; uint256 public constant BONUS_MULTIPLIER = 1; address public feeAddress; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; ) public { TSTI = _TSTI; devaddr = _devaddr; feeAddress = _feeAddress; TSTIPerBlock = _TSTIPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTSTIPerShare: 0, depositFeeBP: _depositFeeBP })); } function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTSTIPerShare: 0, depositFeeBP: _depositFeeBP })); } function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTSTIPerShare: 0, depositFeeBP: _depositFeeBP })); } function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } function pendingTSTI(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTSTIPerShare = pool.accTSTIPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 TSTIReward = multiplier.mul(TSTIPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTSTIPerShare = accTSTIPerShare.add(TSTIReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTSTIPerShare).div(1e12).sub(user.rewardDebt); } function pendingTSTI(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTSTIPerShare = pool.accTSTIPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 TSTIReward = multiplier.mul(TSTIPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTSTIPerShare = accTSTIPerShare.add(TSTIReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTSTIPerShare).div(1e12).sub(user.rewardDebt); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 TSTIReward = multiplier.mul(TSTIPerBlock).mul(pool.allocPoint).div(totalAllocPoint); TSTI.mint(devaddr, TSTIReward.div(10)); TSTI.mint(address(this), TSTIReward); pool.accTSTIPerShare = pool.accTSTIPerShare.add(TSTIReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 TSTIReward = multiplier.mul(TSTIPerBlock).mul(pool.allocPoint).div(totalAllocPoint); TSTI.mint(devaddr, TSTIReward.div(10)); TSTI.mint(address(this), TSTIReward); pool.accTSTIPerShare = pool.accTSTIPerShare.add(TSTIReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 TSTIReward = multiplier.mul(TSTIPerBlock).mul(pool.allocPoint).div(totalAllocPoint); TSTI.mint(devaddr, TSTIReward.div(10)); TSTI.mint(address(this), TSTIReward); pool.accTSTIPerShare = pool.accTSTIPerShare.add(TSTIReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } }else{ 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.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } 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.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } 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.accTSTIPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTSTITransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTSTIPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } function safeTSTITransfer(address _to, uint256 _amount) internal { uint256 TSTIBal = TSTI.balanceOf(address(this)); if (_amount > TSTIBal) { TSTI.transfer(_to, TSTIBal); TSTI.transfer(_to, _amount); } } function safeTSTITransfer(address _to, uint256 _amount) internal { uint256 TSTIBal = TSTI.balanceOf(address(this)); if (_amount > TSTIBal) { TSTI.transfer(_to, TSTIBal); TSTI.transfer(_to, _amount); } } } else { function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function setFeeAddress(address _feeAddress) public{ require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); feeAddress = _feeAddress; } function updateEmissionRate(uint256 _TSTIPerBlock) public onlyOwner { massUpdatePools(); TSTIPerBlock = _TSTIPerBlock; } function transferERC20(address tokenAddress) external onlyOwner { IBEP20(tokenAddress).transfer(msg.sender, IBEP20(tokenAddress).balanceOf(address(this))); } }
11,056,042
[ 1, 4625, 348, 7953, 560, 30, 225, 13453, 39, 580, 74, 353, 326, 4171, 434, 399, 882, 45, 18, 8264, 848, 1221, 399, 882, 45, 471, 3904, 353, 279, 284, 1826, 3058, 93, 18, 3609, 716, 518, 1807, 4953, 429, 471, 326, 3410, 341, 491, 87, 268, 2764, 409, 1481, 7212, 18, 1021, 23178, 903, 506, 906, 4193, 358, 279, 314, 1643, 82, 1359, 13706, 6835, 3647, 399, 882, 45, 353, 18662, 715, 16859, 471, 326, 19833, 848, 2405, 358, 314, 1643, 82, 6174, 18, 21940, 9831, 6453, 518, 18, 670, 1306, 4095, 518, 1807, 7934, 17, 9156, 18, 611, 369, 324, 2656, 18, 3807, 434, 1517, 729, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13453, 39, 580, 74, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 5948, 52, 3462, 364, 467, 5948, 52, 3462, 31, 203, 203, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 3885, 12, 203, 3639, 7766, 93, 1345, 389, 56, 882, 45, 16, 203, 3639, 1758, 389, 5206, 4793, 16, 203, 3639, 1758, 389, 21386, 1887, 16, 203, 3639, 2254, 5034, 389, 56, 882, 45, 2173, 1768, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 203, 565, 7766, 93, 1345, 1071, 399, 882, 45, 31, 203, 565, 1758, 1071, 4461, 4793, 31, 203, 565, 2254, 5034, 1071, 399, 882, 45, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 404, 31, 203, 565, 1758, 1071, 14036, 1887, 31, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 261, 2867, 516, 25003, 3719, 1071, 16753, 31, 203, 565, 2254, 5034, 1071, 2078, 8763, 2148, 273, 374, 31, 203, 565, 2254, 5034, 1071, 787, 1768, 31, 203, 565, 262, 1071, 288, 203, 3639, 399, 882, 45, 273, 389, 56, 882, 45, 31, 203, 3639, 4461, 4793, 273, 389, 5206, 4793, 31, 203, 3639, 14036, 1887, 273, 389, 21386, 1887, 31, 203, 3639, 399, 882, 45, 2173, 1768, 273, 389, 56, 882, 45, 2173, 1768, 31, 203, 3639, 787, 1768, 273, 389, 1937, 1768, 31, 203, 565, 289, 203, 203, 565, 445, 2845, 1782, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2845, 966, 18, 2469, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 5948, 52, 3462, 389, 9953, 1345, 16, 2254, 2313, 389, 323, 1724, 14667, 30573, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 323, 1724, 14667, 30573, 1648, 12619, 16, 315, 1289, 30, 2057, 443, 1724, 14036, 10853, 3143, 8863, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 56, 882, 45, 2173, 9535, 30, 374, 16, 203, 5411, 443, 1724, 14667, 30573, 30, 389, 323, 1724, 14667, 30573, 203, 3639, 289, 10019, 203, 565, 289, 203, 203, 565, 445, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 5948, 52, 3462, 389, 9953, 1345, 16, 2254, 2313, 389, 323, 1724, 14667, 30573, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 323, 1724, 14667, 30573, 1648, 12619, 16, 315, 1289, 30, 2057, 443, 1724, 14036, 10853, 3143, 8863, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 56, 882, 45, 2173, 9535, 30, 374, 16, 203, 5411, 443, 1724, 14667, 30573, 30, 389, 323, 1724, 14667, 30573, 203, 3639, 289, 10019, 203, 565, 289, 203, 203, 565, 445, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 5948, 52, 3462, 389, 9953, 1345, 16, 2254, 2313, 389, 323, 1724, 14667, 30573, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 323, 1724, 14667, 30573, 1648, 12619, 16, 315, 1289, 30, 2057, 443, 1724, 14036, 10853, 3143, 8863, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 56, 882, 45, 2173, 9535, 30, 374, 16, 203, 5411, 443, 1724, 14667, 30573, 30, 389, 323, 1724, 14667, 30573, 203, 3639, 289, 10019, 203, 565, 289, 203, 203, 565, 445, 444, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 9853, 2148, 16, 2254, 2313, 389, 323, 1724, 14667, 30573, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 323, 1724, 14667, 30573, 1648, 12619, 16, 315, 542, 30, 2057, 443, 1724, 14036, 10853, 3143, 8863, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1717, 12, 6011, 966, 63, 67, 6610, 8009, 9853, 2148, 2934, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 63, 67, 6610, 8009, 9853, 2148, 273, 389, 9853, 2148, 31, 203, 3639, 2845, 966, 63, 67, 6610, 8009, 323, 1724, 2 ]
./partial_match/8453/0x6A110a68aD7bb1734603BC28B82c0c9AFf98bc81/sources/FeeManager.sol
* @dev Function to set new master copy and update contract bytecode to install. Can only be called by factory owner @param _masterCopy Address of linkdrop mastercopy contract to calculate bytecode from @return True if updated successfully/
function setMasterCopy(address payable _masterCopy) public onlyOwner returns (bool) { require(_masterCopy != address(0), "INVALID_MASTER_COPY_ADDRESS"); masterCopyVersion = masterCopyVersion.add(1); require ( ILinkdropCommon(_masterCopy).initialize ( masterCopyVersion, chainId, ), "INITIALIZATION_FAILED" ); bytes memory bytecode = abi.encodePacked ( hex"363d3d373d3d3d363d73", _masterCopy, hex"5af43d82803e903d91602b57fd5bf3" ); _bytecode = bytecode; emit SetMasterCopy(_masterCopy, masterCopyVersion); return true; }
16,757,558
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 4284, 358, 444, 394, 4171, 1610, 471, 1089, 6835, 22801, 358, 3799, 18, 4480, 1338, 506, 2566, 635, 3272, 3410, 632, 891, 389, 7525, 2951, 5267, 434, 1692, 7285, 4171, 3530, 6835, 358, 4604, 22801, 628, 632, 2463, 1053, 309, 3526, 4985, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7786, 2951, 12, 2867, 8843, 429, 389, 7525, 2951, 13, 203, 565, 1071, 1338, 5541, 203, 565, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 24899, 7525, 2951, 480, 1758, 12, 20, 3631, 315, 9347, 67, 28045, 67, 24875, 67, 15140, 8863, 203, 3639, 4171, 2951, 1444, 273, 4171, 2951, 1444, 18, 1289, 12, 21, 1769, 203, 203, 3639, 2583, 203, 3639, 261, 203, 5411, 467, 2098, 7285, 6517, 24899, 7525, 2951, 2934, 11160, 203, 5411, 261, 203, 7734, 4171, 2951, 1444, 16, 203, 7734, 2687, 548, 16, 203, 5411, 262, 16, 203, 5411, 315, 12919, 15154, 2689, 67, 11965, 6, 203, 3639, 11272, 203, 203, 3639, 1731, 3778, 22801, 273, 24126, 18, 3015, 4420, 329, 203, 3639, 261, 203, 5411, 3827, 6, 23, 4449, 72, 23, 72, 6418, 23, 72, 23, 72, 23, 72, 23, 4449, 72, 9036, 3113, 203, 5411, 389, 7525, 2951, 16, 203, 5411, 3827, 6, 25, 1727, 8942, 72, 11149, 3672, 23, 73, 29, 4630, 72, 29, 2313, 3103, 70, 10321, 8313, 25, 17156, 23, 6, 203, 3639, 11272, 203, 203, 3639, 389, 1637, 16651, 273, 22801, 31, 203, 203, 3639, 3626, 1000, 7786, 2951, 24899, 7525, 2951, 16, 4171, 2951, 1444, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L2DepositedERC721 } from "../iOVM/iOVM_L2DepositedERC721.sol"; import { iOVM_L1ERC721Gateway } from "../iOVM/iOVM_L1ERC721Gateway.sol"; /* Library Imports */ import { OVM_CrossDomainEnabled } from "@eth-optimism/contracts/libraries/bridge/OVM_CrossDomainEnabled.sol"; /** * @title Abs_DepositedERC721 * @dev An Deposited Token is a representation of funds which were deposited from the other side * Usually contract mints new tokens when it hears about deposits from the other side. * This contract also burns the tokens intended for withdrawal, informing the gateway to release the funds. * * NOTE: This abstract contract gives all the core functionality of a deposited token implementation except for the * token's internal accounting itself. This gives developers an easy way to implement children with their own token code. * * Compiler used: solc, optimistic-solc * Runtime target: EVM or OVM */ abstract contract Abs_L2DepositedERC721 is iOVM_L2DepositedERC721, OVM_CrossDomainEnabled { /******************* * Contract Events * *******************/ event Initialized(iOVM_L1ERC721Gateway tokenGateway); /******************************** * External Contract References * ********************************/ iOVM_L1ERC721Gateway public tokenGateway; /******************************** * Constructor & Initialization * ********************************/ /** * @param _messenger Messenger address being used for cross-chain communications. */ constructor( address _messenger ) OVM_CrossDomainEnabled(_messenger) {} /** * @dev Initialize this contract with the token gateway address on the otehr side. * The flow: 1) this contract gets deployed on one side, 2) the * gateway is deployed with addr from (1) on the other, 3) gateway address passed here. * * @param _tokenGateway Address of the corresponding gateway deployed to the other side */ function init( iOVM_L1ERC721Gateway _tokenGateway ) public { require(address(tokenGateway) == address(0), "Contract has already been initialized"); tokenGateway = _tokenGateway; emit Initialized(tokenGateway); } /********************** * Function Modifiers * **********************/ modifier onlyInitialized() { require(address(tokenGateway) != address(0), "Contract has not yet been initialized"); _; } /******************************** * Overridable Accounting logic * ********************************/ // Default gas value which can be overridden if more complex logic runs on L2. uint32 constant DEFAULT_FINALIZE_WITHDRAWAL_GAS = 1200000; /** * @dev Core logic to be performed when a withdrawal from L2 is initialized. * In most cases, this will simply burn the withdrawn L2 funds. * * param _to Address being withdrawn to * param _tokenId Token being withdrawn */ function _handleInitiateWithdrawal( address, // _to, uint // _tokenId ) internal virtual { revert("Accounting must be implemented by child contract."); } /** * @dev Core logic to be performed when a deposit is finalised. * In most cases, this will simply _mint() the ERC721 the recipient. * * param _to Address being deposited to * param _tokenId ERC721 which was deposited * param _tokenURI URI of the ERC721 which was deposited */ function _handleFinalizeDeposit( address, // _to uint,// _tokenId string memory ) internal virtual { revert("Accounting must be implemented by child contract."); } /** * @dev Overridable getter for the *Other side* gas limit of settling the withdrawal, in the case it may be * dynamic, and the above public constant does not suffice. * */ function getFinalizeWithdrawalGas() public view virtual returns( uint32 ) { return DEFAULT_FINALIZE_WITHDRAWAL_GAS; } /*************** * Withdrawing * ***************/ /** * @dev initiate a withdraw of an ERC721 to the caller's account on the other side * @param _tokenId ERC721 token to withdraw */ function withdraw( uint _tokenId ) external override onlyInitialized() { _initiateWithdrawal(msg.sender, _tokenId); } /** * @dev initiate a withdraw of an ERC721 to a recipient's account on the other side * @param _to adress to credit the withdrawal to * @param _tokenId ERC721 token to withdraw */ function withdrawTo( address _to, uint _tokenId ) external override onlyInitialized() { _initiateWithdrawal(_to, _tokenId); } /** * @dev Performs the logic for withdrawals * * @param _to Account to give the withdrawal to on the other side * @param _tokenId ERC721 token to withdraw */ function _initiateWithdrawal( address _to, uint _tokenId ) internal { // Call our withdrawal accounting handler implemented by child contracts (usually a _burn) _handleInitiateWithdrawal(_to, _tokenId); // Construct calldata for ERC721Gateway.finalizeWithdrawal(_to, _tokenId) bytes memory data = abi.encodeWithSelector( iOVM_L1ERC721Gateway.finalizeWithdrawal.selector, _to, _tokenId ); // Send message up to L1 gateway sendCrossDomainMessage( address(tokenGateway), data, getFinalizeWithdrawalGas() ); emit WithdrawalInitiated(msg.sender, _to, _tokenId); } /************************************ * Cross-chain Function: Depositing * ************************************/ /** * @dev Complete a deposit, and credits funds to the recipient's balance of the * specified ERC721 * This call will fail if it did not originate from a corresponding deposit in OVM_ERC721Gateway. * * @param _to Address to receive the withdrawal at * @param _tokenId ERC721 to deposit * @param _tokenURI URI of the token being deposited */ function finalizeDeposit( address _to, uint _tokenId, string memory _tokenURI ) external override onlyInitialized() onlyFromCrossDomainAccount(address(tokenGateway)) { _handleFinalizeDeposit(_to, _tokenId, _tokenURI); emit DepositFinalized(_to, _tokenId, _tokenURI); } }
* @dev initiate a withdraw of an ERC721 to a recipient's account on the other side @param _to adress to credit the withdrawal to @param _tokenId ERC721 token to withdraw/
function withdrawTo( address _to, uint _tokenId ) external override onlyInitialized() { _initiateWithdrawal(_to, _tokenId); }
12,552,337
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 18711, 279, 598, 9446, 434, 392, 4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 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 389, 2316, 548, 203, 565, 262, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1338, 11459, 1435, 203, 565, 288, 203, 3639, 389, 2738, 3840, 1190, 9446, 287, 24899, 869, 16, 389, 2316, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x5D0e77aA2F8a13B6892e87c05673685805118802/sources/browser/contracts/MarsPoolStaking.sol
@notice Where any user can stake their ERC20 tokens into a pool in order to farm $LPT @param _pid ID of the pool @param _amount Amount of ERC20 being staked
function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount.add(_amount) <= pool.maxStakingAmountPerUser, "deposit: can not exceed max staking amount per user"); updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accLptPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { safeLptTransfer(msg.sender, pending); } } if (_amount > 0) { pool.erc20Token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accLptPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); }
8,164,087
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 12177, 1281, 729, 848, 384, 911, 3675, 4232, 39, 3462, 2430, 1368, 279, 2845, 316, 1353, 358, 284, 4610, 271, 48, 1856, 632, 891, 389, 6610, 1599, 434, 326, 2845, 632, 891, 389, 8949, 16811, 434, 4232, 39, 3462, 3832, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 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, 203, 3639, 2583, 12, 1355, 18, 8949, 18, 1289, 24899, 8949, 13, 1648, 2845, 18, 1896, 510, 6159, 6275, 2173, 1299, 16, 315, 323, 1724, 30, 848, 486, 9943, 943, 384, 6159, 3844, 1534, 729, 8863, 203, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 203, 3639, 309, 261, 1355, 18, 8949, 405, 374, 13, 288, 203, 5411, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 48, 337, 2173, 9535, 2934, 2892, 12, 21, 73, 2643, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 5411, 309, 261, 9561, 405, 374, 13, 288, 203, 7734, 4183, 48, 337, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 8949, 405, 374, 13, 288, 203, 5411, 2845, 18, 12610, 3462, 1345, 18, 4626, 5912, 1265, 12, 2867, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 24899, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 48, 337, 2173, 9535, 2934, 2892, 12, 21, 73, 2643, 1769, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only // Code from: https://github.com/m1guelpf/lil-web3/blob/main/src/LilJuicebox.sol pragma solidity ^0.8.13; import { ERC20 } from "@rari-capital/solmate/src/tokens/ERC20.sol"; import { SafeTransferLib } from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; /// @title Project Share ERC20 /// @author Miguel Piedrafita /// @notice ERC20 token representing a share on LilJuicebox contract ProjectShare is ERC20 { /// ERRORS /// /// @notice Thrown when trying to directly call the mint or burn functions error Unauthorized(); /// @notice The manager of this campaign address public immutable manager; /// @notice Deploys a ProjectShare instance with the specified name and symbol /// @param name The name of the deployed token /// @param symbol The symbol of the deployed token /// @dev Deployed from the constructor of the LilJuicebox contract constructor(string memory name, string memory symbol) payable ERC20(name, symbol, 18) { manager = msg.sender; } /// @notice Grants the specified address a specified amount of tokens /// @param to The address that will receive the tokens /// @param amount the amount of tokens to receive /// @dev This function should be called from within LilJuicebox, and will revert if manually accessed function mint(address to, uint256 amount) public payable { if (msg.sender != manager) revert Unauthorized(); _mint(to, amount); } /// @notice Burns a specified amount of tokens from a specified address' balance /// @param from The address that will get their tokens burned /// @param amount the amount of tokens to burn /// @dev This function should be called from within LilJuicebox, and will revert if manually accessed function burn(address from, uint256 amount) public payable { if (msg.sender != manager) revert Unauthorized(); _burn(from, amount); } } /// @title lil juicebox /// @author Miguel Piedrafita /// @notice Very simple token sale + refund manager. contract LilJuicebox { /// ERRORS /// /// @notice Thrown when trying to change the state of the campaign or renounce the contract without being the manager error Unauthorized(); /// @notice Thrown when trying to claim a refund while refunds are closed error RefundsClosed(); /// @notice Thrown when trying to contribute while contributions are closed error ContributionsClosed(); /// EVENTS /// /// @notice Emitted when the manager renounces the contract, locking its current state forever event Renounced(); /// @notice Emitted when the manager withdrawns a share of the raised funds /// @param amount The amount of ETH withdrawn event Withdrawn(uint256 amount); /// @notice Emitted when the state of the campaign is changed /// @param state The new state of the campaign event StateUpdated(State state); /// @notice Emitted when a contributor successfully claims a refund /// @param contributor The address of the contributor /// @param amount The amount of ETH refunded event Refunded(address indexed contributor, uint256 amount); /// @notice Emitted when a user contributes to the campaign /// @param contributor The address of the contributor /// @param amount The amount of ETH contributed event Contributed(address indexed contributor, uint256 amount); /// @notice Possible states of a campagin enum State { CLOSED, OPEN, REFUNDING } /// @notice The address of the user who can withdraw funds and change the state of the campaign address public manager; /// @notice The current state of the campaign /// @dev This automatically generates a getter for us! State public getState; /// @notice The address of the ERC20 token representing shares of this campaign ProjectShare public immutable token; /// @notice The amount of ERC20 tokens to issue per ETH received uint256 public constant TOKENS_PER_ETH = 1_000_000; /// @notice Deploys a LilJuicebox instance with the specified name and symbol /// @param name The name of the ERC20 token /// @param symbol The symbol of the ERC20 token constructor(string memory name, string memory symbol) payable { manager = msg.sender; getState = State.OPEN; token = new ProjectShare(name, symbol); } /// @notice Contribute to the campaign by sending ETH, if contributions are open function contribute() public payable { if (getState != State.OPEN) revert ContributionsClosed(); emit Contributed(msg.sender, msg.value); token.mint(msg.sender, msg.value * TOKENS_PER_ETH); } /// @notice Receive a refund for your contribution to the campaign, if refunds are open function refund(uint256 amount) public payable { if (getState != State.REFUNDING) revert RefundsClosed(); uint256 refundETH; assembly { refundETH := div(amount, TOKENS_PER_ETH) } emit Refunded(msg.sender, refundETH); token.burn(msg.sender, amount); SafeTransferLib.safeTransferETH(msg.sender, refundETH); } /// @notice Withdraw a share of the raised funds, only available to the manager of the campaign function withdraw() public payable { if (msg.sender != manager) revert Unauthorized(); uint256 amount = address(this).balance; emit Withdrawn(amount); SafeTransferLib.safeTransferETH(msg.sender, amount); } /// @notice Update the state of the campaign, only available to the manager of the campaign /// @param state The new state of the campaign function setState(State state) public payable { if (msg.sender != manager) revert Unauthorized(); getState = state; emit StateUpdated(state); } /// @notice Renounce ownership of the campaign, effectively locking all settings in place. Only available to the manager of the campaign function renounce() public payable { if (msg.sender != manager) revert Unauthorized(); emit Renounced(); manager = address(0); } /// @dev This function ensures this contract can receive ETH receive() external payable {} }
@notice Deploys a LilJuicebox instance with the specified name and symbol @param name The name of the ERC20 token @param symbol The symbol of the ERC20 token
constructor(string memory name, string memory symbol) payable { manager = msg.sender; getState = State.OPEN; token = new ProjectShare(name, symbol); }
6,447,524
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 4019, 383, 1900, 279, 511, 330, 46, 89, 1812, 2147, 791, 598, 326, 1269, 508, 471, 3273, 632, 891, 508, 1021, 508, 434, 326, 4232, 39, 3462, 1147, 632, 891, 3273, 1021, 3273, 434, 326, 4232, 39, 3462, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 8843, 429, 288, 203, 565, 3301, 273, 1234, 18, 15330, 31, 203, 565, 8997, 273, 3287, 18, 11437, 31, 203, 565, 1147, 273, 394, 5420, 9535, 12, 529, 16, 3273, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.3; import './ICerticolCA.sol'; import './ICerticolDAOToken.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity/contracts/token/ERC20/IERC20.sol'; import 'openzeppelin-solidity/contracts/token/ERC777/IERC777Recipient.sol'; import 'openzeppelin-solidity/contracts/introspection/IERC1820Registry.sol'; /** * @title Certicol DAO Contract * * @author Ken Sze <[email protected]> * * @notice This contracts defines the Certicol DAO as specified in the Certicol protocol. * * @dev This token contract obeys the ERC-1820 standard and uses Orcalize. */ contract CerticolDAO is IERC777Recipient { /// Use safe math using SafeMath for uint256; /// Struct definition struct CerticolDAOVoC { uint256 blockIssue; uint256 tokenStaked; } /// ERC-1820 registry IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); /// ERC-777 interface hash for receiving tokens as a contract bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777TokensRecipient") /// CDT token interface that includes the mintInterest function ICerticolDAOToken private _CDT; /// ERC-20 interface of the CDT token IERC20 private _CDT_ERC20; /// Ownable interface of the CDT token Ownable private _CDT_Ownable; /// CerticolCA interface ICerticolCA private _CA; /// Mapping from address to tokens locked mapping(address => uint256) private _tokensLocked; /// Mapping from address to their voting rights /// Voting rights is automatically granted once the DAO received the tokens, /// but can also be delegated to another address mapping(address => uint256) private _votingRights; /// Mapping from address to their available PoSaT credit /// Similar to voting rights, PoSaT credit is automatically granted /// PoSaT credit can be consumed by either participating the PoSaT mechanism, /// thus locking the credit, or by delegating them to another address mapping(address => uint256) private _availablePoSaT; /// Mapping from address to their locked PoSaT credit, due to participation /// in the PoSaT mechanism /// It should be noted that delegation would NOT increase _lockedPoSaT, and /// the query on the net PoSaT credits an address have (available + delegated) /// should be done by getAvailablePoSaT() + getNetDelegatedPoSaT() mapping(address => uint256) private _lockedPoSaT; /// Cumulative tokens locked uint256 private _cumulativeTokenLocked = 0; /// Mapping from address to each delegated address and the amount of voting rights delegated mapping(address => mapping(address => uint256)) private _delegatedVotingRights; /// Mapping from address to the NET delegated voting rights to avoid secondary delegation mapping(address => uint256) private _delegatedNetVotingRights; /// Mapping from address to each delegated address and the amount of PoSaT credits delegated mapping(address => mapping(address => uint256)) private _delegatedPoSaT; /// Mapping from address to the NET delegated PoSaT credits to avoid secondary delegation mapping(address => uint256) private _delegatedNetPoSaT; /// CDT token requirement for granting O10 authorization, designated to be 10% of initial token supply uint256 private _O10Requirement; /// Mapping from address to their O10 authorization status and the amount of tokens locked mapping(address => uint256) private _O10Authorization; /// CDT token requirement for O10 vote of confidence (10,000 CDT) uint256 private _vocRequirement = uint256(10000).mul(uint256(10**18)); /// Mapping from O10 authorized address to total number of active PoSaT VoC records they have given out mapping(address => uint256) private _vocCount; /// Mapping from O10 authorized address to adress that they have voted confidence mapping(address => mapping(address => CerticolDAOVoC)) private _vocRecords; /// Reverse mappng from address being voted to an array of O10 authorized address that has voted confidence toward it mapping(address => address[]) private _vocReverseRecords; /// Proof-of-Stake-as-Trust reward ratio (5% p.a. as default) uint256 private _posatRewardRatio = 5; /// Proof-of-Stake-as-Trust reward block requirement (roughly 1 year as default) uint256 internal _posatRewardRequirement = 2102400; /// Cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status uint256 private _ringOneRequirement = 25; // Mapping that stored all used one-time seed used in previous O5 command to prevent reuse of those signatures mapping(uint256 => bool) private _usedOneTimeSeeds; /// Boolean that store whether this DAO is currently active bool private _DAODissolved = false; // Mapping that stored record of vote of confidence issued by O5 command mapping(address => bool) private _O5VoteNoConfidence; /// Event that will be emitted when tokens are received and locked within this contract event TokensLocked(address indexed tokenHolder, uint256 amount); /// Event that will be emitted when locked tokens are withdrawl event TokensUnlocked(address indexed tokenHolder, uint256 amount); /// Event that will be emitted upon delegation of voting rights event VotingRightsDelegation(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event that will be emitted upon the withdrawl of delegated voting rights event VotingRightsDelegationWithdrawl(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event that will be emitted upon delegation of free PoSaT credits event PoSaTDelegation(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event that will be emitted upon the withdrawl of delegated PoSaT credits event PoSaTDelegationWithdrawl(address indexed tokenHolder, address indexed delegate, uint256 amount); /// Event emitted when O10 authorization is given out event O10Authorized(address indexed O10, uint256 PoSaTLocked); /// Event emitted when O10 authotization is revoked event O10Deauthorized(address indexed O10, uint256 PoSaTUnlocked); /// Event emitted when O10 voted confidence event O10VotedConfidence(address indexed O10, address indexed target, uint256 PoSaTLocked); /// Event emitted when O10 was granted reward for PoSaT event O10RewardGranted(address indexed O10, uint256 reward); /// Event emitted when O10 revoke the vote of confidence event O10RevokeVoteConfidence(address indexed O10, address indexed target, uint256 PoSaTUnlocked); /// Event emitted when O5 is authorized event O5Authorized(string indexed functionSignatureIndex, string functionSignature, address[5] O5, uint256 cumulativeVote); /// Event emitted when O5 amends the cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status event O5AmendRingOneRequirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the PoSaT reward requirement event O5AmendPoSaTRewardRequirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the Proof-of-Stake-as-Trust reward ratio event O5AmendPoSaTReward(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the CDT token requirement for O10 vote of confidence event O5AmendVoCRequirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 amends the CDT token requirement for granting O10 authorization event O5AmendO10Requirement(uint256 effectiveFrom, uint256 amended); /// Event emitted when O5 dissolve this DAO event O5DissolvedDAO(uint256 effectiveFrom); /// Event emitted when O5 voted no confidence toward target event O5VotedNoConfidence(address indexed target); /** * @notice Initialize the CerticolDAO contract * @param tokenAddress address the address of the deployed CerticolDAOToken contract * @param caAddress address the address of the deployed CerticolCA contract */ constructor(address tokenAddress, address caAddress) public { // Register ERC-777 RECIPIENT_INTERFACE at ERC-1820 registry _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); // Initialize CDT token interface _CDT = ICerticolDAOToken(tokenAddress); _CDT_ERC20 = IERC20(tokenAddress); _CDT_Ownable = Ownable(tokenAddress); // Initialize O10 requirements _O10Requirement = _CDT_ERC20.totalSupply().div(10); // Initialize CerticolCA interface _CA = ICerticolCA(caAddress); } /** * @notice Get the number of tokens locked for holder * @param holder address the address queried * @return uint256 the number of tokens locked */ function getTokensLocked(address holder) public view returns (uint256) { return _tokensLocked[holder]; } /** * @notice Get the voting rights owned by holder * @param holder address the address queried * @return uint256 the number of voting rights owned */ function getVotingRights(address holder) public view returns (uint256) { return _votingRights[holder]; } /** * @notice Get the available PoSaT credit owned by holder * @param holder address the address queried * @return uint256 the available PoSaT credit owned */ function getAvailablePoSaT(address holder) public view returns (uint256) { return _availablePoSaT[holder]; } /** * @notice Get the locked PoSaT credit owned by holder * @param holder address the address queried * @return uint256 the locked PoSaT credit owned */ function getLockedPoSaT(address holder) public view returns (uint256) { return _lockedPoSaT[holder]; } /** * @notice Get the net amount of token locked in this contract * @return the net amount of token locked in this contract */ function getCumulativeTokenLocked() public view returns (uint256) { return _cumulativeTokenLocked; } /** * @notice Get the amount of delegated voting rights from tokenHolder to delegate * @param tokenHolder address the address which has their tokens locked * @param delegate address the address of the delegate * @return uint256 the amount of delegated voting rights from tokenHolder to delegate */ function getDelegatedVotingRights(address tokenHolder, address delegate) public view returns (uint256) { return _delegatedVotingRights[tokenHolder][delegate]; } /** * @notice Get the net amount of delegated voting rights from tokenHolder to all delegate(s) * @param tokenHolder address the address which has their tokens locked * @return uint256 the net amount of delegated voting rights from tokenHolder to all delegate(s) */ function getNetDelegatedVotingRights(address tokenHolder) public view returns (uint256) { return _delegatedNetVotingRights[tokenHolder]; } /** * @notice Get the amount of delegated PoSaT credits from tokenHolder to delegate * @param tokenHolder address the address which has their tokens locked * @param delegate address the address of the delegate * @return uint256 tthe amount of delegated PoSaT credits from tokenHolder to delegate */ function getDelegatedPoSaT(address tokenHolder, address delegate) public view returns (uint256) { return _delegatedPoSaT[tokenHolder][delegate]; } /** * @notice Get the net amount of delegated PoSaT credits from tokenHolder to all delegate(s) * @param tokenHolder address the address which has their tokens locked * @return uint256 the net amount of delegated PoSaT credits from tokenHolder to all delegate(s) */ function getNetDelegatedPoSaT(address tokenHolder) public view returns (uint256) { return _delegatedNetPoSaT[tokenHolder]; } /** * @notice Get the amount of available PoSaT credits required for O10 authorization * @return uint256 the amount of available PoSaT credits required for O10 authorization */ function getO10Requirements() public view returns (uint256) { return _O10Requirement; } /** * @notice Get the O10 authorization status of an address * @param query address the address to be queried * @return bool true if query owns O10 authorization status and false if doesn't */ function getO10Status(address query) public view returns (bool) { return _O10Authorization[query] != 0; } /** * @notice Get the available PoSaT credits requirement for voting confidence * @return bool the available PoSaT credits requirement for voting confidence */ function getVOCRequirement() public view returns (uint256) { return _vocRequirement; } /** * @notice Get the total number of active PoSaT vote of confidence issued by the O10 member * @param O10 address the address of the O10 to be queried * @return uint256 the total number of active PoSaT vote of confidence issued by the O10 member */ function getActiveVoCIssued(address O10) public view returns (uint256) { return _vocCount[O10]; } /** * @notice Get a list of O10 that has voted confidence toward target * @param target address the address to be queried on what O10 has voted confidence on it * @return address[] list of O10 that has voted confidence toward target * @dev address(0) could be returned in the array, which is an leftover from a revoke of vote of confidence */ function getVoC(address target) public view returns (address[] memory) { return _vocReverseRecords[target]; } /** * @notice Get whether a O10 has voted confidence toward target * @param target address the address to be queried on whether O10 has voted confidence on it * @param O10 address the address of the O10 to be queried * @return bool true if O10 has voted confidence, and false if otherwise */ function getVoCFrom(address target, address O10) public view returns (bool) { return _vocRecords[O10][target].blockIssue != 0; } /** * @notice Get the current Proof-of-Stake-as-Trust reward ratio * @return uint256 the current Proof-of-Stake-as-Trust reward ratio */ function getCurrentPoSaTReward() public view returns (uint256) { return _posatRewardRatio; } /** * @notice Get the current Proof-of-Stake-as-Trust reward block requirement * @return uint256 the current Proof-of-Stake-as-Trust reward block requirement */ function getCurrentPoSaTRequirement() public view returns (uint256) { return _posatRewardRequirement; } /** * @notice Get the current cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status * @return uint256 the current cumulative PoSaT credits ratio required in O10 who have voted confidence to grant ring 1 status */ function getCurrentRingOneRequirement() public view returns (uint256) { return _ringOneRequirement; } /** * @notice Get the current ring of validation for target * @param target address the address to be queried * @return uint256 either 1, 2, 3 or 4 which corresponds to the ring of validation * @dev Ring one validation is granted if target owns a valid ring 2 status * @dev And, in addition, cumulative PoSaT credits owned by O10 who have voted confidence > _ringOneRequirement of total supply * @dev If O5 has voted no confidence toward target, only 4 would be returned */ function getCurrentRing(address target) external view returns (uint256) { // Check if O5 has voted no confidence if (_O5VoteNoConfidence[target]) { // Return 4 if O5 has voted no confidence return 4; } // Get ring 2 - 4 validation status from CerticolCA (uint256 ring,,) = _CA.getStatus(target); // Return ring 3 - 4 validation status since no further computation is required if (ring > 2) { return ring; } // Compute if target qualifies for ring 1 validation // Calculate the total PoSaT credits held by O10 who have voted confidence (inc. available and locked credits) uint256 totalTokenHeld = 0; for (uint256 i = 0; i<_vocReverseRecords[target].length; i++) { address currentO10 = _vocReverseRecords[target][i]; // Skip if current address is address(0) - leftover from revoking vote of confidence if (currentO10 != address(0)) { totalTokenHeld = totalTokenHeld.add(_availablePoSaT[currentO10]).add(_lockedPoSaT[currentO10]); } } // Validate if all O10 that has voted confidence toward target have a summation of 25% tokens locked if (totalTokenHeld.mul(100).div(_ringOneRequirement) >= _cumulativeTokenLocked) { return 1; // Ring 1 status } else { return 2; // Ring 2 status } } /** * @notice Get if the given seed was already used in a previous O5 command * @return bool true if the seed was used before, or false if otherwise */ function getSeedUsed(uint256 seed) external view returns (bool) { return _usedOneTimeSeeds[seed]; } /** * @notice Get if the current DAO has been dissolved * @return bool true if the current DAO has been dissolved, or false if otherwise */ function getDAODissolved() external view returns (bool) { return _DAODissolved; } /** * @notice Get whether O5 has voted no confidence toward target * @param target address the address to be queried * @return boolean true if O5 has voted no confidence, false if not */ function getO5VoteNoConfidence(address target) external view returns (bool) { return _O5VoteNoConfidence[target]; } /** * @notice Throws if O5 has dissolved this DAO */ modifier DAOFunctional() { // Require dissolved flag to be false require(!_DAODissolved, "CerticolDAO: this function is no longer available since O5 has dissolved this DAO"); _; } /** * @notice Implements the IERC777Recipient interface to allow this contract to receive CDT token * @dev Any inward transaction of ERC-777 other than CDT token would be reverted * @param from address token holder address * @param amount uint256 amount of tokens to transfer * @dev Reverts if O5 has dissolved the current DAO */ function tokensReceived(address, address from, address, uint256 amount, bytes calldata, bytes calldata) external DAOFunctional { // Only accept inward ERC-777 transaction if it is the CDT token require(msg.sender == address(_CDT), "CerticolDAO: we only accept CDT token"); // Modify the internal state upon receiving the tokens _tokensLocked[from] = _tokensLocked[from].add(amount); _votingRights[from] = _votingRights[from].add(amount); _availablePoSaT[from] = _availablePoSaT[from].add(amount); _cumulativeTokenLocked = _cumulativeTokenLocked.add(amount); // Emit TokensLocked event emit TokensLocked(from, amount); } /** * @notice Allow msg.sender to withdraw locked token * @dev This function will only proceeds if the msg.sender owns 1 voting rights and 1 free PoSaT credit per 1 token withdrawl, * and would otherwise reverts * @param amount uint256 amount of tokens to withdraw * @dev Reverts if O5 has dissolved the current DAO */ function withdrawToken(uint256 amount) external DAOFunctional { // Subtract amount from _votingRights and _availablePoSaT _votingRights[msg.sender] = _votingRights[msg.sender].sub(amount); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(amount); // Successfully subtracted their voting rights and PoSaT credit // Proceed with the withdrawl _tokensLocked[msg.sender] = _tokensLocked[msg.sender].sub(amount); _cumulativeTokenLocked = _cumulativeTokenLocked.sub(amount); // Emit TokensUnlocked event emit TokensUnlocked(msg.sender, amount); // Transfer token to msg.sender _CDT_ERC20.transfer(msg.sender, amount); } /** * @notice Delegate voting rights from msg.sender to a specific delegate * @dev This function will only proceeds if the msg.sender owns sufficient voting rights, * and if total voting rights delegated after operation would not exceeds the amount of tokens locked * to avoid secondary delegation * @param delegate address address of the delegate * @param amount uint256 amount of voting rights to delegate * @dev Reverts if O5 has dissolved the current DAO */ function delegateVotingRights(address delegate, uint256 amount) external DAOFunctional { // Check if total voting rights delegated after operation would exceeds the amount of tokens require( _delegatedNetVotingRights[msg.sender].add(amount) <= _tokensLocked[msg.sender], "CerticolDAO: insufficient voting rights or secondary delegation is not permitted" ); // Transfer voting rights to delegate _votingRights[msg.sender] = _votingRights[msg.sender].sub(amount); _votingRights[delegate] = _votingRights[delegate].add(amount); // Add the delegate record to _delegatedVotingRights and _delegatedNetVotingRights _delegatedVotingRights[msg.sender][delegate] = _delegatedVotingRights[msg.sender][delegate].add(amount); _delegatedNetVotingRights[msg.sender] = _delegatedNetVotingRights[msg.sender].add(amount); // Emit VotingRightsDelegation emit VotingRightsDelegation(msg.sender, delegate, amount); } /** * @notice Withdraw delegated voting rights from a specific delegate * @dev This function will reverts if amount > voting rights delegated to the delegate * @param delegate address address of the delegate * @param amount uint256 amount of delegated voting rights to withdraw from the delegate * @dev Reverts if O5 has dissolved the current DAO */ function withdrawDelegatedVotingRights(address delegate, uint256 amount) external DAOFunctional { // Reduce the amount from _delegatedVotingRights and _delegatedNetVotingRights // This will also revert if amount exceeds the voting rights initially delegated _delegatedVotingRights[msg.sender][delegate] = _delegatedVotingRights[msg.sender][delegate].sub(amount); _delegatedNetVotingRights[msg.sender] = _delegatedNetVotingRights[msg.sender].sub(amount); // Transfer voting rights back to msg.sender _votingRights[delegate] = _votingRights[delegate].sub(amount); _votingRights[msg.sender] = _votingRights[msg.sender].add(amount); // Emit VotingRightsDelegationWithdrawl emit VotingRightsDelegationWithdrawl(msg.sender, delegate, amount); } /** * @notice Delegate PoSaT credits from msg.sender to a specific delegate * @dev This function will only proceeds if the msg.sender owns sufficient FREE PoSaT credits, * and if total voting rights delegated after operation would not exceeds the amount of tokens locked * to avoid secondary delegation * @param delegate address address of the delegate * @param amount uint256 amount of voting rights to delegate * @dev Reverts if O5 has dissolved the current DAO */ function delegatePoSaT(address delegate, uint256 amount) external DAOFunctional { // Check if total PoSaT delegated after operation would exceeds the amount of tokens require( _delegatedNetPoSaT[msg.sender].add(amount) <= _tokensLocked[msg.sender], "CerticolDAO: insufficient PoSaT credits or secondary delegation is not permitted" ); // Transfer free PoSaT credits to delegate _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(amount); _availablePoSaT[delegate] = _availablePoSaT[delegate].add(amount); // Add the delegate record to _delegatedPoSaT and _delegatedNetPoSaT _delegatedPoSaT[msg.sender][delegate] = _delegatedPoSaT[msg.sender][delegate].add(amount); _delegatedNetPoSaT[msg.sender] = _delegatedNetPoSaT[msg.sender].add(amount); // Emit PoSaTDelegation emit PoSaTDelegation(msg.sender, delegate, amount); } /** * @notice Withdraw delegated PoSaT credits from a specific delegate * @dev This function will reverts if amount > PoSaT credits delegated to the delegate, * or if the delegate does not have the required FREE PoSaT credits * @param delegate address address of the delegate * @param amount uint256 amount of delegated voting rights to withdraw from the delegate * @dev Reverts if O5 has dissolved the current DAO */ function withdrawDelegatedPoSaT(address delegate, uint256 amount) external DAOFunctional { // Reduce the amount from _delegatedPoSaT and _delegatedNetPoSaT // This will also revert if amount exceeds the PoSaT credits initially delegated _delegatedPoSaT[msg.sender][delegate] = _delegatedPoSaT[msg.sender][delegate].sub(amount); _delegatedNetPoSaT[msg.sender] = _delegatedNetPoSaT[msg.sender].sub(amount); // Transfer PoSaT credits back to msg.sender // Unlike voting rights, PoSaT credits can be locked by the delegate by participating in the PoSaT mechanism // The withdrawl of delegated PoSaT credits will only work if the delegate has sufficient free PoSaT credits _availablePoSaT[delegate] = _availablePoSaT[delegate].sub(amount); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].add(amount); // Emit PoSaTDelegationWithdrawl emit PoSaTDelegationWithdrawl(msg.sender, delegate, amount); } /** * @notice Throws if msg.sender do not have O10 authorization */ modifier O10Only() { require(getO10Status(msg.sender), "CerticolDAO: msg.sender did not owned a valid O10 authorization"); _; } /** * @notice Throws if O5 has voted no confidence toward target */ modifier O5NotVotedNoConfidence(address target) { require(!_O5VoteNoConfidence[target], "CerticolDAO: O5 has voted no confidence toward the target"); _; } /** * @notice Lock _O10Requirement PoSaT credits and grants msg.sender O10 authorization * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if msg.sender does not have sufficient available PoSaT credits * @dev Reverts if msg.sender have O10 authorization already */ function O10Authorization() external DAOFunctional { // Check if msg.sender already have O10 authorization require(!getO10Status(msg.sender), "CerticolDAO: msg.sender already owned a valid O10 authorization"); // Lock _O10Requirement PoSaT credits _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(_O10Requirement); _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].add(_O10Requirement); // Grant O10 authorization _O10Authorization[msg.sender] = _O10Requirement; // Emit O10Authorized emit O10Authorized(msg.sender, _O10Requirement); } /** * @notice Revoke msg.sender O10 authorization and unlock locked PoSaT credits * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender still have active PoSaT VoC issued currently * @dev O10 can ONLY be deauthorized after all PoSaT VoC issued by msg.sender has been revoked */ function O10Deauthorization() external DAOFunctional O10Only { // Check if msg.sender still has any active PoSaT VoC require(getActiveVoCIssued(msg.sender) == 0, "CerticolDAO: msg.sender still has active PoSaT VoC"); // Unlock _O10Requirement PoSaT credits uint256 lockedCredit = _O10Authorization[msg.sender]; _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].sub(lockedCredit); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].add(lockedCredit); // Revoke O10 authorization _O10Authorization[msg.sender] = 0; // Emit O10Deauthorized emit O10Deauthorized(msg.sender, lockedCredit); } /** * @notice Lock required amounts of PoSaT credits and vote confidence toward target * @param target address the address to be voted confidence on * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if O5 has voted no confidence on target * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender have already voted confidence toward target * @dev Reverts if msg.sender do not have sufficient available PoSaT credits */ function O10VoteConfidence(address target) external DAOFunctional O5NotVotedNoConfidence(target) O10Only { // Check if msg.sender has already voted confidence toward target require(!getVoCFrom(target, msg.sender), "CerticolDAO: msg.sender has already voted confidence toward target"); // Subtract required PoSaT credits from msg.sender _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].sub(_vocRequirement); _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].add(_vocRequirement); // Adds to active PoSaT VoC _vocCount[msg.sender] = _vocCount[msg.sender].add(1); // Appends the record to VoC records _vocRecords[msg.sender][target] = CerticolDAOVoC(block.number, _vocRequirement); // Appends to reverse records as well _vocReverseRecords[target].push(msg.sender); // Emit O10VotedConfidence emit O10VotedConfidence(msg.sender, target, _vocRequirement); } /** * @notice Get PoSaT reward from a vote of confidence issued to target * @param target address the address that msg.sender have voted confidence on, and would like to get the PoSaT reward from the vote * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if O5 has voted no confidence on target * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender have not voted confidence toward target * @dev Reverts if the vote has not been sustained for a minimum of _posatRewardRequirement blocks * @dev Reverts if the target has not sustained ring 2 status from CerticolCA for a minimum of _posatRewardRequirement blocks */ function O10GetReward(address target) external DAOFunctional O5NotVotedNoConfidence(target) O10Only { // Check if msg.sender has actually voted confidence toward target require(getVoCFrom(target, msg.sender), "CerticolDAO: msg.sender has not voted confidence toward target"); // Check if the vote has sustained for _posatRewardRequirement blocks require( block.number.sub(_vocRecords[msg.sender][target].blockIssue) >= _posatRewardRequirement, "CerticolDAO: vote of confidence has not sustained long enough for reward" ); // Check if the Ring 2 validation has sustained throughout this period (,uint256 ring2IssueBlock,) = _CA.getStatus(target); require(ring2IssueBlock != 0, "CerticolDAO: target has no ring 2 status"); require( block.number.sub(ring2IssueBlock) >= _posatRewardRequirement, "CerticolDAO: ring 2 status has not sustained long enough for reward" ); // Calculate the reward to be minted (tokenStaked * _posatRewardRatio / 100) uint256 reward = _vocRecords[msg.sender][target].tokenStaked.mul(_posatRewardRatio).div(100); // Before reward is minted, increment blockIssue in CerticolDAOVoC record _vocRecords[msg.sender][target].blockIssue = _vocRecords[msg.sender][target].blockIssue.add(_posatRewardRequirement); // Emit O10RewardGranted emit O10RewardGranted(msg.sender, reward); // Mint the reward _CDT.mintInterest(msg.sender, reward); } /** * @notice Revoke vote of confidence and unlock the locked PoSaT credits * @param target address the address that msg.sender have voted confidence on, and would like to revoke the vote * @dev Reverts if O5 has dissolved the current DAO * @dev Reverts if O5 has voted no confidence on target * @dev Reverts if msg.sender do not have O10 authorization already * @dev Reverts if msg.sender have not voted confidence toward target */ function O10RevokeVote(address target) external DAOFunctional O5NotVotedNoConfidence(target) O10Only { // Check if msg.sender has actually voted confidence toward target require(getVoCFrom(target, msg.sender), "CerticolDAO: msg.sender has not voted confidence toward target"); // Delete reverse vote entry in _vocReverseRecords for (uint256 i = 0; i<_vocReverseRecords[target].length; i++) { if (_vocReverseRecords[target][i] == msg.sender) { delete _vocReverseRecords[target][i]; break; } } // Delete vote entry in _vocRecords uint256 tokenLocked = _vocRecords[msg.sender][target].tokenStaked; delete _vocRecords[msg.sender][target]; // Subtract 1 from active PoSaT VoC _vocCount[msg.sender] = _vocCount[msg.sender].sub(1); // Unlock the locked PoSaT credits _lockedPoSaT[msg.sender] = _lockedPoSaT[msg.sender].sub(tokenLocked); _availablePoSaT[msg.sender] = _availablePoSaT[msg.sender].add(tokenLocked); // Emit O10RevokeVoteConfidence emit O10RevokeVoteConfidence(msg.sender, target, tokenLocked); } /** * @notice O5 authorization check * @param fnSignature string the function signature * @param amendedValue uint256 the new PoSaT reward requirement * @param effectiveBlock uint256 the block number signed by O5 members in signature * @param oneTimeSeed uint256 an one-time seed used to prevent reuse of published signatures * @param v uint[5] v component of up to 5 signatures * @param r bytes32[5] r component of up to 5 signatures * @param s bytes32[5] s component of up to 5 signatures * @dev Reverts if effectiveBlock > block.number, which indicate the signature has already expired * @dev Reverts if cumulative voting rights in all signatures did not exceeds 50% of all voting rights */ modifier O5Only( string memory fnSignature, uint256 amendedValue, uint256 effectiveBlock, uint256 oneTimeSeed, uint8[5] memory v, bytes32[5] memory r, bytes32[5] memory s ) { // Check if signature would still be valid (i.e. effectiveBlock > block.number) require(effectiveBlock > block.number, "CerticolDAO: signature has expired"); // Check if oneTimeSeed was used in the past require(!_usedOneTimeSeeds[oneTimeSeed], "CerticolDAO: the seed was already used"); // Ethereum signature prefix bytes memory prefix = "\x19Ethereum Signed Message:\n32"; // Expected message to be signed would be sha3(fnSignature, amendedValue, effectiveBlock, oneTimeSeed) bytes32 expectedMessage = keccak256(abi.encodePacked(fnSignature, amendedValue, effectiveBlock, oneTimeSeed)); // Expected actual hash signed to be sha3(prefix, message) bytes32 expectedHash = keccak256(abi.encodePacked(prefix, expectedMessage)); // List of O5s that have voted this authorization address[5] memory O5s; // Cumulative voting rights that has signed the message uint256 netVotingRights = 0; // Loop through v, r, s arrays to recover signing address and sum their voting right for (uint256 i = 0; i<5; i++) { // Extract address of the voter address O5 = ecrecover(expectedHash, v[i], r[i], s[i]); // Ensure no repeated signature is submitted for (uint256 j = 0; j < i; j++) { if (O5 == O5s[j]) { // Repeated signature found, reset O5 to address(0) as no processing is required O5 = address(0); break; } } // Process only if O5 is not address(0) if (O5 != address(0)) { // Record to the list of O5s O5s[i] = O5; // Adds to cumulative voting rights netVotingRights = netVotingRights.add(_votingRights[O5]); } } // Check if cumulative voting rights exceeds 50% of total voting rights require( netVotingRights >= _cumulativeTokenLocked.div(2), "CerticolDAO: cumulative voting rights did not exceeds 50% of total voting rights" ); // Updated used seed mapping _usedOneTimeSeeds[oneTimeSeed] = true; // Emit O5Authorized emit O5Authorized(fnSignature, fnSignature, O5s, netVotingRights); // Proceed if true _; } /** * @notice O5 command to modify CerticolDAO variables * @param effectiveBlock uint256 the block number signed by O5 members in signature * @param oneTimeSeed uint256 an one-time seed used to prevent reuse of published signatures * @param v uint[5] v component of up to 5 signatures * @param r bytes32[5] r component of up to 5 signatures * @param s bytes32[5] s component of up to 5 signatures * @param fnSignature string O5 command string * @param amendedValue uint256 the new ring one requirement * @dev Reverts if O5 check failed */ function O5Command( uint256 effectiveBlock, uint256 oneTimeSeed, uint8[5] calldata v, bytes32[5] calldata r, bytes32[5] calldata s, string calldata fnSignature, uint256 amendedValue ) external O5Only(fnSignature, amendedValue, effectiveBlock, oneTimeSeed, v, r, s) { bytes32 fnSignatureHash = keccak256(abi.encodePacked(fnSignature)); if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyRingOneRequirement"))) { // Change the ring one requirement _ringOneRequirement = amendedValue; // Emit O5AmendRingOneRequirement emit O5AmendRingOneRequirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyPoSaTRequirement"))) { // Change the reward requirement _posatRewardRequirement = amendedValue; // Emit O5AmendPoSaTRewardRequirement emit O5AmendPoSaTRewardRequirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyPoSaTReward"))) { // Change the PoSaT reward ratio _posatRewardRatio = amendedValue; // Emit O5AmendPoSaTReward emit O5AmendPoSaTReward(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyVoCRequirement"))) { // Change the VoC Requirement _vocRequirement = amendedValue; // Emit O5AmendVoCRequirement emit O5AmendVoCRequirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5ModifyO10Requirement"))) { // Change the O10 Requirement _O10Requirement = amendedValue; // Emit O5AmendO10Requirement emit O5AmendO10Requirement(block.number, amendedValue); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5DissolveDAO"))) { // Set dissolved falg _DAODissolved = true; // Transfer ownership of CerticolDAOToken _CDT_Ownable.transferOwnership(msg.sender); // Emit O5DissolvedDAO emit O5DissolvedDAO(block.number); } else if (fnSignatureHash == keccak256(abi.encodePacked("O5VoteNoConfidence"))) { // Cast uint256 back to address address target = address(amendedValue); // Update the _O5VoteNoConfidence mapping _O5VoteNoConfidence[target] = true; // Emit O5VotedNoConfidence emit O5VotedNoConfidence(target); } else { return; } } /** * @notice Allow the withdrawl of all token locked in this contract after O5 has dissolved this DAO * @dev Reverts if this DAO has not been dissolved */ function dissolveWithdrawl() external { // Require dissolved flag require(_DAODissolved, "CerticolDAO: this function is only available if O5 has dissolved this DAO"); // Get total amount of token locked by msg.sender uint256 tokenLocked = _tokensLocked[msg.sender]; // Reset tokensLocked mapping _tokensLocked[msg.sender] = 0; // Reduce cumulative token locked respectively _cumulativeTokenLocked = _cumulativeTokenLocked.sub(tokenLocked); // Emit TokensUnlocked emit TokensUnlocked(msg.sender, tokenLocked); // Withdraw all token locked _CDT_ERC20.transfer(msg.sender, tokenLocked); } }
* @notice Get the number of tokens locked for holder @param holder address the address queried @return uint256 the number of tokens locked/
function getTokensLocked(address holder) public view returns (uint256) { return _tokensLocked[holder]; }
13,141,378
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 968, 326, 1300, 434, 2430, 8586, 364, 10438, 632, 891, 10438, 1758, 326, 1758, 23264, 632, 2463, 2254, 5034, 326, 1300, 434, 2430, 8586, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18349, 8966, 12, 2867, 10438, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 7860, 8966, 63, 4505, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.7.6; import '@NutBerry/NutBerry/src/tsm/contracts/NutBerryEvents.sol'; // Audit-1: ok contract UpgradableRollup is NutBerryEvents { /// @notice Returns the address who is in charge of changing the rollup implementation. /// This contract should be managed by a `ExecutionProxy` that in turn verifies governance decisions /// from the rollup. /// The rollup will be managed by a multisig in the beginning until moving to community governance. /// It should be noted that there should be a emergency contract on L1 that can be used to recover from bad upgrades /// in case the rollup is malfunctioning itself. function ROLLUP_MANAGER () public virtual view returns (address) { } /// @notice Upgrades the implementation. function upgradeRollup (address newImplementation) external { require(msg.sender == ROLLUP_MANAGER()); assembly { // uint256(-1) - stores the contract address to delegate calls to (RollupProxy) sstore(not(returndatasize()), newImplementation) } emit NutBerryEvents.RollupUpgrade(newImplementation); } }
@notice Returns the address who is in charge of changing the rollup implementation. This contract should be managed by a `ExecutionProxy` that in turn verifies governance decisions from the rollup. The rollup will be managed by a multisig in the beginning until moving to community governance. It should be noted that there should be a emergency contract on L1 that can be used to recover from bad upgrades in case the rollup is malfunctioning itself.
function ROLLUP_MANAGER () public virtual view returns (address) { }
898,874
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 2860, 326, 1758, 10354, 353, 316, 13765, 434, 12770, 326, 5824, 416, 4471, 18, 1220, 6835, 1410, 506, 7016, 635, 279, 1375, 3210, 3886, 68, 716, 316, 7005, 20761, 314, 1643, 82, 1359, 2109, 12682, 628, 326, 5824, 416, 18, 1021, 5824, 416, 903, 506, 7016, 635, 279, 22945, 360, 316, 326, 8435, 3180, 12499, 358, 19833, 314, 1643, 82, 1359, 18, 2597, 1410, 506, 486, 329, 716, 1915, 1410, 506, 279, 801, 24530, 6835, 603, 511, 21, 716, 848, 506, 1399, 358, 5910, 628, 5570, 28844, 316, 648, 326, 5824, 416, 353, 27431, 915, 310, 6174, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 19402, 1832, 1071, 5024, 1476, 1135, 261, 2867, 13, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xDfc1CcDadf37195228bA39E7Ae72DeC77BCE6401/sources/contracts/AchieveMint.sol
* @dev Support meta transactions/* @dev Setup roles/* @dev Set the base URI for the metadata/* @dev Set the contract level metadata/
constructor(address _forwarder) ERC1155("") { _setTrustedForwarder(_forwarder); ADMIN_ROLE = keccak256("ADMIN_ROLE"); CREATOR_ROLE = keccak256("CREATOR_ROLE"); address sender = _msgSender(); _setupRole(DEFAULT_ADMIN_ROLE, sender); _setupRole(ADMIN_ROLE, sender); _setupRole(CREATOR_ROLE, sender); setContractURI( string( abi.encodePacked( "{", '"name": "AchieveMint",', '"description": "The blockchain solution for tokenizing achievements, enabling secure and verified recognition of accomplishments in any field",', '"seller_fee_basis_points": 500,', '"fee_recipient": "', Strings.toHexString(uint160(address(_msgSender())), 20), '"', "}" ) ) ); }
5,691,070
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 13619, 2191, 8938, 20308, 632, 5206, 10939, 4900, 20308, 632, 5206, 1000, 326, 1026, 3699, 364, 326, 1982, 20308, 632, 5206, 1000, 326, 6835, 1801, 1982, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 389, 1884, 20099, 13, 4232, 39, 2499, 2539, 2932, 7923, 288, 203, 540, 389, 542, 16950, 30839, 24899, 1884, 20099, 1769, 203, 3639, 25969, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 15468, 67, 16256, 8863, 203, 3639, 9666, 3575, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 5458, 3575, 67, 16256, 8863, 203, 3639, 1758, 5793, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 5793, 1769, 203, 3639, 389, 8401, 2996, 12, 15468, 67, 16256, 16, 5793, 1769, 203, 3639, 389, 8401, 2996, 12, 5458, 3575, 67, 16256, 16, 5793, 1769, 203, 3639, 444, 8924, 3098, 12, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 4144, 3113, 203, 10792, 2119, 529, 6877, 315, 37, 17384, 537, 49, 474, 3113, 2187, 203, 10792, 2119, 3384, 6877, 315, 1986, 16766, 6959, 364, 1147, 6894, 20186, 90, 17110, 16, 570, 17912, 8177, 471, 13808, 1950, 7909, 434, 28217, 412, 1468, 1346, 316, 1281, 652, 3113, 2187, 203, 10792, 2119, 1786, 749, 67, 21386, 67, 23774, 67, 4139, 6877, 6604, 16, 2187, 203, 10792, 2119, 21386, 67, 20367, 6877, 14912, 203, 10792, 8139, 18, 869, 14866, 12, 11890, 16874, 12, 2867, 24899, 3576, 12021, 10756, 3631, 4200, 3631, 203, 10792, 2119, 2187, 203, 10792, 11883, 203, 7734, 262, 203, 5411, 262, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // Slightly modified Zeppelin&#39;s Vested Token deriving MiniMeToken /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ contract Controlled { address public controller; function Controlled() { controller = msg.sender; } /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract&#39;s goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO&#39;s /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token&#39;s name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { Transfer(_from, _to, _amount); // Follow the spec to issue the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); } /// @param _owner The address that&#39;s balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint256 _amount ) onlyController returns (bool) { uint256 curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint256 previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) internal view returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract&#39;s controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Jorge Izquierdo (Aragon Foundation) * * Based on VestedToken.sol from https://github.com/OpenZeppelin/zeppelin-solidity * * Math – Copyright (c) 2016 Smart Contract Solutions, Inc. * SafeMath – Copyright (c) 2016 Smart Contract Solutions, Inc. * MiniMeToken – Copyright 2017, Jordi Baylina (Giveth) **/ // @dev MiniMeIrrevocableVestedToken is a derived version of MiniMeToken adding the // ability to createTokenGrants which are basically a transfer that limits the // receiver of the tokens how can he spend them over time. // For simplicity, token grants are not saved in MiniMe type checkpoints. // Vanilla cloning ESCBCoin will clone it into a MiniMeToken without vesting. // More complex cloning could account for past vesting calendars. contract MiniMeIrrevocableVestedToken is MiniMeToken { using SafeMath for uint256; uint256 MAX_GRANTS_PER_ADDRESS = 20; // Keep the struct at 2 stores (1 slot for value + 64 * 3 (dates) + 20 (address) = 2 slots // (2nd slot is 212 bytes, lower than 256)) struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint64 start, uint64 cliff, uint64 vesting, uint256 grantId); mapping (address => bool) canCreateGrants; address vestingWhitelister; modifier canTransfer(address _sender, uint _value) { require(_value <= spendableBalanceOf(_sender)); _; } modifier onlyVestingWhitelister { require(msg.sender == vestingWhitelister); _; } function MiniMeIrrevocableVestedToken ( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public MiniMeToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) { vestingWhitelister = msg.sender; doSetCanCreateGrants(vestingWhitelister, true); } // @dev Add canTransfer modifier before allowing transfer and transferFrom to go through function transfer(address _to, uint _value) canTransfer(msg.sender, _value) public returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) public returns (bool success) { return super.transferFrom(_from, _to, _value); } function spendableBalanceOf(address _holder) constant public returns (uint) { return transferableTokens(_holder, uint64(now)); } /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. * @param _revokable bool Token can be revoked with send amount to back. * @param _burnsOnRevoke bool Token can be revoked with send amount to back and destroyed. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior require(_cliff >= _start && _vesting >= _cliff); require(canCreateGrants[msg.sender]); require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint256 count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, _cliff, _vesting, _start, count - 1); } function setCanCreateGrants(address _addr, bool _allowed) onlyVestingWhitelister public { doSetCanCreateGrants(_addr, _allowed); } function doSetCanCreateGrants(address _addr, bool _allowed) internal { canCreateGrants[_addr] = _allowed; } function changeVestingWhitelister(address _newWhitelister) onlyVestingWhitelister public { doSetCanCreateGrants(vestingWhitelister, false); vestingWhitelister = _newWhitelister; doSetCanCreateGrants(vestingWhitelister, true); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint256 _grantId) public { TokenGrant storage grant = grants[_holder][_grantId]; require(grant.revokable); require(grant.granter == msg.sender); // Only granter can revoke it address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; var previousBalanceReceiver = balanceOfAt(receiver, block.number); //balances[receiver] = balances[receiver].add(nonVested); updateValueAtNow(balances[receiver], previousBalanceReceiver + nonVested); var previousBalance_holder = balanceOfAt(_holder, block.number); //balances[_holder] = balances[_holder].sub(nonVested); updateValueAtNow(balances[_holder], previousBalance_holder - nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint256 representing a holder&#39;s total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) public view returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return Math.min256(vestedTransferable, balanceOf(holder)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint256 representing the total amount of grants. */ function tokenGrantsCount(address _holder) public view returns (uint256 index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint256 representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) internal view returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above&#39;s figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = SafeMath.div( SafeMath.mul( tokens, SafeMath.sub(time, start) ), SafeMath.sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint256 _grantId) public view returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint256 representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { // Of all the tokens of the grant, how many of them are not vested? // grantValue - vestedTokens return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint256 representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = Math.max64(grants[holder][i].vesting, date); } } } /** * Dividends * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Adam Dossa * Based on ProfitSharingContract.sol from https://github.com/adamdossa/ProfitSharingContract **/ contract MiniMeIrrVesDivToken is MiniMeIrrevocableVestedToken { event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim); event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); uint256 public RECYCLE_TIME = 1 years; function MiniMeIrrVesDivToken ( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public MiniMeIrrevocableVestedToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) {} struct Dividend { uint256 blockNumber; uint256 timestamp; uint256 amount; uint256 claimedAmount; uint256 totalSupply; bool recycled; mapping (address => bool) claimed; } Dividend[] public dividends; mapping (address => uint256) dividendsClaimed; modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length); _; } function depositDividend() public payable onlyController { uint256 currentSupply = super.totalSupplyAt(block.number); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), msg.value, 0, currentSupply, false ) ); DividendDeposited(msg.sender, blockNumber, getNow(), msg.value, currentSupply, dividendIndex); } function claimDividend(uint256 _dividendIndex) public validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(dividend.claimed[msg.sender] == false); require(dividend.recycled == false); uint256 balance = super.balanceOfAt(msg.sender, dividend.blockNumber); uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply); dividend.claimed[msg.sender] = true; dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim); if (claim > 0) { msg.sender.transfer(claim); DividendClaimed(msg.sender, _dividendIndex, claim); } } function claimDividendAll() public { require(dividendsClaimed[msg.sender] < dividends.length); for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) { if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) { dividendsClaimed[msg.sender] = SafeMath.add(i, 1); claimDividend(i); } } } function recycleDividend(uint256 _dividendIndex) public onlyController validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(dividend.recycled == false); require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME)); dividends[_dividendIndex].recycled = true; uint256 currentSupply = super.totalSupplyAt(block.number); uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), remainingAmount, 0, currentSupply, false ) ); DividendRecycled(msg.sender, blockNumber, getNow(), remainingAmount, currentSupply, dividendIndex); } function getNow() internal constant returns (uint256) { return now; } } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) **/ contract ESCBCoin is MiniMeIrrVesDivToken { // @dev ESCBCoin constructor just parametrizes the MiniMeIrrVesDivToken constructor function ESCBCoin ( address _tokenFactory ) public MiniMeIrrVesDivToken( _tokenFactory, 0x0, // no parent token 0, // no snapshot block number from parent "ESCB token", // Token name 18, // Decimals "ESCB", // Symbol true // Enable transfers ) {} } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Jorge Izquierdo (Aragon Foundation) **/ /* @notice The ESCBCoinPlaceholder contract will take control over the ESCB coin after the sale is finalized and before the EscrowBlock Network is deployed. The contract allows for ESCBCoin transfers and transferFrom and implements the logic for transfering control of the token to the network when the sale asks it to do so. */ contract ESCBCoinPlaceholder is TokenController { address public tokenSale; ESCBCoin public token; function ESCBCoinPlaceholder(address _sale, address _ESCBCoin) public { tokenSale = _sale; token = ESCBCoin(_ESCBCoin); } function changeController(address network) public { assert(msg.sender == tokenSale); token.changeController(network); selfdestruct(network); // network gets all amount } // In between the sale and the network. Default settings for allowing token transfers. function proxyPayment(address _owner) public payable returns (bool) { revert(); return false; } function onTransfer(address _from, address _to, uint _amount) public returns (bool) { return true; } function onApprove(address _owner, address _spender, uint _amount) public returns (bool) { return true; } } // @dev Contract to hold sale raised funds during the sale period. // Prevents attack in which the ESCB Multisig sends raised ether // to the sale contract to mint tokens to itself, and getting the // funds back immediately. contract AbstractSale { function saleFinalized() public returns (bool); function minGoalReached() public returns (bool); } contract SaleWallet { using SafeMath for uint256; enum State { Active, Refunding } State public currentState; mapping (address => uint256) public deposited; //Events event Withdrawal(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); event Deposit(address beneficiary, uint256 weiAmount); // Public variables address public multisig; AbstractSale public tokenSale; // @dev Constructor initializes public variables // @param _multisig The address of the multisig that will receive the funds // @param _tokenSale The address of the token sale function SaleWallet(address _multisig, address _tokenSale) { currentState = State.Active; multisig = _multisig; tokenSale = AbstractSale(_tokenSale); } // @dev Receive all sent funds and build the refund map function deposit(address investor, uint256 amount) public { require(currentState == State.Active); require(msg.sender == address(tokenSale)); deposited[investor] = deposited[investor].add(amount); Deposit(investor, amount); } // @dev Withdraw function sends all the funds to the wallet if conditions are correct function withdraw() public { require(currentState == State.Active); assert(msg.sender == multisig); // Only the multisig can request it if (tokenSale.minGoalReached()) { // Allow when sale reached minimum goal return doWithdraw(); } } function doWithdraw() internal { assert(multisig.send(this.balance)); Withdrawal(); } function enableRefunds() public { require(currentState == State.Active); assert(msg.sender == multisig); // Only the multisig can request it require(!tokenSale.minGoalReached()); // Allow when minimum goal isn&#39;t reached require(tokenSale.saleFinalized()); // Allow when sale is finalized currentState = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(currentState == State.Refunding); require(msg.sender == address(tokenSale)); require(deposited[investor] != 0); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; assert(investor.send(depositedValue)); Refunded(investor, depositedValue); } // @dev Receive all sent funds function () public payable {} } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Jorge Izquierdo (Aragon Foundation) * Copyright 2017, Jordi Baylina (Giveth) * * Based on SampleCampaign-TokenController.sol from https://github.com/Giveth/minime * This is the new token sale smart contract for conduction IITO and Airdrop together, * also it will allow having a stable price for some period after exchange listing. **/ contract ESCBTokenSale is TokenController { uint256 public initialTime; // Time in which the sale starts. Inclusive. sale will be opened at initial time. uint256 public controlTime; // The Unix time in which the sale needs to check on the refunding start. uint256 public price; // Number of wei-ESCBCoin tokens for 1 ether address public ESCBDevMultisig; // The address to hold the funds donated uint256 public affiliateBonusPercent = 2; // Purpose in percentage of payment via referral uint256 public totalCollected = 0; // In wei bool public saleStopped = false; // Has ESCB Dev stopped the sale? bool public saleFinalized = false; // Has ESCB Dev finalized the sale? mapping (address => bool) public activated; // Address confirmates that wants to activate the sale ESCBCoin public token; // The token ESCBCoinPlaceholder public networkPlaceholder; // The network placeholder SaleWallet public saleWallet; // Wallet that receives all sale funds uint256 constant public dust = 1 finney; // Minimum investment uint256 public minGoal; // amount of minimum fund in wei uint256 public goal; // Goal for IITO in wei uint256 public currentStage = 1; // Current stage uint256 public allocatedStage = 1; // Current stage when was allocated tokens for ESCB uint256 public usedTotalSupply = 0; // This uses for calculation ESCB allocation part event ActivatedSale(); event FinalizedSale(); event NewBuyer(address indexed holder, uint256 ESCBCoinAmount, uint256 etherAmount); event NewExternalFoundation(address indexed holder, uint256 ESCBCoinAmount, uint256 etherAmount, bytes32 externalId); event AllocationForESCBFund(address indexed holder, uint256 ESCBCoinAmount); event NewStage(uint64 numberStage); // @dev There are several checks to make sure the parameters are acceptable // @param _initialTime The Unix time in which the sale starts // @param _controlTime The Unix time in which the sale needs to check on the refunding start // @param _ESCBDevMultisig The address that will store the donated funds and manager for the sale // @param _price The price. Price in wei-ESCBCoin per wei function ESCBTokenSale (uint _initialTime, uint _controlTime, address _ESCBDevMultisig, uint256 _price) non_zero_address(_ESCBDevMultisig) { assert (_initialTime >= getNow()); assert (_initialTime < _controlTime); // Save constructor arguments as global variables initialTime = _initialTime; controlTime = _controlTime; ESCBDevMultisig = _ESCBDevMultisig; price = _price; } modifier only(address x) { require(msg.sender == x); _; } modifier only_before_sale { require(getNow() < initialTime); _; } modifier only_during_sale_period { require(getNow() >= initialTime); // if minimum goal is reached, then infinite time to reach the main goal require(getNow() < controlTime || minGoalReached()); _; } modifier only_after_sale { require(getNow() >= controlTime || goalReached()); _; } modifier only_sale_stopped { require(saleStopped); _; } modifier only_sale_not_stopped { require(!saleStopped); _; } modifier only_before_sale_activation { require(!isActivated()); _; } modifier only_sale_activated { require(isActivated()); _; } modifier only_finalized_sale { require(getNow() >= controlTime || goalReached()); require(saleFinalized); _; } modifier non_zero_address(address x) { require(x != 0); _; } modifier minimum_value(uint256 x) { require(msg.value >= x); _; } // @notice Deploy ESCBCoin is called only once to setup all the needed contracts. // @param _token: Address of an instance of the ESCBCoin token // @param _networkPlaceholder: Address of an instance of ESCBCoinPlaceholder // @param _saleWallet: Address of the wallet receiving the funds of the sale // @param _minGoal: Minimum fund for success // @param _goal: The end fund amount function setESCBCoin(address _token, address _networkPlaceholder, address _saleWallet, uint256 _minGoal, uint256 _goal) payable non_zero_address(_token) only(ESCBDevMultisig) public { // 3 times by non_zero_address is not working for current compiler version require(_networkPlaceholder != 0); require(_saleWallet != 0); // Assert that the function hasn&#39;t been called before, as activate will happen at the end assert(!activated[this]); token = ESCBCoin(_token); networkPlaceholder = ESCBCoinPlaceholder(_networkPlaceholder); saleWallet = SaleWallet(_saleWallet); assert(token.controller() == address(this)); // sale is controller assert(token.totalSupply() == 0); // token is empty assert(networkPlaceholder.tokenSale() == address(this)); // placeholder has reference to Sale assert(networkPlaceholder.token() == address(token)); // placeholder has reference to ESCBCoin assert(saleWallet.multisig() == ESCBDevMultisig); // receiving wallet must match assert(saleWallet.tokenSale() == address(this)); // watched token sale must be self assert(_minGoal > 0); // minimum goal is not empty assert(_goal > 0); // the main goal is not empty assert(_minGoal < _goal); // minimum goal is less than the main goal minGoal = _minGoal; goal = _goal; // Contract activates sale as all requirements are ready doActivateSale(this); } function activateSale() public { doActivateSale(msg.sender); ActivatedSale(); } function doActivateSale(address _entity) non_zero_address(token) // cannot activate before setting token only_before_sale private { activated[_entity] = true; } // @notice Whether the needed accounts have activated the sale. // @return Is sale activated function isActivated() constant public returns (bool) { return activated[this] && activated[ESCBDevMultisig]; } // @notice Get the price for tokens for the current stage // @param _amount the amount for which the price is requested // @return Number of wei-ESCBToken function getPrice(uint256 _amount) only_during_sale_period only_sale_not_stopped only_sale_activated constant public returns (uint256) { return priceForStage(SafeMath.mul(_amount, price)); } // @notice Get the bonus tokens for a stage // @param _amount the amount of tokens // @return Number of wei-ESCBCoin with bonus for 1 wei function priceForStage(uint256 _amount) internal returns (uint256) { if (totalCollected >= 0 && totalCollected <= 80 ether) { // 1 ETH = 500 USD, then 40 000 USD 1 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 20), 100)); } if (totalCollected > 80 ether && totalCollected <= 200 ether) { // 1 ETH = 500 USD, then 100 000 USD 2 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 18), 100)); } if (totalCollected > 200 ether && totalCollected <= 400 ether) { // 1 ETH = 500 USD, then 200 000 USD 3 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 16), 100)); } if (totalCollected > 400 ether && totalCollected <= 1000 ether) { // 1 ETH = 500 USD, then 500 000 USD 4 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 14), 100)); } if (totalCollected > 1000 ether && totalCollected <= 2000 ether) { // 1 ETH = 500 USD, then 1 000 000 USD 5 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 12), 100)); } if (totalCollected > 2000 ether && totalCollected <= 4000 ether) { // 1 ETH = 500 USD, then 2 000 000 USD 6 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 10), 100)); } if (totalCollected > 4000 ether && totalCollected <= 8000 ether) { // 1 ETH = 500 USD, then 4 000 000 USD 7 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 8), 100)); } if (totalCollected > 8000 ether && totalCollected <= 12000 ether) { // 1 ETH = 500 USD, then 6 000 000 USD 8 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 6), 100)); } if (totalCollected > 12000 ether && totalCollected <= 16000 ether) { // 1 ETH = 500 USD, then 8 000 000 USD 9 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 4), 100)); } if (totalCollected > 16000 ether && totalCollected <= 20000 ether) { // 1 ETH = 500 USD, then 10 000 000 USD 10 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 2), 100)); } if (totalCollected > 20000 ether) { // without bonus return _amount; } } // ESCBDevMultisig can use this function for allocation tokens // for ESCB Foundation by each stage, start from 2nd // Amount of stages can not be more than MAX_GRANTS_PER_ADDRESS function allocationForESCBbyStage() only(ESCBDevMultisig) public { if (totalCollected >= 0 && totalCollected <= 80 ether) { // 1 ETH = 500 USD, then 40 000 USD 1 stage currentStage = 1; } if (totalCollected > 80 ether && totalCollected <= 200 ether) { // 1 ETH = 500 USD, then 100 000 USD 2 stage currentStage = 2; } if (totalCollected > 200 ether && totalCollected <= 400 ether) { // 1 ETH = 500 USD, then 200 000 USD 3 stage currentStage = 3; } if (totalCollected > 400 ether && totalCollected <= 1000 ether) { // 1 ETH = 500 USD, then 500 000 USD 4 stage currentStage = 4; } if (totalCollected > 1000 ether && totalCollected <= 2000 ether) { // 1 ETH = 500 USD, then 1 000 000 USD 5 stage currentStage = 5; } if (totalCollected > 2000 ether && totalCollected <= 4000 ether) { // 1 ETH = 500 USD, then 2 000 000 USD 6 stage currentStage = 6; } if (totalCollected > 4000 ether && totalCollected <= 8000 ether) { // 1 ETH = 500 USD, then 4 000 000 USD 7 stage currentStage = 7; } if (totalCollected > 8000 ether && totalCollected <= 12000 ether) { // 1 ETH = 500 USD, then 6 000 000 USD 8 stage currentStage = 8; } if (totalCollected > 12000 ether && totalCollected <= 16000 ether) { // 1 ETH = 500 USD, then 8 000 000 USD 9 stage currentStage = 9; } if (totalCollected > 16000 ether && totalCollected <= 20000 ether) { // 1 ETH = 500 USD, then 10 000 000 USD 10 stage currentStage = 10; } if(currentStage > allocatedStage) { // ESCB Foundation owns 30% of the total number of emitted tokens. // totalSupply here 66%, then we 30%/66% to get amount 30% of tokens uint256 ESCBTokens = SafeMath.div(SafeMath.mul(SafeMath.sub(uint256(token.totalSupply()), usedTotalSupply), 15), 33); uint256 prevTotalSupply = uint256(token.totalSupply()); if(token.generateTokens(address(this), ESCBTokens)) { allocatedStage = currentStage; usedTotalSupply = prevTotalSupply; uint64 cliffDate = uint64(SafeMath.add(uint256(now), 365 days)); uint64 vestingDate = uint64(SafeMath.add(uint256(now), 547 days)); token.grantVestedTokens(ESCBDevMultisig, ESCBTokens, uint64(now), cliffDate, vestingDate, true, false); AllocationForESCBFund(ESCBDevMultisig, ESCBTokens); } else { revert(); } } } // @notice Notifies the controller about a transfer, for this sale all // transfers are allowed by default and no extra notifications are needed // @param _from The origin of the transfer // @param _to The destination of the transfer // @param _amount The amount of the transfer // @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns (bool) { return true; } // @notice Notifies the controller about an approval, for this sale all // approvals are allowed by default and no extra notifications are needed // @param _owner The address that calls `approve()` // @param _spender The spender in the `approve()` call // @param _amount The amount in the `approve()` call // @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns (bool) { return true; } // @dev The fallback function is called when ether is sent to the contract, it // simply calls `doPayment()` with the address that sent the ether as the // `_owner`. Payable is a require solidity modifier for functions to receive // ether, without this modifier functions will throw if ether is sent to them function () public payable { doPayment(msg.sender); } // @dev This function allow to get bonus tokens for a buyer and for referral function paymentAffiliate(address _referral) non_zero_address(_referral) payable public { uint256 boughtTokens = doPayment(msg.sender); uint256 affiliateBonus = SafeMath.div( SafeMath.mul(boughtTokens, affiliateBonusPercent), 100 ); // Calculate how many bonus tokens need to add assert(token.generateTokens(_referral, affiliateBonus)); assert(token.generateTokens(msg.sender, affiliateBonus)); } //////////// // Controller interface //////////// // @notice `proxyPayment()` allows the caller to send ether to the Token directly and // have the tokens created in an address of their choosing // @param _owner The address that will hold the newly created tokens function proxyPayment(address _owner) payable public returns (bool) { doPayment(_owner); return true; } // @dev `doPayment()` is an internal function that sends the ether that this // contract receives to the ESCBDevMultisig and creates tokens in the address of the sender // @param _owner The address that will hold the newly created tokens function doPayment(address _owner) only_during_sale_period only_sale_not_stopped only_sale_activated non_zero_address(_owner) minimum_value(dust) internal returns (uint256) { assert(totalCollected + msg.value <= goal); // If goal is reached, throw uint256 boughtTokens = priceForStage(SafeMath.mul(msg.value, price)); // Calculate how many tokens bought saleWallet.transfer(msg.value); // Send funds to multisig saleWallet.deposit(_owner, msg.value); // Send info about deposit to multisig assert(token.generateTokens(_owner, boughtTokens)); // Allocate tokens. totalCollected = SafeMath.add(totalCollected, msg.value); // Save total collected amount NewBuyer(_owner, boughtTokens, msg.value); return boughtTokens; } // @notice Function for issuing new tokens for address which made purchasing not in // ETH currency, for example via cards or wire transfer. // @dev Only ESCB Dev can do it with the publishing of transaction id in an external system. // Any audits will be able to confirm eligibility of issuing in such case. // @param _owner The address that will hold the newly created tokens // @param _amount Amount of purchasing in ETH function issueWithExternalFoundation(address _owner, uint256 _amount, bytes32 _extId) only_during_sale_period only_sale_not_stopped only_sale_activated non_zero_address(_owner) only(ESCBDevMultisig) public returns (uint256) { assert(totalCollected + _amount <= goal); // If goal is reached, throw uint256 boughtTokens = priceForStage(SafeMath.mul(_amount, price)); // Calculate how many tokens bought assert(token.generateTokens(_owner, boughtTokens)); // Allocate tokens. totalCollected = SafeMath.add(totalCollected, _amount); // Save total collected amount // Events NewBuyer(_owner, boughtTokens, _amount); NewExternalFoundation(_owner, boughtTokens, _amount, _extId); return boughtTokens; } // @notice Function to stop sale for an emergency. // @dev Only ESCB Dev can do it after it has been activated. function emergencyStopSale() only_sale_activated only_sale_not_stopped only(ESCBDevMultisig) public { saleStopped = true; } // @notice Function to restart stopped sale. // @dev Only ESCB Dev can do it after it has been disabled and sale is ongoing. function restartSale() only_during_sale_period only_sale_stopped only(ESCBDevMultisig) public { saleStopped = false; } // @notice Finalizes sale when main goal is reached or if for control time the minimum goal was not reached. // @dev Transfers the token controller power to the ESCBCoinPlaceholder. function finalizeSale() only_after_sale only(ESCBDevMultisig) public { token.changeController(networkPlaceholder); // Sale loses token controller power in favor of network placeholder saleFinalized = true; // Set finalized flag as true, that will allow enabling network deployment saleStopped = true; FinalizedSale(); } // @notice Deploy ESCB Network contract. // @param _networkAddress: The address the network was deployed at. function deployNetwork(address _networkAddress) only_finalized_sale non_zero_address(_networkAddress) only(ESCBDevMultisig) public { networkPlaceholder.changeController(_networkAddress); } // @notice Set up new ESCB Dev. // @param _newMultisig: The address new ESCB Dev. function setESCBDevMultisig(address _newMultisig) non_zero_address(_newMultisig) only(ESCBDevMultisig) public { ESCBDevMultisig = _newMultisig; } // @notice Get current unix time stamp function getNow() constant internal returns (uint) { return now; } // @notice If crowdsale is unsuccessful, investors can claim refunds here function claimRefund() only_finalized_sale public { require(!minGoalReached()); saleWallet.refund(msg.sender); } // @notice Check minimum goal for 1st stage function minGoalReached() public view returns (bool) { return totalCollected >= minGoal; } // @notice Check the main goal for 10th stage function goalReached() public view returns (bool) { return totalCollected >= goal; } }
@dev There are several checks to make sure the parameters are acceptable @param _initialTime The Unix time in which the sale starts @param _controlTime The Unix time in which the sale needs to check on the refunding start @param _ESCBDevMultisig The address that will store the donated funds and manager for the sale @param _price The price. Price in wei-ESCBCoin per wei
contract ESCBTokenSale is TokenController { event ActivatedSale(); event FinalizedSale(); event NewBuyer(address indexed holder, uint256 ESCBCoinAmount, uint256 etherAmount); event NewExternalFoundation(address indexed holder, uint256 ESCBCoinAmount, uint256 etherAmount, bytes32 externalId); event AllocationForESCBFund(address indexed holder, uint256 ESCBCoinAmount); event NewStage(uint64 numberStage); function ESCBTokenSale (uint _initialTime, uint _controlTime, address _ESCBDevMultisig, uint256 _price) non_zero_address(_ESCBDevMultisig) { assert (_initialTime >= getNow()); assert (_initialTime < _controlTime); initialTime = _initialTime; controlTime = _controlTime; ESCBDevMultisig = _ESCBDevMultisig; price = _price; } modifier only(address x) { require(msg.sender == x); _; } modifier only_before_sale { require(getNow() < initialTime); _; } modifier only_during_sale_period { require(getNow() >= initialTime); require(getNow() < controlTime || minGoalReached()); _; } modifier only_after_sale { require(getNow() >= controlTime || goalReached()); _; } modifier only_sale_stopped { require(saleStopped); _; } modifier only_sale_not_stopped { require(!saleStopped); _; } modifier only_before_sale_activation { require(!isActivated()); _; } modifier only_sale_activated { require(isActivated()); _; } modifier only_finalized_sale { require(getNow() >= controlTime || goalReached()); require(saleFinalized); _; } modifier non_zero_address(address x) { require(x != 0); _; } modifier minimum_value(uint256 x) { require(msg.value >= x); _; } function setESCBCoin(address _token, address _networkPlaceholder, address _saleWallet, uint256 _minGoal, uint256 _goal) payable non_zero_address(_token) only(ESCBDevMultisig) public { require(_networkPlaceholder != 0); require(_saleWallet != 0); assert(!activated[this]); token = ESCBCoin(_token); networkPlaceholder = ESCBCoinPlaceholder(_networkPlaceholder); saleWallet = SaleWallet(_saleWallet); minGoal = _minGoal; goal = _goal; doActivateSale(this); } function activateSale() public { doActivateSale(msg.sender); ActivatedSale(); } function doActivateSale(address _entity) only_before_sale private { activated[_entity] = true; } function isActivated() constant public returns (bool) { return activated[this] && activated[ESCBDevMultisig]; } function getPrice(uint256 _amount) only_during_sale_period only_sale_not_stopped only_sale_activated constant public returns (uint256) { return priceForStage(SafeMath.mul(_amount, price)); } function priceForStage(uint256 _amount) internal returns (uint256) { return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 20), 100)); } return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 18), 100)); }
2,303,022
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 6149, 854, 11392, 4271, 358, 1221, 3071, 326, 1472, 854, 14206, 632, 891, 389, 6769, 950, 1021, 9480, 813, 316, 1492, 326, 272, 5349, 2542, 632, 891, 389, 7098, 950, 1021, 9480, 813, 316, 1492, 326, 272, 5349, 4260, 358, 866, 603, 326, 1278, 14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, 10438, 16, 2254, 5034, 512, 2312, 16283, 885, 6275, 16, 2254, 5034, 225, 2437, 6275, 1769, 203, 282, 871, 1166, 6841, 27788, 12, 2867, 8808, 10438, 16, 2254, 5034, 512, 2312, 16283, 885, 6275, 16, 2254, 5034, 225, 2437, 6275, 16, 1731, 1578, 3903, 548, 1769, 203, 282, 871, 24242, 1290, 41, 2312, 15259, 1074, 12, 2867, 8808, 10438, 16, 2254, 5034, 512, 2312, 16283, 885, 6275, 1769, 203, 282, 871, 1166, 8755, 12, 11890, 1105, 1300, 8755, 1769, 203, 282, 445, 512, 2312, 38, 1345, 30746, 261, 11890, 389, 6769, 950, 16, 2254, 389, 7098, 950, 16, 1758, 389, 41, 2312, 38, 8870, 5049, 291, 360, 16, 2254, 5034, 389, 8694, 13, 203, 203, 5411, 1661, 67, 7124, 67, 2867, 24899, 41, 2312, 38, 8870, 5049, 291, 360, 13, 288, 203, 377, 1815, 261, 67, 6769, 950, 1545, 336, 8674, 10663, 203, 377, 1815, 261, 67, 6769, 950, 411, 389, 7098, 950, 1769, 203, 203, 377, 2172, 950, 273, 389, 6769, 950, 31, 203, 377, 3325, 950, 273, 389, 7098, 950, 31, 203, 377, 512, 2312, 38, 8870, 5049, 291, 360, 273, 389, 41, 2312, 38, 8870, 5049, 291, 360, 31, 203, 377, 6205, 273, 389, 8694, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 12, 2867, 619, 13, 288, 203, 377, 2583, 12, 3576, 18, 15330, 422, 619, 1769, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 5771, 67, 87, 5349, 288, 203, 377, 2583, 12, 588, 8674, 1435, 411, 2172, 950, 1769, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 72, 4017, 67, 87, 5349, 67, 6908, 288, 203, 377, 2583, 12, 588, 8674, 1435, 1545, 2172, 950, 1769, 203, 203, 377, 2583, 12, 588, 8674, 1435, 411, 3325, 950, 747, 1131, 27716, 23646, 10663, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 5205, 67, 87, 5349, 288, 203, 377, 2583, 12, 588, 8674, 1435, 1545, 3325, 950, 747, 17683, 23646, 10663, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 87, 5349, 67, 24228, 288, 203, 377, 2583, 12, 87, 5349, 15294, 1769, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 87, 5349, 67, 902, 67, 24228, 288, 203, 377, 2583, 12, 5, 87, 5349, 15294, 1769, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 5771, 67, 87, 5349, 67, 16908, 288, 203, 377, 2583, 12, 5, 291, 28724, 10663, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 87, 5349, 67, 18836, 288, 203, 377, 2583, 12, 291, 28724, 10663, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1338, 67, 6385, 1235, 67, 87, 5349, 288, 203, 377, 2583, 12, 588, 8674, 1435, 1545, 3325, 950, 747, 17683, 23646, 10663, 203, 377, 2583, 12, 87, 5349, 7951, 1235, 1769, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 1661, 67, 7124, 67, 2867, 12, 2867, 619, 13, 288, 203, 377, 2583, 12, 92, 480, 374, 1769, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 9606, 5224, 67, 1132, 12, 11890, 5034, 619, 13, 288, 203, 377, 2583, 12, 3576, 18, 1132, 1545, 619, 1769, 203, 377, 389, 31, 203, 282, 289, 203, 203, 282, 445, 444, 41, 2312, 16283, 885, 12, 2867, 389, 2316, 16, 1758, 389, 5185, 14038, 16, 1758, 389, 87, 5349, 16936, 16, 2254, 5034, 389, 1154, 27716, 16, 2254, 5034, 389, 27354, 13, 203, 5411, 8843, 429, 203, 5411, 1661, 67, 7124, 67, 2867, 24899, 2316, 13, 203, 5411, 1338, 12, 41, 2312, 38, 8870, 5049, 291, 360, 13, 203, 5411, 1071, 288, 203, 203, 377, 2583, 24899, 5185, 14038, 480, 374, 1769, 203, 377, 2583, 24899, 87, 5349, 16936, 480, 374, 1769, 203, 203, 377, 1815, 12, 5, 18836, 63, 2211, 19226, 203, 203, 377, 1147, 273, 512, 2312, 16283, 885, 24899, 2316, 1769, 203, 377, 2483, 14038, 273, 512, 2312, 16283, 885, 14038, 24899, 5185, 14038, 1769, 203, 377, 272, 5349, 16936, 273, 348, 5349, 16936, 24899, 87, 5349, 16936, 1769, 203, 203, 203, 203, 203, 203, 377, 1131, 27716, 273, 389, 1154, 27716, 31, 203, 377, 17683, 273, 389, 27354, 31, 203, 203, 377, 741, 21370, 30746, 12, 2211, 1769, 203, 282, 289, 203, 203, 282, 445, 10235, 30746, 1435, 203, 5411, 1071, 288, 203, 377, 741, 21370, 30746, 12, 3576, 18, 15330, 1769, 203, 377, 26939, 690, 30746, 5621, 203, 282, 289, 203, 203, 282, 445, 741, 21370, 30746, 12, 2867, 389, 1096, 13, 203, 377, 1338, 67, 5771, 67, 87, 5349, 203, 377, 3238, 288, 203, 377, 14892, 63, 67, 1096, 65, 273, 638, 31, 203, 282, 289, 203, 203, 282, 445, 353, 28724, 1435, 203, 5411, 5381, 203, 5411, 1071, 203, 5411, 1135, 261, 6430, 13, 288, 203, 377, 327, 14892, 63, 2211, 65, 597, 14892, 63, 41, 2312, 38, 8870, 5049, 291, 360, 15533, 203, 282, 289, 203, 203, 282, 445, 25930, 12, 11890, 5034, 389, 8949, 13, 203, 5411, 1338, 67, 72, 4017, 67, 87, 5349, 67, 6908, 203, 5411, 1338, 67, 87, 5349, 67, 902, 67, 24228, 203, 5411, 1338, 67, 87, 5349, 67, 18836, 203, 5411, 5381, 203, 5411, 1071, 203, 5411, 1135, 261, 11890, 5034, 13, 288, 203, 377, 327, 6205, 1290, 8755, 12, 9890, 10477, 18, 16411, 24899, 8949, 16, 6205, 10019, 203, 282, 289, 203, 203, 282, 445, 6205, 1290, 8755, 12, 11890, 5034, 389, 8949, 13, 203, 5411, 2713, 203, 5411, 1135, 261, 11890, 5034, 13, 288, 203, 203, 4202, 327, 14060, 10477, 18, 1289, 24899, 8949, 16, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 24899, 8949, 16, 4200, 3631, 2130, 10019, 203, 377, 289, 203, 203, 4202, 327, 14060, 10477, 18, 1289, 24899, 8949, 16, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 24899, 8949, 16, 6549, 3631, 2130, 10019, 203, 377, 289, 203, 2, -100, -100 ]
./full_match/137/0x4eEC1Dc3a43d8F53A36d4A416fC30b1B6C287d13/sources/contract-0beda585d0.sol
@custom:security-contact [email protected]
contract KIWANO is ERC20, ERC20Burnable, Pausable, Ownable { pragma solidity ^0.8.2; constructor() ERC20("KIWANO", "WANO") { _mint(msg.sender, 250000000 * 10 ** decimals()); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override { super._beforeTokenTransfer(from, to, amount); } }
4,761,041
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 3662, 30, 7462, 17, 8994, 4373, 36, 15299, 91, 304, 556, 28290, 18, 832, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 45, 26499, 51, 353, 4232, 39, 3462, 16, 4232, 39, 3462, 38, 321, 429, 16, 21800, 16665, 16, 14223, 6914, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 22, 31, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 47, 45, 26499, 51, 3113, 315, 26499, 51, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 6969, 17877, 380, 1728, 2826, 15105, 10663, 203, 565, 289, 203, 203, 565, 445, 11722, 1435, 1071, 1338, 5541, 288, 203, 3639, 389, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 640, 19476, 1435, 1071, 1338, 5541, 288, 203, 3639, 389, 318, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 12, 869, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 203, 3639, 2713, 203, 3639, 1347, 1248, 28590, 203, 3639, 3849, 203, 565, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-11-19 */ /** *Submitted for verification at Etherscan.io on 2020-10-26 */ // SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.7.0; pragma solidity ^0.6.0; pragma solidity ^0.6.0; pragma solidity >=0.5.0; pragma solidity 0.6.12; pragma solidity ^0.6.0; pragma solidity 0.6.12; pragma solidity >=0.5.0; pragma solidity ^0.6.0; pragma solidity >=0.5.0; pragma solidity ^0.6.0; pragma solidity 0.6.12; // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: contracts/interfaces/IWETH9.sol interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts/interfaces/IFeeApprover.sol interface IFeeApprover { function sync() external; function setFeeMultiplier(uint _feeMultiplier) external; function feePercentX100() external view returns (uint); function setTokenUniswapPair(address _tokenUniswapPair) external; function setTcoreTokenAddress(address _tcoreTokenAddress) external; function updateTxState() external; function calculateAmountsAfterFee( address sender, address recipient, uint256 amount ) external returns (uint256 transferToAmount, uint256 transferToFeeBearerAmount); function setPaused() external; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (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: contracts/libraries/Math.sol // 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; } } } // File: @uniswap/v1-tcore/contracts/interfaces/IUniswapV2Pair.sol 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; } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/libraries/UniswapV2Library.sol 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; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts/ITcoreVault.sol interface ITcoreVault { function addPendingRewards(uint _amount) external; function depositFor(address depositFor, uint256 _pid, uint256 _amount) external; } // File: contracts/TCOREv1Router.sol // import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; contract TCOREv1Router is OwnableUpgradeSafe { using SafeMath for uint256; mapping(address => uint256) public hardTCORE; address public _tcoreToken = address(0x7A3D5d49D64E57DBd6FBB21dF7202bD3EE7A2253); address public _tcoreWETHPair = address(0x39C0eDEf530d284b8f7820061114157C5bD78093); IFeeApprover public _feeApprover = IFeeApprover(0x9c5AD35C0adC42e996E5F7C3d6681b9e2807c700); ITcoreVault public _tcoreVault = ITcoreVault(0x42A43cD4A19eaBE7775Ea261e4ECAC4CBC2acC3a); IWETH public _WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); function initialize() public initializer { OwnableUpgradeSafe.__Ownable_init(); refreshApproval(); } function refreshApproval() public { IUniswapV2Pair(_tcoreWETHPair).approve(address(_tcoreVault), uint(-1)); } fallback() external payable { if(msg.sender != address(_WETH)){ addLiquidityETHOnly(msg.sender, false); } } function addLiquidityETHOnly(address payable to, bool autoStake) public payable { require(to != address(0), "Invalid address"); hardTCORE[msg.sender] = hardTCORE[msg.sender].add(msg.value); uint256 buyAmount = msg.value.div(2); require(buyAmount > 0, "Insufficient ETH amount"); _WETH.deposit{value : msg.value}(); (uint256 reserveWeth, uint256 reserveTcore) = getPairReserves(); uint256 outTcore = UniswapV2Library.getAmountOut(buyAmount, reserveWeth, reserveTcore); _WETH.transfer(_tcoreWETHPair, buyAmount); (address token0, address token1) = UniswapV2Library.sortTokens(address(_WETH), _tcoreToken); IUniswapV2Pair(_tcoreWETHPair).swap(_tcoreToken == token0 ? outTcore : 0, _tcoreToken == token1 ? outTcore : 0, address(this), ""); _addLiquidity(outTcore, buyAmount, to, autoStake); _feeApprover.sync(); } function _addLiquidity(uint256 tcoreAmount, uint256 wethAmount, address payable to, bool autoStake) internal { (uint256 wethReserve, uint256 tcoreReserve) = getPairReserves(); uint256 optimalTcoreAmount = UniswapV2Library.quote(wethAmount, wethReserve, tcoreReserve); uint256 optimalWETHAmount; if (optimalTcoreAmount > tcoreAmount) { optimalWETHAmount = UniswapV2Library.quote(tcoreAmount, tcoreReserve, wethReserve); optimalTcoreAmount = tcoreAmount; } else optimalWETHAmount = wethAmount; assert(_WETH.transfer(_tcoreWETHPair, optimalWETHAmount)); assert(IERC20(_tcoreToken).transfer(_tcoreWETHPair, optimalTcoreAmount)); if (autoStake) { IUniswapV2Pair(_tcoreWETHPair).mint(address(this)); _tcoreVault.depositFor(to, 0, IUniswapV2Pair(_tcoreWETHPair).balanceOf(address(this))); } else IUniswapV2Pair(_tcoreWETHPair).mint(to); //refund dust if (tcoreAmount > optimalTcoreAmount) IERC20(_tcoreToken).transfer(to, tcoreAmount.sub(optimalTcoreAmount)); if (wethAmount > optimalWETHAmount) { uint256 withdrawAmount = wethAmount.sub(optimalWETHAmount); _WETH.withdraw(withdrawAmount); to.transfer(withdrawAmount); } } function changeFeeApprover(address feeApprover) external onlyOwner { address oldAddress = address(_feeApprover); _feeApprover = IFeeApprover(feeApprover); } function changeTVault(address tcoreVault) external onlyOwner { address oldAddress = address(_tcoreVault); _tcoreVault = ITcoreVault(tcoreVault); } function getLPTokenPerEthUnit(uint ethAmt) public view returns (uint liquidity){ (uint256 reserveWeth, uint256 reserveTcore) = getPairReserves(); uint256 outTcore = UniswapV2Library.getAmountOut(ethAmt.div(2), reserveWeth, reserveTcore); uint _totalSupply = IUniswapV2Pair(_tcoreWETHPair).totalSupply(); (address token0, ) = UniswapV2Library.sortTokens(address(_WETH), _tcoreToken); (uint256 amount0, uint256 amount1) = token0 == _tcoreToken ? (outTcore, ethAmt.div(2)) : (ethAmt.div(2), outTcore); (uint256 _reserve0, uint256 _reserve1) = token0 == _tcoreToken ? (reserveTcore, reserveWeth) : (reserveWeth, reserveTcore); liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } function getPairReserves() internal view returns (uint256 wethReserves, uint256 tcoreReserves) { (address token0,) = UniswapV2Library.sortTokens(address(_WETH), _tcoreToken); (uint256 reserve0, uint reserve1,) = IUniswapV2Pair(_tcoreWETHPair).getReserves(); (wethReserves, tcoreReserves) = token0 == _tcoreToken ? (reserve1, reserve0) : (reserve0, reserve1); } }
File: contracts/TCOREv1Router.sol import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
contract TCOREv1Router is OwnableUpgradeSafe { using SafeMath for uint256; mapping(address => uint256) public hardTCORE; address public _tcoreToken = address(0x7A3D5d49D64E57DBd6FBB21dF7202bD3EE7A2253); address public _tcoreWETHPair = address(0x39C0eDEf530d284b8f7820061114157C5bD78093); IFeeApprover public _feeApprover = IFeeApprover(0x9c5AD35C0adC42e996E5F7C3d6681b9e2807c700); ITcoreVault public _tcoreVault = ITcoreVault(0x42A43cD4A19eaBE7775Ea261e4ECAC4CBC2acC3a); IWETH public _WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); function initialize() public initializer { OwnableUpgradeSafe.__Ownable_init(); refreshApproval(); } function refreshApproval() public { IUniswapV2Pair(_tcoreWETHPair).approve(address(_tcoreVault), uint(-1)); } fallback() external payable { if(msg.sender != address(_WETH)){ addLiquidityETHOnly(msg.sender, false); } } fallback() external payable { if(msg.sender != address(_WETH)){ addLiquidityETHOnly(msg.sender, false); } } function addLiquidityETHOnly(address payable to, bool autoStake) public payable { require(to != address(0), "Invalid address"); hardTCORE[msg.sender] = hardTCORE[msg.sender].add(msg.value); uint256 buyAmount = msg.value.div(2); require(buyAmount > 0, "Insufficient ETH amount"); (uint256 reserveWeth, uint256 reserveTcore) = getPairReserves(); uint256 outTcore = UniswapV2Library.getAmountOut(buyAmount, reserveWeth, reserveTcore); _WETH.transfer(_tcoreWETHPair, buyAmount); (address token0, address token1) = UniswapV2Library.sortTokens(address(_WETH), _tcoreToken); IUniswapV2Pair(_tcoreWETHPair).swap(_tcoreToken == token0 ? outTcore : 0, _tcoreToken == token1 ? outTcore : 0, address(this), ""); _addLiquidity(outTcore, buyAmount, to, autoStake); _feeApprover.sync(); } _WETH.deposit{value : msg.value}(); function _addLiquidity(uint256 tcoreAmount, uint256 wethAmount, address payable to, bool autoStake) internal { (uint256 wethReserve, uint256 tcoreReserve) = getPairReserves(); uint256 optimalTcoreAmount = UniswapV2Library.quote(wethAmount, wethReserve, tcoreReserve); uint256 optimalWETHAmount; if (optimalTcoreAmount > tcoreAmount) { optimalWETHAmount = UniswapV2Library.quote(tcoreAmount, tcoreReserve, wethReserve); optimalTcoreAmount = tcoreAmount; } else optimalWETHAmount = wethAmount; assert(_WETH.transfer(_tcoreWETHPair, optimalWETHAmount)); assert(IERC20(_tcoreToken).transfer(_tcoreWETHPair, optimalTcoreAmount)); if (autoStake) { IUniswapV2Pair(_tcoreWETHPair).mint(address(this)); _tcoreVault.depositFor(to, 0, IUniswapV2Pair(_tcoreWETHPair).balanceOf(address(this))); } else IUniswapV2Pair(_tcoreWETHPair).mint(to); IERC20(_tcoreToken).transfer(to, tcoreAmount.sub(optimalTcoreAmount)); if (wethAmount > optimalWETHAmount) { uint256 withdrawAmount = wethAmount.sub(optimalWETHAmount); _WETH.withdraw(withdrawAmount); to.transfer(withdrawAmount); } } function _addLiquidity(uint256 tcoreAmount, uint256 wethAmount, address payable to, bool autoStake) internal { (uint256 wethReserve, uint256 tcoreReserve) = getPairReserves(); uint256 optimalTcoreAmount = UniswapV2Library.quote(wethAmount, wethReserve, tcoreReserve); uint256 optimalWETHAmount; if (optimalTcoreAmount > tcoreAmount) { optimalWETHAmount = UniswapV2Library.quote(tcoreAmount, tcoreReserve, wethReserve); optimalTcoreAmount = tcoreAmount; } else optimalWETHAmount = wethAmount; assert(_WETH.transfer(_tcoreWETHPair, optimalWETHAmount)); assert(IERC20(_tcoreToken).transfer(_tcoreWETHPair, optimalTcoreAmount)); if (autoStake) { IUniswapV2Pair(_tcoreWETHPair).mint(address(this)); _tcoreVault.depositFor(to, 0, IUniswapV2Pair(_tcoreWETHPair).balanceOf(address(this))); } else IUniswapV2Pair(_tcoreWETHPair).mint(to); IERC20(_tcoreToken).transfer(to, tcoreAmount.sub(optimalTcoreAmount)); if (wethAmount > optimalWETHAmount) { uint256 withdrawAmount = wethAmount.sub(optimalWETHAmount); _WETH.withdraw(withdrawAmount); to.transfer(withdrawAmount); } } function _addLiquidity(uint256 tcoreAmount, uint256 wethAmount, address payable to, bool autoStake) internal { (uint256 wethReserve, uint256 tcoreReserve) = getPairReserves(); uint256 optimalTcoreAmount = UniswapV2Library.quote(wethAmount, wethReserve, tcoreReserve); uint256 optimalWETHAmount; if (optimalTcoreAmount > tcoreAmount) { optimalWETHAmount = UniswapV2Library.quote(tcoreAmount, tcoreReserve, wethReserve); optimalTcoreAmount = tcoreAmount; } else optimalWETHAmount = wethAmount; assert(_WETH.transfer(_tcoreWETHPair, optimalWETHAmount)); assert(IERC20(_tcoreToken).transfer(_tcoreWETHPair, optimalTcoreAmount)); if (autoStake) { IUniswapV2Pair(_tcoreWETHPair).mint(address(this)); _tcoreVault.depositFor(to, 0, IUniswapV2Pair(_tcoreWETHPair).balanceOf(address(this))); } else IUniswapV2Pair(_tcoreWETHPair).mint(to); IERC20(_tcoreToken).transfer(to, tcoreAmount.sub(optimalTcoreAmount)); if (wethAmount > optimalWETHAmount) { uint256 withdrawAmount = wethAmount.sub(optimalWETHAmount); _WETH.withdraw(withdrawAmount); to.transfer(withdrawAmount); } } if (tcoreAmount > optimalTcoreAmount) function _addLiquidity(uint256 tcoreAmount, uint256 wethAmount, address payable to, bool autoStake) internal { (uint256 wethReserve, uint256 tcoreReserve) = getPairReserves(); uint256 optimalTcoreAmount = UniswapV2Library.quote(wethAmount, wethReserve, tcoreReserve); uint256 optimalWETHAmount; if (optimalTcoreAmount > tcoreAmount) { optimalWETHAmount = UniswapV2Library.quote(tcoreAmount, tcoreReserve, wethReserve); optimalTcoreAmount = tcoreAmount; } else optimalWETHAmount = wethAmount; assert(_WETH.transfer(_tcoreWETHPair, optimalWETHAmount)); assert(IERC20(_tcoreToken).transfer(_tcoreWETHPair, optimalTcoreAmount)); if (autoStake) { IUniswapV2Pair(_tcoreWETHPair).mint(address(this)); _tcoreVault.depositFor(to, 0, IUniswapV2Pair(_tcoreWETHPair).balanceOf(address(this))); } else IUniswapV2Pair(_tcoreWETHPair).mint(to); IERC20(_tcoreToken).transfer(to, tcoreAmount.sub(optimalTcoreAmount)); if (wethAmount > optimalWETHAmount) { uint256 withdrawAmount = wethAmount.sub(optimalWETHAmount); _WETH.withdraw(withdrawAmount); to.transfer(withdrawAmount); } } function changeFeeApprover(address feeApprover) external onlyOwner { address oldAddress = address(_feeApprover); _feeApprover = IFeeApprover(feeApprover); } function changeTVault(address tcoreVault) external onlyOwner { address oldAddress = address(_tcoreVault); _tcoreVault = ITcoreVault(tcoreVault); } function getLPTokenPerEthUnit(uint ethAmt) public view returns (uint liquidity){ (uint256 reserveWeth, uint256 reserveTcore) = getPairReserves(); uint256 outTcore = UniswapV2Library.getAmountOut(ethAmt.div(2), reserveWeth, reserveTcore); uint _totalSupply = IUniswapV2Pair(_tcoreWETHPair).totalSupply(); (address token0, ) = UniswapV2Library.sortTokens(address(_WETH), _tcoreToken); (uint256 amount0, uint256 amount1) = token0 == _tcoreToken ? (outTcore, ethAmt.div(2)) : (ethAmt.div(2), outTcore); (uint256 _reserve0, uint256 _reserve1) = token0 == _tcoreToken ? (reserveTcore, reserveWeth) : (reserveWeth, reserveTcore); liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } function getPairReserves() internal view returns (uint256 wethReserves, uint256 tcoreReserves) { (address token0,) = UniswapV2Library.sortTokens(address(_WETH), _tcoreToken); (uint256 reserve0, uint reserve1,) = IUniswapV2Pair(_tcoreWETHPair).getReserves(); (wethReserves, tcoreReserves) = token0 == _tcoreToken ? (reserve1, reserve0) : (reserve0, reserve1); } }
239,369
[ 1, 4625, 348, 7953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0, 0 ]
[ 1, 16351, 399, 15715, 90, 21, 8259, 353, 14223, 6914, 10784, 9890, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 7877, 56, 15715, 31, 203, 203, 565, 1758, 1071, 389, 88, 3644, 1345, 273, 1758, 12, 20, 92, 27, 37, 23, 40, 25, 72, 7616, 40, 1105, 41, 10321, 2290, 72, 26, 42, 9676, 5340, 72, 42, 9060, 3103, 70, 40, 23, 9383, 27, 37, 22, 30304, 1769, 203, 565, 1758, 1071, 389, 88, 3644, 59, 1584, 2500, 1826, 273, 1758, 12, 20, 92, 5520, 39, 20, 73, 1639, 74, 25, 5082, 72, 22, 5193, 70, 28, 74, 8285, 6976, 26, 2499, 3461, 27985, 39, 25, 70, 40, 27, 3672, 11180, 1769, 203, 565, 11083, 1340, 12053, 502, 1071, 389, 21386, 12053, 502, 273, 11083, 1340, 12053, 502, 12, 20, 92, 29, 71, 25, 1880, 4763, 39, 20, 361, 39, 9452, 73, 2733, 26, 41, 25, 42, 27, 39, 23, 72, 6028, 11861, 70, 29, 73, 22, 3672, 27, 71, 26874, 1769, 203, 565, 24142, 3644, 12003, 1071, 389, 88, 3644, 12003, 273, 24142, 3644, 12003, 12, 20, 92, 9452, 37, 8942, 71, 40, 24, 37, 3657, 24852, 5948, 4700, 5877, 41, 69, 5558, 21, 73, 24, 7228, 2226, 24, 21813, 22, 1077, 39, 23, 69, 1769, 203, 565, 467, 59, 1584, 44, 1071, 389, 59, 1584, 44, 273, 467, 59, 1584, 44, 12, 20, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 1769, 203, 203, 565, 445, 4046, 1435, 1071, 12562, 288, 203, 3639, 14223, 6914, 10784, 9890, 16186, 5460, 429, 67, 2738, 5621, 203, 3639, 4460, 23461, 5621, 203, 565, 289, 203, 203, 565, 445, 4460, 23461, 1435, 1071, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 4154, 24899, 88, 3644, 59, 1584, 2500, 1826, 2934, 12908, 537, 12, 2867, 24899, 88, 3644, 12003, 3631, 2254, 19236, 21, 10019, 203, 565, 289, 203, 203, 565, 5922, 1435, 3903, 8843, 429, 288, 203, 3639, 309, 12, 3576, 18, 15330, 480, 1758, 24899, 59, 1584, 44, 3719, 95, 203, 2398, 527, 48, 18988, 24237, 1584, 44, 3386, 12, 3576, 18, 15330, 16, 629, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 565, 5922, 1435, 3903, 8843, 429, 288, 203, 3639, 309, 12, 3576, 18, 15330, 480, 1758, 24899, 59, 1584, 44, 3719, 95, 203, 2398, 527, 48, 18988, 24237, 1584, 44, 3386, 12, 3576, 18, 15330, 16, 629, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 565, 445, 527, 48, 18988, 24237, 1584, 44, 3386, 12, 2867, 8843, 429, 358, 16, 1426, 3656, 510, 911, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 1941, 1758, 8863, 203, 3639, 7877, 56, 15715, 63, 3576, 18, 15330, 65, 273, 7877, 56, 15715, 63, 3576, 18, 15330, 8009, 1289, 12, 3576, 18, 1132, 1769, 203, 203, 3639, 2254, 5034, 30143, 6275, 273, 1234, 18, 1132, 18, 2892, 12, 22, 1769, 203, 3639, 2583, 12, 70, 9835, 6275, 405, 374, 16, 315, 5048, 11339, 512, 2455, 3844, 8863, 203, 203, 3639, 261, 11890, 5034, 20501, 59, 546, 16, 2254, 5034, 20501, 56, 3644, 13, 273, 1689, 1826, 607, 264, 3324, 5621, 203, 3639, 2254, 5034, 596, 56, 3644, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 588, 6275, 1182, 12, 70, 9835, 6275, 16, 20501, 59, 546, 16, 20501, 56, 3644, 1769, 203, 203, 3639, 389, 59, 1584, 44, 18, 13866, 24899, 88, 3644, 59, 1584, 2500, 1826, 16, 30143, 6275, 1769, 203, 203, 3639, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 3804, 5157, 12, 2867, 24899, 59, 1584, 44, 3631, 389, 88, 3644, 1345, 1769, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 4154, 24899, 88, 3644, 59, 1584, 2500, 1826, 2934, 22270, 24899, 88, 3644, 1345, 422, 1147, 20, 692, 596, 56, 3644, 294, 374, 16, 389, 88, 3644, 1345, 422, 1147, 21, 692, 596, 56, 3644, 294, 374, 16, 1758, 12, 2211, 3631, 1408, 1769, 203, 203, 3639, 389, 1289, 48, 18988, 24237, 12, 659, 56, 3644, 16, 30143, 6275, 16, 358, 16, 3656, 510, 911, 1769, 203, 203, 3639, 389, 21386, 12053, 502, 18, 8389, 5621, 203, 565, 289, 203, 203, 3639, 389, 59, 1584, 44, 18, 323, 1724, 95, 1132, 294, 1234, 18, 1132, 97, 5621, 203, 565, 445, 389, 1289, 48, 18988, 24237, 12, 11890, 5034, 1715, 479, 6275, 16, 2254, 5034, 341, 546, 6275, 16, 1758, 8843, 429, 358, 16, 1426, 3656, 510, 911, 13, 2713, 288, 203, 3639, 261, 11890, 5034, 341, 546, 607, 6527, 16, 2254, 5034, 1715, 479, 607, 6527, 13, 273, 1689, 1826, 607, 264, 3324, 5621, 203, 203, 3639, 2254, 5034, 16413, 56, 3644, 6275, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 6889, 12, 91, 546, 6275, 16, 341, 546, 607, 6527, 16, 1715, 479, 607, 6527, 1769, 203, 203, 3639, 2254, 5034, 16413, 59, 1584, 44, 6275, 31, 203, 3639, 309, 261, 3838, 2840, 56, 3644, 6275, 405, 1715, 479, 6275, 13, 288, 203, 5411, 16413, 59, 1584, 44, 6275, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 6889, 12, 88, 3644, 6275, 16, 1715, 479, 607, 6527, 16, 341, 546, 607, 6527, 1769, 203, 5411, 16413, 56, 3644, 6275, 273, 1715, 479, 6275, 31, 203, 3639, 289, 203, 3639, 469, 203, 5411, 16413, 59, 1584, 44, 6275, 273, 341, 546, 6275, 31, 203, 203, 3639, 1815, 24899, 59, 1584, 44, 18, 13866, 24899, 88, 3644, 59, 1584, 2500, 1826, 16, 16413, 59, 1584, 44, 6275, 10019, 203, 3639, 1815, 12, 45, 654, 39, 3462, 24899, 88, 3644, 1345, 2934, 13866, 24899, 88, 3644, 59, 1584, 2500, 1826, 16, 16413, 56, 3644, 6275, 10019, 203, 203, 3639, 309, 261, 6079, 510, 911, 13, 288, 203, 5411, 467, 984, 291, 91, 438, 58, 22, 4154, 24899, 88, 3644, 59, 1584, 2500, 1826, 2934, 81, 474, 12, 2867, 12, 2211, 10019, 203, 5411, 389, 88, 3644, 12003, 18, 323, 1724, 2 ]
./full_match/5/0x626Cc7C3BE5dd533be2AC4DAbc4B7ef7480C15ca/sources/contracts/Crowdfunding.sol
return the idex (id) of latest campaign
function createCampaign( address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image ) public returns (uint256) { Campaign storage campaign = campaigns[numberOfCampaigns]; require( campaign.deadline < block.timestamp, "The deadline should be a date in the future..." ); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.image = _image; numberOfCampaigns++; return numberOfCampaigns - 1; }
1,866,366
[ 1, 4625, 348, 7953, 560, 30, 327, 326, 277, 561, 261, 350, 13, 434, 4891, 8965, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13432, 12, 203, 3639, 1758, 389, 8443, 16, 203, 3639, 533, 3778, 389, 2649, 16, 203, 3639, 533, 3778, 389, 3384, 16, 203, 3639, 2254, 5034, 389, 3299, 16, 203, 3639, 2254, 5034, 389, 22097, 1369, 16, 203, 3639, 533, 3778, 389, 2730, 203, 565, 262, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 17820, 2502, 8965, 273, 8965, 87, 63, 2696, 951, 13432, 87, 15533, 203, 203, 3639, 2583, 12, 203, 5411, 8965, 18, 22097, 1369, 411, 1203, 18, 5508, 16, 203, 5411, 315, 1986, 14096, 1410, 506, 279, 1509, 316, 326, 3563, 7070, 203, 3639, 11272, 203, 3639, 8965, 18, 8443, 273, 389, 8443, 31, 203, 3639, 8965, 18, 2649, 273, 389, 2649, 31, 203, 3639, 8965, 18, 3384, 273, 389, 3384, 31, 203, 3639, 8965, 18, 3299, 273, 389, 3299, 31, 203, 3639, 8965, 18, 22097, 1369, 273, 389, 22097, 1369, 31, 203, 3639, 8965, 18, 2730, 273, 389, 2730, 31, 203, 203, 3639, 7922, 13432, 87, 9904, 31, 203, 203, 3639, 327, 7922, 13432, 87, 300, 404, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./erc721.sol"; import "./SafeMath.sol"; import "./Random.sol"; import "./Database.sol"; contract WarriorBase is ERC721 { using SafeMath for uint256; using SafeMath for uint64; Random private randomContract; Database private databaseContract; /// @dev This emits when the token ownership changed event Transfer(address indexed from, address indexed to, uint256 tokenId); /// @dev This emits when user charged his warrior event NewFund(uint _value); /// @dev This emits when a new warrior is created(adopted) by user event CreateWarrior(address _owner, uint newWarriorId, uint _val); event Consequence(uint winnerId, uint loserId, address winnerAddr, address loserAddr, uint valToTransfer, uint ceToTransfer, uint winnerTitle, uint loserTitle); event KillWarrior(uint _id, address owner, uint tokenToOwnerIndex); event AddPrestige(uint _id, uint winningPrestige, uint title); event SubPrestige(uint _id, uint winningPrestige); event SetCoachCoolDownTime(uint coachId, uint attackId, uint curTime); event SwitchRetirementStatus(uint tokenId, uint retirementStatus); mapping (uint => address) internal tokenApprovals; mapping (uint => address) internal tokenIndexToOwner; mapping (address => uint) internal ownerToTokenCount; mapping (address => uint[]) internal ownerToTokenArray; /// the id of the given token in owner's token list. mapping (uint => uint) internal tokenIndexToOwnerIndex; string public constant name = "SpartaxWarrior"; string public constant symbol = "SW"; uint constant greenhandProtection = 30 minutes; uint constant miniValue = 10 ** 16; struct Warrior { uint val; /// 0 uint winCount; /// 1 uint lossCount; /// 2 uint combo; /// 3 uint title; /// 4 title: default--0 primary coach--7 intermediate coach--8 advanced coach--9 master--10 uint prestige; /// 5 uint ce; /// 6 comat effectiveness uint createTime; /// 7 uint destroyTime; /// 8 uint lastAttackCoach1; /// 9 uint lastAttackCoach2; /// 10 uint lastAttackCoach3; /// 11 uint lastAttackCoach4; /// 12 uint isRetired; /// 13 } Warrior[] private WarriorList; uint private ActiveWarriorListLength; /// @dev check the given tokenId is in the tokenList and its owner is not null. modifier tokenExist(uint256 _id) { require(_id >= 1 && _id <= WarriorList.length); require(tokenIndexToOwner[_id] != address(0)); _; } /// @dev construction method. constructor( address _randomContract, address _databaseContract) public{ randomContract = Random(_randomContract); databaseContract = Database(_databaseContract); /// warrior list contains the 4 coaches at the very beginning ActiveWarriorListLength = 4; /// drop index 0 WarriorList.length += 1; /// primary coach : value 0.01ether comat effectiveness 10 title 7 uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = miniValue; /// 0.01 ether in Wei war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 7; war.prestige = 0; war.ce = 10; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); /// primary coach : value 0.01ether comat effectiveness 10 title 8 newWarriorId = WarriorList.length; WarriorList.length += 1; war = WarriorList[newWarriorId]; war.val = miniValue * 5; /// 0.05 ether in Wei war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 8; war.prestige = 0; war.ce = 50; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); /// primary coach : value 0.01ether comat effectiveness 10 title 9 newWarriorId = WarriorList.length; WarriorList.length += 1; war = WarriorList[newWarriorId]; war.val = miniValue * 10; /// 0.1 ether in Wei war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 9; war.prestige = 0; war.ce = 100; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); /// primary coach : value 0.01ether comat effectiveness 10 title 10 newWarriorId = WarriorList.length; WarriorList.length += 1; war = WarriorList[newWarriorId]; war.val = miniValue * 50; /// 0.5 ether in Wei; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 10; war.prestige = 0; war.ce = 500; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); } /// @dev adopt a level 1 warrior (0.01 eth) function adoptLvOne() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.01 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 10; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender,newWarriorId, msg.value); return newWarriorId; } /// @dev adopt a level 2 warrior (0.05 eth) function adoptLvTwo() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.05 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 50; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; } /// @dev adopt a level 3 warrior (0.1 eth) function adoptLvThree() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.1 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 100; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; } /// @dev adopt a level 4 warrior (0.5 eth) function adoptLvFour() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.5 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 500; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; } function setRandomAddr(address _randomContract) external { randomContract = Random(_randomContract); } /// @dev return the total number of tokens in the game function getTokenNum() external view returns(uint) { return WarriorList.length - 1; } /// @dev return the owner address of the token(warrior) function getTokenOwner(uint _id) external view tokenExist(_id) returns(address) { require(tokenIndexToOwner[_id] != address(0)); return tokenIndexToOwner[_id]; } /// @dev Ruturn token details by tokenId function getToken(uint256 _id) external view tokenExist(_id) returns (uint[14] datas) { Warrior storage warrior = WarriorList[_id]; datas[0] = warrior.val; datas[1] = warrior.winCount; datas[2] = warrior.lossCount; datas[3] = warrior.combo; datas[4] = warrior.title; datas[5] = warrior.prestige; datas[6] = warrior.ce; datas[7] = warrior.createTime; datas[8] = warrior.destroyTime; datas[9] = warrior.lastAttackCoach1; datas[10] = warrior.lastAttackCoach2; datas[11] = warrior.lastAttackCoach3; datas[12] = warrior.lastAttackCoach4; datas[13] = warrior.isRetired; } /// @dev return all tokens owned by owner function getOwnTokens(address _owner) external view returns(uint256[] tokens){ require(_owner != address(0)); uint256[] memory tokenArray = ownerToTokenArray[_owner]; uint256 length = (uint256)(tokenArray.length); tokens = new uint256[](length); for (uint256 i = 0; i < length; ++i) { tokens[i] = tokenArray[i]; } } /// @dev return all tokens not belong to owner function getEnemyTokens(address _owner) external view returns(uint[] tokens) { require(_owner != address(0)); uint length = WarriorList.length - 1 - ownerToTokenArray[_owner].length; tokens = new uint256[](length); uint index = 0; for (uint256 i = 1; i < WarriorList.length; ++i) { if (tokenIndexToOwner[i] != _owner && tokenIndexToOwner[i] != address(0)) { tokens[index] = i; index += 1; } } } /// @dev return active warrior numbers for now function getActiveWarriorListLength() external view returns(uint) { return ActiveWarriorListLength; } /// @dev set the timestamp of attacking each coach, you cannot attack them twice within an hour function setCoachCoolDownTime(uint coachId, uint attackId) external tokenExist(attackId){ Warrior storage attacker = WarriorList[attackId]; if (coachId == 1) attacker.lastAttackCoach1 = uint(now); else if (coachId == 2) attacker.lastAttackCoach2 = uint(now); else if (coachId == 3) attacker.lastAttackCoach3 = uint(now); else if (coachId == 4) attacker.lastAttackCoach4 = uint(now); emit SetCoachCoolDownTime(coachId, attackId, now); } /// @dev calculate the consequece of a finished battle function consequence( uint winnerId, uint loserId, address winnerAddr, address loserAddr) external tokenExist(winnerId) tokenExist(loserId) returns(uint){ require(tokenIndexToOwner[winnerId] == winnerAddr); require(tokenIndexToOwner[loserId] == loserAddr); uint valToTransfer; uint ceToTransfer; if (WarriorList[loserId].ce <= 2) { valToTransfer = WarriorList[loserId].val; ceToTransfer = WarriorList[loserId].ce; } else { valToTransfer = WarriorList[loserId].val.div(2); ceToTransfer = WarriorList[loserId].ce.div(2); } Warrior storage winner = WarriorList[winnerId]; winner.winCount = winner.winCount.add(1); winner.combo = winner.combo.add(1); Warrior storage loser = WarriorList[loserId]; loser.lossCount = loser.lossCount.add(1); loser.combo = 0; if (loser.title < 7 || loser.title > 10) /// if the loser is a coach, his value shall not be reduced. { loser.val = loser.val.sub(valToTransfer); loser.title = 0; loser.ce = loser.ce.sub(ceToTransfer); } if (winner.title < 7 || winner.title > 10) { winner.val = winner.val.add(valToTransfer); winner.ce = winner.ce.add(ceToTransfer); if (winner.title < 7) { if (winner.combo < 1) winner.title = 0; else if (winner.combo < 2) winner.title = 1; else if (winner.combo < 4) winner.title = 2; else if (winner.combo < 8) winner.title = 3; else if (winner.combo < 12) winner.title = 4; else if (winner.combo < 20) winner.title = 5; else winner.title = 6; } } emit Consequence(winnerId,loserId, winnerAddr, loserAddr, valToTransfer, ceToTransfer, winner.title, loser.title); return valToTransfer; } function addPrestige(uint tokenId, uint prestigeAmt) tokenExist(tokenId) external { WarriorList[tokenId].prestige = WarriorList[tokenId].prestige.add(prestigeAmt); if ( WarriorList[tokenId].prestige >= 30 ) WarriorList[tokenId].title = 11; if ( WarriorList[tokenId].prestige >= 40 ) WarriorList[tokenId].title = 12; emit AddPrestige(tokenId, prestigeAmt, WarriorList[tokenId].title); } function subPrestige(uint tokenId, uint prestigeAmt) tokenExist(tokenId) external { WarriorList[tokenId].prestige = WarriorList[tokenId].prestige.sub(prestigeAmt); WarriorList[tokenId].title = 0; if ( WarriorList[tokenId].prestige >= 30 ) WarriorList[tokenId].title = 11; if ( WarriorList[tokenId].prestige >= 40 ) WarriorList[tokenId].title = 12; emit SubPrestige(tokenId, prestigeAmt); } function switchRetirementStatus(uint tokenId) tokenExist(tokenId) external { require(WarriorList[tokenId].title == 12); WarriorList[tokenId].isRetired = 1 - WarriorList[tokenId].isRetired; emit SwitchRetirementStatus(tokenId, WarriorList[tokenId].isRetired); } /// @dev "feed" the token with msg.value function feedWarrior(uint _id) public tokenExist(_id) payable returns(uint) { require(tokenIndexToOwner[_id] == msg.sender); WarriorList[_id].val = WarriorList[_id].val.add(msg.value); databaseContract.addAccountEth(msg.sender, msg.value); NewFund(this.balance); return this.balance; } function _removeFromList(uint _id, address _owner) private { for (uint i = 0; i < ownerToTokenArray[_owner].length; i++) { if (ownerToTokenArray[_owner][i] == _id) { for (uint j = i; j < ownerToTokenArray[_owner].length - 1; j++) ownerToTokenArray[_owner][j] = ownerToTokenArray[_owner][j + 1]; ownerToTokenArray[_owner].length -= 1; return; } } } /// @dev "kill" the token and sent its ether value back to owner's wallet function killWarrior(uint _id) external tokenExist(_id) returns(uint) { require(tokenIndexToOwner[_id] == msg.sender); uint valToTransfer = WarriorList[_id].val; uint tokenToOwnerIndex = tokenIndexToOwnerIndex[_id]; _removeFromList(_id, msg.sender); tokenIndexToOwner[_id] = address(0); ownerToTokenCount[msg.sender] = ownerToTokenCount[msg.sender].sub(1); tokenIndexToOwnerIndex[_id] = 0; databaseContract.reduceAccountEth(msg.sender,valToTransfer); ActiveWarriorListLength = ActiveWarriorListLength.sub(1); msg.sender.transfer(valToTransfer); emit KillWarrior(_id, msg.sender, tokenToOwnerIndex); return tokenToOwnerIndex; } function addFund() public payable returns(uint) { require(msg.value > 0); emit NewFund(this.balance); return this.balance; } function getBalance() external returns(uint){ return this.balance; } function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)){ uint256 indexFrom = tokenIndexToOwnerIndex[_tokenId]; uint256[] storage tokenArray = ownerToTokenArray[_from]; require(tokenArray[indexFrom] == _tokenId); if (indexFrom != tokenArray.length - 1){ uint256 lastTokenId = tokenArray[tokenArray.length - 1]; tokenArray[indexFrom] = lastTokenId; tokenIndexToOwnerIndex[lastTokenId] = indexFrom; } tokenArray.length.sub(1); } /// Transfer the token to address '_to' tokenIndexToOwner[_tokenId] = _to; if (ownerToTokenArray[_to].length == 0){ ownerToTokenCount[_to] = 0; } ownerToTokenArray[_to].push(_tokenId); ownerToTokenCount[_to] = ownerToTokenCount[_to].add(1); tokenIndexToOwnerIndex[_tokenId] = (uint256)(ownerToTokenArray[_to].length.sub(1)); emit Transfer(_from, _to, _tokenId); } ///@dev The function is to be called by former owner to tranfer the token to the new owner himself. function transfer(address _to, uint256 _tokenId) external{ require(msg.sender == tokenIndexToOwner[_tokenId]); require(_to != 0x0); _transfer(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) external{ // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); require(_to != address(this)); // Check for approval and valid ownership //require(_approvedFor(msg.sender, _tokenId)); require(ownerOf(_tokenId) == _from); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return WarriorList.length - 1; } function balanceOf(address _owner) public view returns (uint256 balance) { return ownerToTokenCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { _owner = tokenIndexToOwner[_tokenId]; require(_owner != address(0)); } ///@dev The function is to be called by new owner to get the token from the former owner himself. function takeOwnership(uint256 _tokenId) public { require(tokenApprovals[_tokenId] == msg.sender); address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } ///@dev The function is to be called by former owner to assign the token ownership to the new owner. function approve(address _to, uint256 _tokenId) external{ require(msg.sender == tokenIndexToOwner[_tokenId]); tokenApprovals[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function destroyWeaponById(uint256 _tokenId) public { require(msg.sender == tokenIndexToOwner[_tokenId]); } // ERC721 function supportsInterface(bytes4 _interfaceId) external view returns(bool) { // ERC165 || ERC721 || ERC165^ERC721 return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff); } }
@dev adopt a level 2 warrior (0.05 eth)
function adoptLvTwo() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.05 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 50; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; }
1,821,250
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 1261, 3838, 279, 1801, 576, 21983, 2432, 261, 20, 18, 6260, 13750, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1261, 3838, 48, 90, 11710, 1435, 7010, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 3639, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 374, 18, 6260, 225, 2437, 1769, 203, 203, 203, 3639, 2254, 394, 30634, 2432, 548, 273, 678, 297, 2432, 682, 18, 2469, 31, 203, 3639, 678, 297, 2432, 682, 18, 2469, 1011, 404, 31, 203, 3639, 678, 297, 2432, 2502, 21983, 273, 678, 297, 2432, 682, 63, 2704, 30634, 2432, 548, 15533, 203, 3639, 21983, 18, 1125, 273, 1234, 18, 1132, 31, 203, 3639, 21983, 18, 8082, 1380, 273, 374, 31, 203, 3639, 21983, 18, 7873, 1380, 273, 374, 31, 203, 3639, 21983, 18, 25053, 273, 374, 31, 203, 3639, 21983, 18, 2649, 273, 374, 31, 203, 3639, 21983, 18, 1484, 334, 360, 73, 273, 374, 31, 203, 3639, 21983, 18, 311, 273, 6437, 31, 203, 3639, 21983, 18, 2640, 950, 273, 2037, 31, 203, 3639, 21983, 18, 11662, 950, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 21, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 22, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 23, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 24, 273, 374, 31, 203, 203, 3639, 389, 13866, 12, 20, 16, 3576, 18, 15330, 16, 394, 30634, 2432, 548, 1769, 203, 3639, 2063, 8924, 18, 1289, 3032, 41, 451, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 3639, 8857, 30634, 2432, 682, 1782, 273, 8857, 30634, 2432, 682, 1782, 18, 1289, 12, 21, 1769, 203, 3639, 1788, 30634, 2432, 12, 3576, 18, 15330, 16, 394, 30634, 2432, 548, 16, 1234, 18, 1132, 1769, 203, 3639, 327, 394, 30634, 2432, 548, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.22 <0.6.0; contract IERC20 { function totalSupply() constant public returns (uint256); function balanceOf(address _owner) constant public returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) constant public returns (uint256 remianing); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* CREATED BY ANDRAS SZEKELY, SaiTech (c) 2019 */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract LYCCoin is IERC20, Ownable { using SafeMath for uint256; uint public _totalSupply = 0; uint public constant INITIAL_SUPPLY = 175000000000000000000000000; uint public MAXUM_SUPPLY = 175000000000000000000000000; uint256 public _currentSupply = 0; string public constant symbol = "LYC"; string public constant name = "LYCCoin"; uint8 public constant decimals = 18; uint256 public RATE; bool public mintingFinished = false; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping (address => uint256) public freezeOf; mapping(address => bool) whitelisted; mapping(address => bool) blockListed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Burn(address indexed from, uint256 value); event Freeze(address indexed from, uint256 value); event Unfreeze(address indexed from, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Mint(address indexed to, uint256 amount); event MintFinished(); event LogUserAdded(address user); event LogUserRemoved(address user); constructor() public { setRate(1); _totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); owner = msg.sender; } function () public payable { revert(); } function createTokens() payable public { require(msg.value > 0); require(whitelisted[msg.sender]); uint256 tokens = msg.value.mul(RATE); balances[msg.sender] = balances[msg.sender].add(tokens); _totalSupply = _totalSupply.add(tokens); owner.transfer(msg.value); } function totalSupply() constant public returns (uint256) { return _totalSupply; } function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool success) { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); require( balances[msg.sender] >= _value && _value > 0 && !blockListed[_to] && !blockListed[msg.sender] ); // Save this for an assertion in the future uint previousBalances = balances[msg.sender] + balances[_to]; balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); // Subtract from the sender balances[_to] = SafeMath.add(balances[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[msg.sender] + balances[_to] == previousBalances); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require( balances[msg.sender] >= _value && balances[_from] >= _value && _value > 0 && whitelisted[msg.sender] && !blockListed[_to] && !blockListed[msg.sender] ); balances[_from] = SafeMath.sub(balances[_from], _value); // Subtract from the sender balances[_to] = SafeMath.add(balances[_to], _value); // Add the same to the recipient allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; whitelisted[_spender] = true; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remianing) { return allowed[_owner][_spender]; } function getRate() public constant returns (uint256) { return RATE; } function setRate(uint256 _rate) public returns (bool success) { RATE = _rate; return true; } modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint(address _to, uint256 _amount) hasMintPermission canMint public returns (bool) { uint256 tokens = _amount.mul(RATE); require( _currentSupply.add(tokens) < MAXUM_SUPPLY && whitelisted[msg.sender] && !blockListed[_to] ); if (_currentSupply >= INITIAL_SUPPLY) { _totalSupply = _totalSupply.add(tokens); } _currentSupply = _currentSupply.add(tokens); balances[_to] = balances[_to].add(tokens); emit Mint(_to, tokens); emit Transfer(address(0), _to, tokens); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } // Add a user to the whitelist function addUser(address user) onlyOwner public { whitelisted[user] = true; emit LogUserAdded(user); } // Remove an user from the whitelist function removeUser(address user) onlyOwner public { whitelisted[user] = false; emit LogUserRemoved(user); } function getCurrentOwnerBallence() constant public returns (uint256) { return balances[msg.sender]; } function addBlockList(address wallet) onlyOwner public { blockListed[wallet] = true; } function removeBlockList(address wallet) onlyOwner public { blockListed[wallet] = false; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); // Subtract from the sender _totalSupply = SafeMath.sub(_totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance _totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } function freeze(uint256 _value) onlyOwner public returns (bool success) { if (balances[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.add(freezeOf[msg.sender], _value); // Updates totalSupply emit Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) onlyOwner public returns (bool success) { if (freezeOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); freezeOf[msg.sender] = SafeMath.sub(freezeOf[msg.sender], _value); // Subtract from the sender balances[msg.sender] = SafeMath.add(balances[msg.sender], _value); emit Unfreeze(msg.sender, _value); return true; } }
Subtract from the sender
freezeOf[msg.sender] = SafeMath.sub(freezeOf[msg.sender], _value);
5,501,043
[ 1, 4625, 348, 7953, 560, 30, 225, 2592, 1575, 628, 326, 5793, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16684, 951, 63, 3576, 18, 15330, 65, 273, 14060, 10477, 18, 1717, 12, 29631, 951, 63, 3576, 18, 15330, 6487, 389, 1132, 1769, 15604, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./OwnerRole.sol"; /// @title BurnerRole Contract /// @notice Only administrators can update the burner roles /// @dev Keeps track of burners and can check if an account is authorized contract BurnerRole is OwnerRole { event BurnerAdded(address indexed addedBurner, address indexed addedBy); event BurnerRemoved( address indexed removedBurner, address indexed removedBy ); Role private _burners; /// @dev Modifier to make a function callable only when the caller is a burner modifier onlyBurner() { require( isBurner(msg.sender), "BurnerRole: caller does not have the Burner role" ); _; } /// @dev Public function returns `true` if `account` has been granted a burner role function isBurner(address account) public view returns (bool) { return _has(_burners, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a burner /// @param account The address that is guaranteed burner authorization function _addBurner(address account) internal { _add(_burners, account); emit BurnerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a burner /// @param account The address removed as a burner function _removeBurner(address account) internal { _remove(_burners, account); emit BurnerRemoved(account, msg.sender); } /// @dev Public function that adds an address as a burner /// @param account The address that is guaranteed burner authorization function addBurner(address account) external onlyOwner { _addBurner(account); } /// @dev Public function that removes an account from being a burner /// @param account The address removed as a burner function removeBurner(address account) external onlyOwner { _removeBurner(account); } uint256[49] private __gap; }
@dev Public function returns `true` if `account` has been granted a burner role
function isBurner(address account) public view returns (bool) { return _has(_burners, account); }
5,361,957
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 7224, 445, 1135, 1375, 3767, 68, 309, 1375, 4631, 68, 711, 2118, 17578, 279, 18305, 264, 2478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 27057, 321, 264, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 5332, 24899, 70, 321, 414, 16, 2236, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view {
1,019,073
[ 1, 4625, 348, 7953, 560, 30, 4590, 18708, 882, 18264, 423, 2192, 1360, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2018, 7132, 12, 1080, 3778, 293, 20, 16, 1758, 293, 21, 16, 2254, 293, 22, 16, 533, 3778, 293, 23, 13, 2713, 1476, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xC68a8c6A29412827018A23058E0CEd132889Ea48/sources/src/strategies/PancakeSwapPulseStrategyV2.sol
@param positionManager_ PancakeSwap v3 NonfungiblePositionManager
constructor(IPancakeNonfungiblePositionManager positionManager_) { require(address(positionManager_) != address(0), ExceptionsLibrary.ADDRESS_ZERO); positionManager = positionManager_; }
16,471,529
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 891, 1754, 1318, 67, 12913, 23780, 12521, 331, 23, 3858, 12125, 75, 1523, 2555, 1318, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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67, 13, 480, 1758, 12, 20, 3631, 12781, 9313, 18, 15140, 67, 24968, 1769, 203, 3639, 1754, 1318, 273, 1754, 1318, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8b2185bB3750cD6eD1Ced62a8E415bf05C40644e/sources/localhost/protocol/extensions/adapters/AUniswapV2.sol
callerIsDragoOwner();canTradeTokenOnExchange(UNISWAP_V2_ROUTER_ADDRESS, path[0]);
function swapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts) { _safeApprove(path[0], UNISWAP_V2_ROUTER_ADDRESS, 2**256 -1); amounts = IUniswapV2Router02(UNISWAP_V2_ROUTER_ADDRESS).swapExactTokensForETH( amountIn, amountOutMin, path, deadline ); if (Token(path[0]).allowance(address(this), UNISWAP_V2_ROUTER_ADDRESS) > uint256(0)) { _safeApprove(path[0], UNISWAP_V2_ROUTER_ADDRESS, uint256(0)); } }
4,890,514
[ 1, 4625, 348, 7953, 560, 30, 4894, 2520, 11728, 83, 5541, 5621, 4169, 22583, 1345, 1398, 11688, 12, 2124, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 67, 15140, 16, 589, 63, 20, 19226, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 14332, 5157, 1290, 1584, 44, 12, 203, 3639, 2254, 3844, 382, 16, 203, 3639, 2254, 3844, 1182, 2930, 16, 203, 3639, 1758, 8526, 745, 892, 589, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 8526, 3778, 30980, 13, 203, 565, 288, 203, 3639, 389, 4626, 12053, 537, 12, 803, 63, 20, 6487, 5019, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 67, 15140, 16, 576, 636, 5034, 300, 21, 1769, 203, 3639, 30980, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 2124, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 67, 15140, 2934, 22270, 14332, 5157, 1290, 1584, 44, 12, 203, 5411, 3844, 382, 16, 203, 5411, 3844, 1182, 2930, 16, 203, 5411, 589, 16, 203, 5411, 14096, 203, 3639, 11272, 203, 3639, 309, 261, 1345, 12, 803, 63, 20, 65, 2934, 5965, 1359, 12, 2867, 12, 2211, 3631, 5019, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 67, 15140, 13, 405, 2254, 5034, 12, 20, 3719, 288, 203, 5411, 389, 4626, 12053, 537, 12, 803, 63, 20, 6487, 5019, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 67, 15140, 16, 2254, 5034, 12, 20, 10019, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x273bb54f21E23CeA5312bE2623ED97C25CBd6F0D/sources/data/source/services/ServiceRegistry.sol
The contract can disappear.
selfdestruct(_to);
1,912,360
[ 1, 4625, 348, 7953, 560, 30, 225, 1021, 6835, 848, 1015, 438, 17964, 18, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 365, 5489, 8813, 24899, 869, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /* Fully commented standard ERC721 Distilled from OpenZeppelin Docs Base for Building ERC721 by Martin McConnell All the utility without the fluff. */ interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } 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`. 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; } 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); } 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); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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); } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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); } } // ****************************************************************************************************************************** // ************************************************** Start of Main Contract *************************************************** // ****************************************************************************************************************************** contract goldenEaglez is IERC721, Ownable { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // 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; // PandaBugz Specific Functionality bool public mintActive; bool private reentrancyLock; uint256 public price; uint256 public totalTokens = 10000; uint256 public numberMinted; uint256 private _maxMintsPerTxn; uint256 public earlyMint; mapping(address => bool) _whitelist; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "Golden Eaglez Kartel"; _symbol = "GEK"; _baseURI = "https://herodev.mypinata.cloud/ipfs/QmUBv8AVVD3bh76J364ATqL22ZsuWmovuY2kSKEkCovGqd/"; price = 8 * (10 ** 16); // 0.08eth _maxMintsPerTxn = 20; earlyMint = 1500; } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == goldenEaglez.onERC721Received.selector; } function withdraw() external onlyOwner { uint256 sendAmount = address(this).balance; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } function ownerMint(address _to, uint256 qty) external onlyOwner{ uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch numberMinted += qty; for(uint256 i = 0; i < qty; i++) { _safeMint(_to, mintSeedValue + i); } } function mint(address _to, uint256 qty) external payable { require(msg.value >= qty * price, "Mint: Insufficient Funds"); require(qty <= _maxMintsPerTxn, "Mint: Above Transaction Threshold!"); if (mintActive) { require(qty < totalTokens - numberMinted, "Mint: Not enough NFTs remaining to fill order"); } else { require(qty < earlyMint - numberMinted, "Mint: Not enough NFTs remaining to fill order"); require(_whitelist[_msgSender()]); } require(!reentrancyLock); //Lock up this whole function just in case reentrancyLock = true; uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch numberMinted += qty; //Handle ETH transactions uint256 cashIn = msg.value; uint256 cashChange = cashIn - (qty * price); //send tokens for(uint256 i = 0; i < qty; i++) { _safeMint(_to, mintSeedValue + i); } if (cashChange > 0){ (bool success, ) = msg.sender.call{value: cashChange}(""); require(success, "Mint: unable to send change to user"); } reentrancyLock = false; } function burn(uint256 tokenID) external { require(_msgSender() == ownerOf(tokenID)); _burn(tokenID); } //////////////////// Setters and Getters function whiteList(address account) external onlyOwner { _whitelist[account] = true; } function whiteListMany(address[] memory accounts) external onlyOwner { for (uint256 i; i < accounts.length; i++) { _whitelist[accounts[i]] = true; } } function checkWhitelist(address testAddress) external view returns (bool) { if (_whitelist[testAddress] == true) { return true; } return false; } function setMaximumMintThreshold(uint256 maxMints) external onlyOwner { _maxMintsPerTxn = maxMints; } function viewMaxMintThreshold() external view onlyOwner returns(uint256) { return _maxMintsPerTxn; } function setBaseURI(string memory newURI) public onlyOwner { _baseURI = newURI; } function setActive(bool setBoolValue) public onlyOwner { mintActive = setBoolValue; } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setTotalTokens(uint256 numTokens) public onlyOwner { totalTokens = numTokens; } function getBalance(address tokenAddress) view external returns (uint256) { return _balances[tokenAddress]; } // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory){ //Fill out file location here later require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory tokenuri = string(abi.encodePacked(_baseURI, tokenId.toString(), ".json")); return tokenuri; } // ******************************************************************************* /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "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 != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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(msg.sender, 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(msg.sender, 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 = 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 = 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(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(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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // *********************** ERC721 Token Receiver ********************** /** * @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) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @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 {} receive() external payable {} fallback() external payable {} }
Store the starting value of the mint batch
uint256 mintSeedValue = numberMinted;
153,372
[ 1, 4625, 348, 7953, 560, 30, 4994, 326, 5023, 460, 434, 326, 312, 474, 2581, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 312, 474, 12702, 620, 273, 1300, 49, 474, 329, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return Returns two values: /// - assetAmountInternal which is the converted asset amount accounting for transfer fees /// - assetAmountTransferred which is the internal precision amount transferred into the account function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetAmountInternal = token.convertToInternal(assetAmountExternal); // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Tokens that are not mintable like cTokens will be deposited as assetTokens require(assetToken.tokenType == TokenType.cToken || assetToken.tokenType == TokenType.cETH); // dev: deposit underlying token invalid token type int256 assetTokensReceivedExternalPrecision = assetToken.mint(SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // It's crucial that incentives are claimed before we do any sort of nToken transfer to prevent gaming // of the system. This method will update the lastClaimTime time and lastIntegralTotalSupply in balance // state in place. Incentives.claimIncentives(balanceState, account); // nTokens are within the notional system so we can update balances directly. balanceState.storedNTokenBalance = balanceState .storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // underlyingAmountExternal is converted from uint to int inside redeem, must be positive int256 underlyingAmountExternal = assetToken.redeem( underlyingToken, uint256(assetTransferAmountExternal.neg()) ); // Withdraws the underlying amount out to the destination account actualTransferAmountExternal = underlyingToken.transfer( account, underlyingAmountExternal.neg() ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { actualTransferAmountExternal = assetToken.transfer(account, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, lastClaimIntegralSupply ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, lastClaimIntegralSupply ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow require(lastClaimTime <= type(uint32).max); // dev: last claim time overflow balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.cashBalance = int88(cashBalance); // Last claim supply is stored in a "floating point" storage slot that does not maintain exact precision but // is also not limited by storage overflows. `packTo56Bits` will ensure that the the returned value will fit // in 56 bits (7 bytes) balanceStorage.packedLastClaimIntegralSupply = FloatingPoint56.packTo56Bits(lastClaimIntegralSupply); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; lastClaimIntegralSupply = FloatingPoint56.unpackFrom56Bits(balanceStorage.packedLastClaimIntegralSupply); cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.lastClaimIntegralSupply = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the lastClaimTime and lastClaimIntegralSupply function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256) { uint256 incentivesClaimed = Incentives.claimIncentives(balanceState, account); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply ); return incentivesClaimed; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Sets the account context of a given account function enableBitmapForAccount( AccountContext memory accountContext, address account, uint16 currencyId, uint256 blockTime ) internal view { // Allow setting the currency id to zero to turn off bitmap require(currencyId <= Constants.MAX_CURRENCIES, "AC: invalid currency id"); if (isBitmapEnabled(accountContext)) { // Account cannot change their bitmap if they have assets set bytes32 ifCashBitmap = BitmapAssetsHandler.getAssetsBitmap(account, accountContext.bitmapCurrencyId); require(ifCashBitmap == 0, "AC: cannot have assets"); } else { require(accountContext.assetArrayLength == 0, "AC: cannot have assets"); // Account context also cannot have negative cash debts require(accountContext.hasDebt == 0x00, "AC: cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); } accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../external/SettleAssetsExternal.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @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 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @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 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function _getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) private view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = _getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } /// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming /// nTokens to its underlying assets. function reduceifCashAssetsProportional( address account, uint256 currencyId, uint256 nextSettleTime, int256 tokensToRedeem, int256 totalSupply ) internal returns (PortfolioAsset[] memory) { // It is not possible to redeem the entire token supply because some liquidity tokens must remain // in the liquidity token portfolio in order to re-initialize markets. require(tokensToRedeem < totalSupply, "Cannot redeem"); bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; int256 notional = fCashSlot.notional; int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply); int256 finalNotional = notional.sub(notionalToTransfer); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notionalToTransfer; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "interfaces/chainlink/AggregatorV2V3Interface.sol"; import "interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // The last integral supply amount when tokens were claimed uint256 lastClaimIntegralSupply; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // The total integral supply of the nToken at the last claim time packed into // 56 bits. There is some loss of precision here but it is acceptable uint56 packedLastClaimIntegralSupply; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 lastClaimIntegralSupply; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // NOTE: this address is hardcoded in the library, must update this on deployment address constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 96 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(blockTime != 0 && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; 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 result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `buildMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, nTokenTotalSupply, AssetRate, ExchangeRate } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nTokenHandler.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @dev Notional incentivizes nTokens using the formula: /// incentivesToClaim = (tokenBalance / totalSupply) * emissionRatePerYear * proRataYears /// where proRataYears is: /// (timeSinceLastClaim / YEAR) * INTERNAL_TOKEN_PRECISION /// @return (emissionRatePerYear * proRataYears), decimal basis is (1e8 * 1e8 = 1e16) function _getIncentiveRate(uint256 timeSinceLastClaim, uint256 emissionRatePerYear) private pure returns (uint256) { // (timeSinceLastClaim * INTERNAL_TOKEN_PRECISION) / YEAR uint256 proRataYears = timeSinceLastClaim.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)).div(Constants.YEAR); return proRataYears.mul(emissionRatePerYear); } /// @notice Calculates the claimable incentives for a particular nToken and account function calculateIncentivesToClaim( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply, uint256 blockTime, uint256 integralTotalSupply ) internal view returns (uint256) { if (lastClaimTime == 0 || lastClaimTime >= blockTime) return 0; // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); // No overflow here, checked above uint256 timeSinceLastClaim = blockTime - lastClaimTime; uint256 incentiveRate = _getIncentiveRate( timeSinceLastClaim, // Convert this to the appropriate denomination, emissionRatePerYear is denominated // in whole tokens emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) ); // Returns the average supply between now and the previous mint time using the integral of the total // supply. uint256 avgTotalSupply = integralTotalSupply.sub(lastClaimIntegralSupply).div(timeSinceLastClaim); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } /// @notice Incentives must be claimed every time nToken balance changes function claimIncentives(BalanceState memory balanceState, address account) internal returns (uint256) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will set the new supply and return the previous integral total supply uint256 integralTotalSupply = nTokenHandler.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); uint256 incentivesToClaim = calculateIncentivesToClaim( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply, blockTime, integralTotalSupply ); balanceState.lastClaimTime = blockTime; balanceState.lastClaimIntegralSupply = integralTotalSupply; if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); return incentivesToClaim; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "interfaces/compound/CErc20Interface.sol"; import "interfaces/compound/CEtherInterface.sol"; import "interfaces/IEIP20NonStandard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken) { // Set the approval for the underlying so that we can mint cTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( tokenStorage.tokenAddress, type(uint256).max ); checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /// @notice This method only works with cTokens, it's unclear how we can make this more generic function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 startingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); uint256 success; if (token.tokenType == TokenType.cToken) { success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); } else if (token.tokenType == TokenType.cETH) { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } else { revert(); // dev: non mintable token } require(success == Constants.COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); uint256 endingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } function redeem( Token memory assetToken, Token memory underlyingToken, uint256 assetAmountExternal ) internal returns (int256) { uint256 startingBalance; if (assetToken.tokenType == TokenType.cETH) { startingBalance = address(this).balance; } else if (assetToken.tokenType == TokenType.cToken) { startingBalance = IERC20(underlyingToken.tokenAddress).balanceOf(address(this)); } else { revert(); // dev: non redeemable failure } uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == Constants.COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance; if (assetToken.tokenType == TokenType.cETH) { endingBalance = address(this).balance; } else { endingBalance = IERC20(underlyingToken.tokenAddress).balanceOf(address(this)); } // Underlying token external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, int256 netTransferExternal ) internal returns (int256) { if (netTransferExternal > 0) { // Deposits must account for transfer fees. netTransferExternal = _deposit(token, account, uint256(netTransferExternal)); } else if (token.tokenType == TokenType.Ether) { require(netTransferExternal <= 0); // dev: cannot deposit ether address payable accountPayable = payable(account); // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. accountPayable.transfer(uint256(netTransferExternal.neg())); } else { safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } return netTransferExternal; } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; if (token.hasTransferFee) { startingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); } safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { endingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { safeTransferOut(Constants.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } function safeTransferOut( address token, address account, uint256 amount ) private { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) private { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() private pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./markets/CashGroup.sol"; import "./markets/AssetRate.sol"; import "./valuation/AssetHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; import "./balances/BalanceHandler.sol"; import "../math/SafeInt256.sol"; library nTokenHandler { using AssetRate for AssetRateParameters; using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // TODO: how many storage reads is this? currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Retrieves the nToken supply factors without any updates or calculations function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 integralTotalSupply, uint256 lastSupplyChangeTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The integral total supply // must be updated given the block time. Use `calculateIntegralTotalSupply` instead integralTotalSupply = nTokenStorage.integralTotalSupply; lastSupplyChangeTime = nTokenStorage.lastSupplyChangeTime; } /// @notice Retrieves stored total supply factors and function calculateIntegralTotalSupply(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 integralTotalSupply, uint256 lastSupplyChangeTime ) { ( totalSupply, integralTotalSupply, lastSupplyChangeTime ) = getStoredNTokenSupplyFactors(tokenAddress); // Initialize last supply change time if it has not been set. if (lastSupplyChangeTime == 0) lastSupplyChangeTime = blockTime; require(blockTime >= lastSupplyChangeTime); // dev: invalid block time // Add to the integral total supply the total supply of tokens multiplied by the time that the total supply // has been the value. This will part of the numerator for the average total supply calculation during // minting incentives. integralTotalSupply = uint256(int256(integralTotalSupply).add( int256(totalSupply).mul(int256(blockTime - lastSupplyChangeTime)) )); require(integralTotalSupply >= 0 && integralTotalSupply < type(uint128).max); // dev: integral total supply overflow require(blockTime < type(uint32).max); // dev: last supply change supply overflow } /// @notice Updates the nToken token supply amount when minting or redeeming. function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 integralTotalSupply, /* uint256 lastSupplyChangeTime */ ) = calculateIntegralTotalSupply(tokenAddress, blockTime); if (netChange != 0) { // If the totalSupply will change then we store the new total supply, the integral total supply and the // current block time. We know that this int256 conversion will not overflow because totalSupply is stored // as a uint96 and checked in the next line. int256 newTotalSupply = int256(totalSupply).add(netChange); require(newTotalSupply >= 0 && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflows checked in calculateIntegralTotalSupply nTokenStorage.integralTotalSupply = uint128(integralTotalSupply); nTokenStorage.lastSupplyChangeTime = uint32(blockTime); } return integralTotalSupply; } function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* integralTotalSupply */, /* lastSupplyChangeTime */ ) = getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* lastClaimIntegralSupply */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // Since we are not doing a risk adjusted valuation here we do not need to net off residual fCash // balances in the future before discounting to present. If we did, then the ifCash assets would // have to be in the portfolio array first. PV here is denominated in asset cash terms, not in // underlying terms. { MarketParameters memory market; for (uint256 i; i < nToken.portfolioState.storedAssets.length; i++) { // NOTE: getLiquidityTokenValue can rewrite fCash values in memory, however, that does not // happen in this call because there are no fCash values in the nToken portfolio. (int256 assetCashClaim, int256 pv) = AssetHandler.getLiquidityTokenValue( i, nToken.cashGroup, market, nToken.portfolioState.storedAssets, blockTime, false ); totalAssetPV = totalAssetPV.add(assetCashClaim); totalUnderlyingPV = totalUnderlyingPV.add(pv); } } // Then iterate over bitmapped assets and get present value // prettier-ignore ( int256 bitmapPv, /* hasDebt */ ) = BitmapAssetsHandler.getifCashNetPresentValue( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false ); totalUnderlyingPV = totalUnderlyingPV.add(bitmapPv); // Return the total present value denominated in asset terms totalAssetPV = totalAssetPV .add(nToken.cashGroup.assetRate.convertFromUnderlying(totalUnderlyingPV)) .add(nToken.cashBalance); return totalAssetPV; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external; /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } }
prettier-ignore prettier-ignore prettier-ignore
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); ( uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); ( uint256 totalSupply, ) = getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); ( nToken.cashBalance, ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
309,903
[ 1, 4625, 348, 7953, 560, 30, 225, 675, 748, 2453, 17, 6185, 675, 748, 2453, 17, 6185, 675, 748, 2453, 17, 6185, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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639, 290, 1345, 18, 2316, 1887, 273, 290, 1345, 1887, 12, 7095, 548, 1769, 203, 3639, 261, 203, 5411, 2254, 5034, 1142, 11459, 950, 16, 203, 5411, 2254, 28, 3310, 1076, 1782, 16, 203, 5411, 1731, 25, 1472, 203, 3639, 262, 273, 11069, 1345, 1042, 12, 82, 1345, 18, 2316, 1887, 1769, 203, 203, 3639, 261, 203, 5411, 2254, 5034, 2078, 3088, 1283, 16, 203, 3639, 262, 273, 15818, 72, 50, 1345, 3088, 1283, 23535, 12, 82, 1345, 18, 2316, 1887, 1769, 203, 203, 3639, 290, 1345, 18, 2722, 11459, 950, 273, 1142, 11459, 950, 31, 203, 3639, 290, 1345, 18, 4963, 3088, 1283, 273, 509, 5034, 12, 4963, 3088, 1283, 1769, 203, 3639, 290, 1345, 18, 3977, 273, 1472, 31, 203, 203, 3639, 290, 1345, 18, 28962, 1119, 273, 6008, 10270, 1503, 18, 3510, 17163, 1119, 12, 203, 5411, 290, 1345, 18, 2316, 1887, 16, 203, 5411, 3310, 1076, 1782, 16, 203, 5411, 374, 203, 3639, 11272, 203, 203, 3639, 261, 203, 5411, 290, 1345, 18, 71, 961, 13937, 16, 203, 3639, 262, 273, 30918, 1503, 18, 588, 13937, 3245, 12, 82, 1345, 18, 2316, 1887, 16, 5462, 548, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma ton-solidity >= 0.38.2; /// @title LiquiSOR\DEXRoot /// @author laugan /// @notice Factory contract for pool deployment, adding TIP-3 tokens and overall DEX management pragma AbiHeader time; pragma AbiHeader expire; pragma AbiHeader pubkey; import "../std/lib/TVM.sol"; import "../dex/lib/DEX.sol"; import "../dex/DEXPool.sol"; import "../dex/int/IDEXRoot.sol"; import "../tip3/int/ITIP3Root.sol"; contract DEXRoot is IDEXRoot { /* Attributes */ uint8 static iteration; mapping(address => ITIP3RootMetadata.TokenDetails) tokens_; // key - root, value - symbol TvmCell liqWalletCode_; TvmCell poolCode_; address governance_; uint64 constant DEPLOY_FEE = 1.6 ton; uint64 constant USAGE_FEE = 0.2 ton; uint64 constant MESSAGE_FEE = 0.05 ton; uint64 constant CALLBACK_FEE = 0.01 ton; uint128 constant INITIAL_GAS = 0.5 ton; address constant ZERO_ADDRESS = address.makeAddrStd(0, 0); /// @dev Contract constructor. constructor() public { require(msg.pubkey() == tvm.pubkey(), DEX.ERROR_NOT_AUTHORIZED); tvm.accept(); } /* Gatters */ function getTokenExists(address rootAddress) external override view returns(bool) { return _checkToken(rootAddress); } function getPoolAddress(address _tokenA, address _tokenB) external override view returns (address poolAddress) { (address tokenX, address tokenY) = _pairRoutine(_tokenA, _tokenB); poolAddress = _expectedAddress(tokenX, tokenY); } /* User methods */ // import of tokens by users (requires value) function importToken(address _rootAddr) external override onlyOwnerAcceptOrPay { ITIP3RootMetadata(_rootAddr).callTokenInfo{ callback: DEXRoot.onGetInfo, value: USAGE_FEE + USAGE_FEE }(); //tokens_.add(_rootAddr, symbol); } /// Function for deployment of pair pools by users (requires value) function deployPool(address _tokenA, address _tokenB) external override onlyOwnerAcceptOrPay returns(address poolAddress) { // check enough value with message!!! //require(msg.value >= DEX.POOL_DEPLOY_FEE, DEX.ERROR_NOT_ENOUGH_VALUE); // token pair routine (address tokenX, address tokenY) = _pairRoutine(_tokenA, _tokenB); //(address walletX, address walletY) = _tokenA < _tokenB ? (_walletA, _walletB) : (_walletB, _walletA); // deploy pair pool contract poolAddress = new DEXPool { code: poolCode_, value: DEPLOY_FEE + DEPLOY_FEE + DEPLOY_FEE + USAGE_FEE + USAGE_FEE + USAGE_FEE, pubkey: 0, varInit: { dex_: address(this), name_: _pairName(tokenX, tokenY), symbol_: _pairSymbol(tokenX, tokenY), code_: liqWalletCode_, tokenX_:tokenX, tokenY_:tokenY } }(tokens_.fetch(tokenX).get(), tokens_.fetch(tokenY).get()); //(walletX, walletY, tokens_.fetch(tokenX).get().code, tokens_.fetch(tokenY).get().code); // constructor params //_pairName(tokenX, tokenY), return poolAddress; } /* Owner/Governance methods */ function updatePoolCode(TvmCell _cell) external onlyOwnerAcceptOrPay { //require(cellHash == tvm.hash(_cell), ERROR_WRONG_CODE_CRC); poolCode_ = _cell; } function updateLiqWalletCode(TvmCell _cell) external onlyOwnerAcceptOrPay { //require(cellHash == tvm.hash(_cell), ERROR_WRONG_CODE_CRC); liqWalletCode_ = _cell; } function deployGovernance(address _govAddress) external onlyOwnerAcceptOrPay { require(_govAddress != ZERO_ADDRESS, DEX.ERROR_WRONG_VALUE); governance_ = _govAddress; } /* Callbacks */ // callback from TIP-3 token root function onGetInfo(ITIP3RootMetadata.TokenDetails details) public { //tvm.accept(); tokens_.add(msg.sender, details); } /* Private part */ modifier internalOnlyPay() { require(msg.sender != ZERO_ADDRESS && msg.value >= USAGE_FEE,DEX.ERROR_NOT_ENOUGH_VALUE); _reserveGas(); _; // BODY msg.sender.transfer({ value: 0, flag: TVM.FLAG_ALL_BALANCE }); } // Modifier for governance functions // It checks for owner public key until governance is deployed, // then it accepts only governance' decisions // At the end, sends back gas if value was attached modifier onlyOwnerAcceptOrPay() { require(_isOwner(), DEX.ERROR_NOT_AUTHORIZED); if (msg.sender != ZERO_ADDRESS) { require(msg.value >= USAGE_FEE,DEX.ERROR_NOT_ENOUGH_VALUE); _reserveGas(); } else { tvm.accept(); } _; // BODY if (msg.sender != ZERO_ADDRESS) { msg.sender.transfer({ value: 0, flag: TVM.FLAG_ALL_BALANCE }); } } function _reserveGas() internal inline returns (bool) { tvm.rawReserve(math.max(INITIAL_GAS, address(this).balance - msg.value), 2); } // after deployment of governance, you're not the owner anymore! function _isOwner() internal inline view returns (bool) { return ( (governance_ != ZERO_ADDRESS && msg.sender == governance_) || (governance_ == ZERO_ADDRESS && msg.pubkey() == tvm.pubkey()) ); } function _pairRoutine(address _tokenA, address _tokenB) private inline view returns (address tokenX, address tokenY) { // token pair routine require(_checkToken(_tokenA) && _checkToken(_tokenB),DEX.ERROR_UNKNOWN_TOKEN); require(_tokenA != _tokenB, DEX.ERROR_IDENTICAL_TOKENS); (tokenX, tokenY) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA); } function _checkToken(address _token) private inline view returns(bool) { return tokens_.fetch(_token).hasValue(); } function _pairName(address _tokenX, address _tokenY) private view returns (bytes) { // format() isn't recommended on-chain, but append() isn't usable now, so using format() string str = format("LiquiSOR({}:{})", string(tokens_.fetch(_tokenX).get().name), string(tokens_.fetch(_tokenX).get().name)); return bytes(str); } function _pairSymbol(address _tokenX, address _tokenY) private view returns (string) { // format() isn't recommended on-chain, but append() isn't usable now, so using format() string str = format("LIQ({}:{})", string(tokens_.fetch(_tokenX).get().symbol), string(tokens_.fetch(_tokenX).get().symbol)); return bytes(str); } function _expectedAddress(address _tokenX, address _tokenY) internal inline view returns (address) { //bytes name = abi.encodePacked("0x4c4951534f523a474c443a504c54");//bytes(_pairName(tokenX, tokenY)); //bytes symbol = abi.encodePacked("0x4c4951534f523a474c443a504c54");//bytes(_pairSymbol(tokenX, tokenY)); TvmCell stateInit = tvm.buildStateInit({ contr: DEXPool, varInit: { dex_: address(this), name_: _pairName(_tokenX, _tokenY), symbol_: _pairSymbol(_tokenX, _tokenY), code_: liqWalletCode_, tokenX_:_tokenX, tokenY_:_tokenY }, code: poolCode_ }); return address.makeAddrStd(0, tvm.hash(stateInit)); } }
require(cellHash == tvm.hash(_cell), ERROR_WRONG_CODE_CR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0, 0, 0, 0, 0, 0, 0, 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, 48, 18638, 16936, 1085, 12, 56, 3489, 4020, 389, 3855, 13, 3903, 1338, 5541, 5933, 1162, 9148, 288, 203, 1377, 4501, 85, 16936, 1085, 67, 273, 389, 3855, 31, 203, 565, 289, 1377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xBb4BAB913E3C001b6C30059B398c0797ded84d34/sources/contracts/deploy/DSProxyContract.sol
use the proxy to execute calldata _data on contract _code deploy contract & store its address in cache
function execute( bytes memory _code, bytes memory _data, bool bools ) external payable returns (address target, bytes memory response) { target = cache.read(_code); if (target == address(0)) { target = cache.write(_code); } response = execute(target, _data); }
4,876,342
[ 1, 4625, 348, 7953, 560, 30, 225, 999, 326, 2889, 358, 1836, 745, 892, 389, 892, 603, 6835, 389, 710, 7286, 6835, 473, 1707, 2097, 1758, 316, 1247, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 12, 203, 3639, 1731, 3778, 389, 710, 16, 203, 3639, 1731, 3778, 389, 892, 16, 203, 3639, 1426, 1426, 87, 203, 565, 262, 3903, 8843, 429, 1135, 261, 2867, 1018, 16, 1731, 3778, 766, 13, 288, 203, 3639, 1018, 273, 1247, 18, 896, 24899, 710, 1769, 203, 3639, 309, 261, 3299, 422, 1758, 12, 20, 3719, 288, 203, 5411, 1018, 273, 1247, 18, 2626, 24899, 710, 1769, 203, 3639, 289, 203, 203, 3639, 766, 273, 1836, 12, 3299, 16, 389, 892, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.8.0; interface IHswapV2Callee { function hswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } interface IMdexFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeToRate() external view returns (uint256); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setFeeToRate(uint256) external; function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1); function pairFor(address tokenA, address tokenB) external view returns (address pair); function getReserves(address tokenA, address tokenB) external view returns (uint256 reserveA, uint256 reserveB); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IMdexPair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function price(address token, uint256 baseDecimal) external view returns (uint256); function initialize(address, address) external; } contract MdexERC20 { using SafeMath for uint256; string public constant name = 'HSwap LP Token'; string public constant symbol = 'HMDX'; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); constructor() public { uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external returns (bool) { if (allowance[from][msg.sender] != uint256(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, 'MdexSwap: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'MdexSwap: INVALID_SIGNATURE'); _approve(owner, spender, value); } } contract MdexPair is MdexERC20 { using SafeMath for uint256; using UQ112x112 for uint224; uint256 public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint256 private unlocked = 1; modifier lock() { require(unlocked == 1, 'MdexSwap: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer( address token, address to, uint256 value ) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'MdexSwap: TRANSFER_FAILED'); } event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); 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, 'MdexSwap: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update( uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1 ) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'MdexSwap: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IMdexFactory(factory).feeTo(); feeOn = feeTo != address(0); uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = SafeMath.sqrt(uint256(_reserve0).mul(_reserve1)); uint256 rootKLast = SafeMath.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(IMdexFactory(factory).feeToRate()).add(rootKLast); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint256 liquidity) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); uint256 amount0 = balance0.sub(_reserve0); uint256 amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = SafeMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'MdexSwap: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint256 amount0, uint256 amount1) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint256 balance0 = IERC20(_token0).balanceOf(address(this)); uint256 balance1 = IERC20(_token1).balanceOf(address(this)); uint256 liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'MdexSwap: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external lock { require(amount0Out > 0 || amount1Out > 0, 'MdexSwap: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'MdexSwap: INSUFFICIENT_LIQUIDITY'); uint256 balance0; uint256 balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'MdexSwap: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IHswapV2Callee(to).hswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'MdexSwap: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2), 'MdexSwap: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } function price(address token, uint256 baseDecimal) public view returns (uint256) { if ((token0 != token && token1 != token) || 0 == reserve0 || 0 == reserve1) { return 0; } if (token0 == token) { return uint256(reserve1).mul(baseDecimal).div(uint256(reserve0)); } else { return uint256(reserve0).mul(baseDecimal).div(uint256(reserve1)); } } } contract MdexFactory { using SafeMath for uint256; address public feeTo; address public feeToSetter; uint256 public feeToRate; bytes32 public initCodeHash; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint256); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; initCodeHash = keccak256(abi.encodePacked(type(MdexPair).creationCode)); } function allPairsLength() external view returns (uint256) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(tokenA != tokenB, 'MdexSwapFactory: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'MdexSwapFactory: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'MdexSwapFactory: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(MdexPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IMdexPair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external { require(msg.sender == feeToSetter, 'MdexSwapFactory: FORBIDDEN'); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external { require(msg.sender == feeToSetter, 'MdexSwapFactory: FORBIDDEN'); require(_feeToSetter != address(0), 'MdexSwapFactory: FeeToSetter is zero address'); feeToSetter = _feeToSetter; } function setFeeToRate(uint256 _rate) external { require(msg.sender == feeToSetter, 'MdexSwapFactory: FORBIDDEN'); require(_rate > 0, 'MdexSwapFactory: FEE_TO_RATE_OVERFLOW'); feeToRate = _rate.sub(1); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) public pure returns (address token0, address token1) { require(tokenA != tokenB, 'MdexSwapFactory: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'MdexSwapFactory: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address tokenA, address tokenB) public view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint256(keccak256(abi.encodePacked(hex'ff', address(this), keccak256(abi.encodePacked(token0, token1)), initCodeHash)))); } // fetches and sorts the reserves for a pair function getReserves(address tokenA, address tokenB) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IMdexPair(pairFor(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( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure returns (uint256 amountB) { require(amountA > 0, 'MdexSwapFactory: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'MdexSwapFactory: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public pure returns (uint256 amountOut) { require(amountIn > 0, 'MdexSwapFactory: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'MdexSwapFactory: INSUFFICIENT_LIQUIDITY'); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public pure returns (uint256 amountIn) { require(amountOut > 0, 'MdexSwapFactory: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'MdexSwapFactory: INSUFFICIENT_LIQUIDITY'); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(uint256 amountIn, address[] memory path) public view returns (uint256[] memory amounts) { require(path.length >= 2, 'MdexSwapFactory: INVALID_PATH'); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(uint256 amountOut, address[] memory path) public view returns (uint256[] memory amounts) { require(path.length >= 2, 'MdexSwapFactory: INVALID_PATH'); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } 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); } } library SafeMath { uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wad() public pure returns (uint256) { return WAD; } function ray() public pure returns (uint256) { return RAY; } 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function sqrt(uint256 a) internal pure returns (uint256 b) { if (a > 3) { b = a; uint256 x = a / 2 + 1; while (x < b) { b = x; x = (a / x + x) / 2; } } else if (a != 0) { b = 1; } } function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / WAD; } function wmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function rmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / RAY; } function rmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), RAY / 2) / RAY; } function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, WAD), b); } function wdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, RAY), b); } function rdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, RAY), b / 2) / b; } function wpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = WAD; while (n > 0) { if (n % 2 != 0) { result = wmul(result, x); } x = wmul(x, x); n /= 2; } return result; } function rpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = RAY; while (n > 0) { if (n % 2 != 0) { result = rmul(result, x); } x = rmul(x, x); n /= 2; } return result; } }
this low-level function should be called from a contract which performs important safety checks gas savings scope for _token{0,1}, avoids stack too deep errors optimistically transfer tokens optimistically transfer tokens scope for reserve{0,1}Adjusted, avoids stack too deep errors
function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external lock { require(amount0Out > 0 || amount1Out > 0, 'MdexSwap: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); require(amount0Out < _reserve0 && amount1Out < _reserve1, 'MdexSwap: INSUFFICIENT_LIQUIDITY'); uint256 balance0; uint256 balance1; { address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'MdexSwap: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); if (data.length > 0) IHswapV2Callee(to).hswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'MdexSwap: INSUFFICIENT_INPUT_AMOUNT'); { uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2), 'MdexSwap: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); }
14,092,432
[ 1, 4625, 348, 7953, 560, 30, 225, 333, 4587, 17, 2815, 445, 1410, 506, 2566, 628, 279, 6835, 1492, 11199, 10802, 24179, 4271, 16189, 4087, 899, 2146, 364, 389, 2316, 95, 20, 16, 21, 5779, 24192, 2110, 4885, 4608, 1334, 5213, 5846, 1230, 7412, 2430, 5213, 5846, 1230, 7412, 2430, 2146, 364, 20501, 95, 20, 16, 21, 97, 10952, 329, 16, 24192, 2110, 4885, 4608,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, 296, 49, 561, 12521, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15527, 67, 2192, 51, 5321, 8284, 203, 3639, 261, 11890, 17666, 389, 455, 6527, 20, 16, 2254, 17666, 389, 455, 6527, 21, 16, 262, 273, 31792, 264, 3324, 5621, 203, 3639, 2583, 12, 8949, 20, 1182, 411, 389, 455, 6527, 20, 597, 3844, 21, 1182, 411, 389, 455, 6527, 21, 16, 296, 49, 561, 12521, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 203, 3639, 2254, 5034, 11013, 20, 31, 203, 3639, 2254, 5034, 11013, 21, 31, 203, 3639, 288, 203, 5411, 1758, 389, 2316, 20, 273, 1147, 20, 31, 203, 5411, 1758, 389, 2316, 21, 273, 1147, 21, 31, 203, 5411, 2583, 12, 869, 480, 389, 2316, 20, 597, 358, 480, 389, 2316, 21, 16, 296, 49, 561, 12521, 30, 10071, 67, 4296, 8284, 203, 5411, 309, 261, 8949, 20, 1182, 405, 374, 13, 389, 4626, 5912, 24899, 2316, 20, 16, 358, 16, 3844, 20, 1182, 1769, 203, 5411, 309, 261, 8949, 21, 1182, 405, 374, 13, 389, 4626, 5912, 24899, 2316, 21, 16, 358, 16, 3844, 21, 1182, 1769, 203, 5411, 309, 261, 892, 18, 2469, 405, 374, 13, 467, 44, 22270, 58, 22, 3005, 11182, 12, 869, 2934, 4487, 91, 438, 58, 22, 1477, 12, 3576, 18, 15330, 16, 3844, 20, 1182, 16, 3844, 21, 1182, 16, 501, 1769, 203, 5411, 11013, 20, 273, 467, 654, 39, 3462, 24899, 2316, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 11013, 21, 273, 467, 654, 39, 3462, 24899, 2316, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 289, 203, 3639, 2254, 5034, 3844, 20, 382, 273, 11013, 20, 405, 389, 455, 6527, 20, 300, 3844, 20, 1182, 692, 11013, 20, 300, 261, 67, 455, 6527, 20, 300, 3844, 20, 1182, 13, 294, 374, 31, 203, 3639, 2254, 5034, 3844, 21, 382, 273, 11013, 21, 405, 389, 455, 6527, 21, 300, 3844, 21, 1182, 692, 11013, 21, 300, 261, 67, 455, 6527, 21, 300, 3844, 21, 1182, 13, 294, 374, 31, 203, 3639, 2583, 12, 8949, 20, 382, 405, 374, 747, 3844, 21, 382, 405, 374, 16, 296, 49, 561, 12521, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15934, 67, 2192, 51, 5321, 8284, 203, 3639, 288, 203, 5411, 2254, 5034, 11013, 20, 10952, 329, 273, 11013, 20, 18, 16411, 12, 18088, 2934, 1717, 12, 8949, 20, 382, 18, 16411, 12, 23, 10019, 203, 5411, 2254, 5034, 11013, 21, 10952, 329, 273, 11013, 21, 18, 16411, 12, 18088, 2934, 1717, 12, 8949, 21, 382, 18, 16411, 12, 23, 10019, 203, 5411, 2583, 12, 12296, 20, 10952, 329, 18, 16411, 12, 12296, 21, 10952, 329, 13, 1545, 2254, 5034, 24899, 455, 6527, 20, 2934, 16411, 24899, 455, 6527, 21, 2934, 16411, 12, 18088, 636, 22, 3631, 296, 49, 561, 12521, 30, 1475, 8284, 203, 3639, 289, 203, 203, 3639, 389, 2725, 12, 12296, 20, 16, 11013, 21, 16, 389, 455, 6527, 20, 16, 389, 455, 6527, 21, 1769, 203, 3639, 3626, 12738, 12, 3576, 18, 15330, 16, 3844, 20, 382, 16, 3844, 21, 382, 16, 3844, 20, 1182, 16, 3844, 21, 1182, 16, 358, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract BitUPToken is ERC20, Ownable { using SafeMath for uint; /*----------------- Token Information -----------------*/ string public constant name = "BitUP Token"; string public constant symbol = "BUT"; uint8 public decimals = 18; // (ERC20 API) Decimal precision, factor is 1e18 mapping (address => uint256) balances; // User's balances table mapping (address => mapping (address => uint256)) allowed; // User's allowances table /*----------------- Alloc Information -----------------*/ uint256 public totalSupply; uint256 public presaleSupply; // Pre-sale supply uint256 public angelSupply; // Angel supply uint256 public marketingSupply; // marketing supply uint256 public foundationSupply; // /Foundation supply uint256 public teamSupply; // Team supply uint256 public communitySupply; // Community supply uint256 public teamSupply6Months; //Amount of Team supply could be released after 6 months uint256 public teamSupply12Months; //Amount of Team supply could be released after 12 months uint256 public teamSupply18Months; //Amount of Team supply could be released after 18 months uint256 public teamSupply24Months; //Amount of Team supply could be released after 24 months uint256 public TeamLockingPeriod6Months; // Locking period for team's supply, release 1/4 per 6 months uint256 public TeamLockingPeriod12Months; // Locking period for team's supply, release 1/4 per 6 months uint256 public TeamLockingPeriod18Months; // Locking period for team's supply, release 1/4 per 6 months uint256 public TeamLockingPeriod24Months; // Locking period for team's supply, release 1/4 per 6 months address public presaleAddress; // Presale address address public angelAddress; // Angel address address public marketingAddress; // marketing address address public foundationAddress; // Foundation address address public teamAddress; // Team address address public communityAddress; // Community address function () { //if ether is sent to this address, send it back. //throw; require(false); } /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier checkTeamLockingPeriod6Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod6Months); _; } modifier checkTeamLockingPeriod12Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod12Months); _; } modifier checkTeamLockingPeriod18Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod18Months); _; } modifier checkTeamLockingPeriod24Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod24Months); _; } modifier onlyTeam() { // Ensures only team can call the function require(msg.sender == teamAddress); _; } /*----------------- Burn -----------------*/ event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; // balances[burner] = balances[burner].sub(_value); decrementBalance(burner, _value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } /*----------------- Token API -----------------*/ // ------------------------------------------------- // Total supply // ------------------------------------------------- function totalSupply() constant returns (uint256){ return totalSupply; } // ------------------------------------------------- // Transfers amount to address // ------------------------------------------------- function transfer(address _to, uint256 _amount) returns (bool success) { require(balanceOf(msg.sender) >= _amount); uint previousBalances = balances[msg.sender] + balances[_to]; addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); assert(balances[msg.sender] + balances[_to] == previousBalances); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { require(balanceOf(_from) >= _amount); require(allowance(_from, msg.sender) >= _amount); uint previousBalances = balances[_from] + balances[_to]; decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); assert(balances[_from] + balances[_to] == previousBalances); return true; } // ------------------------------------------------- // Approves another address a certain amount of FUEL // ------------------------------------------------- function approve(address _spender, uint256 _value) returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's FUEL allowance // ------------------------------------------------- function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the FUEL balance of any address // ------------------------------------------------- function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function BitUPToken() { totalSupply = 1000000000 * 1e18; // 100% - 1 billion total BUT with 18 decimals presaleSupply = 400000000 * 1e18; // 40% - 400 million BUT pre-crowdsale angelSupply = 50000000 * 1e18; // 5% - 50 million BUT for the angel crowdsale teamSupply = 200000000 * 1e18; // 20% - 200 million BUT for team. 1/4 part released per 6 months foundationSupply = 150000000 * 1e18; // 15% - 300 million BUT for foundation/incentivising efforts marketingSupply = 100000000 * 1e18; // 10% - 100 million BUT for communitySupply = 100000000 * 1e18; // 10% - 100 million BUT for teamSupply6Months = 50000000 * 1e18; // team supply release 1/4 per 6 months teamSupply12Months = 50000000 * 1e18; // team supply release 1/4 per 6 months teamSupply18Months = 50000000 * 1e18; // team supply release 1/4 per 6 months teamSupply24Months = 50000000 * 1e18; // team supply release 1/4 per 6 months angelAddress = 0xeF01453A730486d262D0b490eF1aDBBF62C2Fe00; // Angel address presaleAddress = 0x2822332F63a6b80E21cEA5C8c43Cb6f393eb5703; // Presale address teamAddress = 0x8E199e0c1DD38d455815E11dc2c9A64D6aD893B7; // Team address foundationAddress = 0xcA972ac76F4Db643C30b86E4A9B54EaBB88Ce5aD; // Foundation address marketingAddress = 0xd2631280F7f0472271Ae298aF034eBa549d792EA; // marketing address communityAddress = 0xF691e8b2B2293D3d3b06ecdF217973B40258208C; //Community address TeamLockingPeriod6Months = now.add(180 * 1 days); // 180 days locking period TeamLockingPeriod12Months = now.add(360 * 1 days); // 360 days locking period TeamLockingPeriod18Months = now.add(450 * 1 days); // 450 days locking period TeamLockingPeriod24Months = now.add(730 * 1 days); // 730 days locking period addToBalance(foundationAddress, foundationSupply); foundationSupply = 0; addToBalance(marketingAddress, marketingSupply); marketingSupply = 0; addToBalance(communityAddress, communitySupply); communitySupply = 0; addToBalance(presaleAddress, presaleSupply); presaleSupply = 0; addToBalance(angelAddress, angelSupply); angelSupply = 0; } // ------------------------------------------------- // Releases 1/4 of team supply after 6 months // ------------------------------------------------- function releaseTeamTokensAfter6Months() checkTeamLockingPeriod6Months onlyTeam returns(bool success) { require(teamSupply6Months > 0); addToBalance(teamAddress, teamSupply6Months); Transfer(0x0, teamAddress, teamSupply6Months); teamSupply6Months = 0; teamSupply.sub(teamSupply6Months); return true; } // ------------------------------------------------- // Releases 1/4 of team supply after 12 months // ------------------------------------------------- function releaseTeamTokensAfter12Months() checkTeamLockingPeriod12Months onlyTeam returns(bool success) { require(teamSupply12Months > 0); addToBalance(teamAddress, teamSupply12Months); Transfer(0x0, teamAddress, teamSupply12Months); teamSupply12Months = 0; teamSupply.sub(teamSupply12Months); return true; } // ------------------------------------------------- // Releases 1/4 of team supply after 18 months // ------------------------------------------------- function releaseTeamTokensAfter18Months() checkTeamLockingPeriod18Months onlyTeam returns(bool success) { require(teamSupply18Months > 0); addToBalance(teamAddress, teamSupply18Months); Transfer(0x0, teamAddress, teamSupply18Months); teamSupply18Months = 0; teamSupply.sub(teamSupply18Months); return true; } // ------------------------------------------------- // Releases 1/4 of team supply after 24 months // ------------------------------------------------- function releaseTeamTokensAfter24Months() checkTeamLockingPeriod24Months onlyTeam returns(bool success) { require(teamSupply24Months > 0); addToBalance(teamAddress, teamSupply24Months); Transfer(0x0, teamAddress, teamSupply24Months); teamSupply24Months = 0; teamSupply.sub(teamSupply24Months); return true; } // ------------------------------------------------- // Adds to balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { balances[_address] = SafeMath.add(balances[_address], _amount); } // ------------------------------------------------- // Removes from balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { balances[_address] = SafeMath.sub(balances[_address], _amount); } }
Amount of Team supply could be released after 18 months
uint256 public teamSupply18Months;
366,303
[ 1, 4625, 348, 7953, 560, 30, 16811, 434, 10434, 14467, 3377, 506, 15976, 1839, 6549, 8846, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5927, 3088, 1283, 2643, 19749, 31, 21821, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // Created for conduction of Zaber ICO - http://www.zabercoin.io/ // Copying in whole or in part is prohibited. // This code is the property of ICORating and ICOmachine - http://ICORating.com // Authors: Ivan Fedorov and Dmitry Borodin /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this does not hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public{ require(newOwner != address(0)); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool _paused = false; function paused() public constant returns(bool) { return _paused; } /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused()); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { require(!_paused); _paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { require(_paused); _paused = false; Unpause(); } } // Contract interface for transferring current tokens to another contract MigrationAgent { function migrateFrom(address _from, uint256 _value) public; } // (A2) // Contract token contract Token is Pausable{ using SafeMath for uint256; string public constant name = "ZABERcoin"; string public constant symbol = "ZAB"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public unpausedWallet; bool public mintingFinished = false; uint256 public totalMigrated; address public migrationAgent; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); event Migrate(address indexed _from, address indexed _to, uint256 _value); modifier canMint() { require(!mintingFinished); _; } function Token(){ owner = 0x0; } function setOwner() public{ require(owner == 0x0); owner = msg.sender; } // Balance of the specified address function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } // Transfer of tokens from one account to another function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require (_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } // Returns the number of tokens that _owner trusted to spend from his account _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Trust _sender and spend _value tokens from your account function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // Transfer of tokens from the trusted address _from to the address _to in the number _value function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); require (_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } // Issue new tokens to the address _to in the amount _amount. Available to the owner of the contract (contract Crowdsale) function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } // Stop the release of tokens. This is not possible to cancel. Available to the owner of the contract. // function finishMinting() public onlyOwner returns (bool) { // mintingFinished = true; // MintFinished(); // return true; // } // Redefinition of the method of the returning status of the "Exchange pause". // Never for the owner of an unpaused wallet. function paused() public constant returns(bool) { return super.paused() && !unpausedWallet[msg.sender]; } // Add a wallet ignoring the "Exchange pause". Available to the owner of the contract. function addUnpausedWallet(address _wallet) public onlyOwner { unpausedWallet[_wallet] = true; } // Remove the wallet ignoring the "Exchange pause". Available to the owner of the contract. function delUnpausedWallet(address _wallet) public onlyOwner { unpausedWallet[_wallet] = false; } // Enable the transfer of current tokens to others. Only 1 time. Disabling this is not possible. // Available to the owner of the contract. function setMigrationAgent(address _migrationAgent) public onlyOwner { require(migrationAgent == 0x0); migrationAgent = _migrationAgent; } // Reissue your tokens. function migrate() public { uint256 value = balances[msg.sender]; require(value > 0); totalSupply = totalSupply.sub(value); totalMigrated = totalMigrated.add(value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); Migrate(msg.sender,migrationAgent,value); balances[msg.sender] = 0; } } // (A3) // Contract for freezing of investors' funds. Hence, investors will be able to withdraw money if the // round does not attain the softcap. From here the wallet of the beneficiary will receive all the // money (namely, the beneficiary, not the manager's wallet). contract RefundVault is Ownable { using SafeMath for uint256; uint8 public round = 0; enum State { Active, Refunding, Closed } mapping (uint8 => mapping (address => uint256)) public deposited; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault() public { state = State.Active; } // Depositing funds on behalf of an ICO investor. Available to the owner of the contract (Crowdsale Contract). function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[round][investor] = deposited[round][investor].add(msg.value); } // Move the collected funds to a specified address. Available to the owner of the contract. function close(address _wallet) onlyOwner public { require(state == State.Active); require(_wallet != 0x0); state = State.Closed; Closed(); _wallet.transfer(this.balance); } // Allow refund to investors. Available to the owner of the contract. function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } // Return the funds to a specified investor. In case of failure of the round, the investor // should call this method of this contract (RefundVault) or call the method claimRefund of Crowdsale // contract. This function should be called either by the investor himself, or the company // (or anyone) can call this function in the loop to return funds to all investors en masse. function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[round][investor]; deposited[round][investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } function restart() onlyOwner public{ require(state == State.Closed); round += 1; state = State.Active; } // Destruction of the contract with return of funds to the specified address. Available to // the owner of the contract. function del(address _wallet) public onlyOwner { selfdestruct(_wallet); } } contract DistributorRefundVault is RefundVault{ address public taxCollector; uint256 public taxValue; function DistributorRefundVault(address _taxCollector, uint256 _taxValue) RefundVault() public{ taxCollector = _taxCollector; taxValue = _taxValue; } function close(address _wallet) onlyOwner public { require(state == State.Active); require(_wallet != 0x0); state = State.Closed; Closed(); uint256 allPay = this.balance; uint256 forTarget1; uint256 forTarget2; if(taxValue <= allPay){ forTarget1 = taxValue; forTarget2 = allPay.sub(taxValue); taxValue = 0; }else { taxValue = taxValue.sub(allPay); forTarget1 = allPay; forTarget2 = 0; } if(forTarget1 != 0){ taxCollector.transfer(forTarget1); } if(forTarget2 != 0){ _wallet.transfer(forTarget2); } } } // (A1) // The main contract for the sale and management of rounds. contract Crowdsale{ using SafeMath for uint256; enum ICOType {preSale, sale} enum Roles {beneficiary,accountant,manager,observer,team} Token public token; bool public isFinalized = false; bool public isInitialized = false; bool public isPausedCrowdsale = false; mapping (uint8 => address) public wallets; uint256 public maxProfit; // percent from 0 to 90 uint256 public minProfit; // percent from 0 to 90 uint256 public stepProfit; // percent step, from 1 to 50 (please, read doc!) uint256 public startTime; // unixtime uint256 public endDiscountTime; // unixtime uint256 public endTime; // unixtime // How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH // **THOUSANDS** 10^3 for human, 1**3 for Solidity, 1e3 for MyEtherWallet (MEW). // Example: if 1ETH = 40.5 Token ==> use 40500 uint256 public rate; // If the round does not attain this value before the closing date, the round is recognized as a // failure and investors take the money back (the founders will not interfere in any way). // **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: softcap=15ETH ==> use 15**18 (Solidity) or 15e18 (MEW) uint256 public softCap; // The maximum possible amount of income // **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450**15 (Solidity) or 12345e15 (MEW) uint256 public hardCap; // If the last payment is slightly higher than the hardcap, then the usual contracts do // not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the // last payment, very slightly raising the hardcap. The value indicates by how many ETH the // last payment can exceed the hardcap to allow it to be paid. Immediately after this payment, the // round closes. The funders should write here a small number, not more than 1% of the CAP. // Can be equal to zero, to cancel. // **QUINTILLIONS** 10^18 / 1**18 / 1e18 uint256 public overLimit; // The minimum possible payment from an investor in ETH. Payments below this value will be rejected. // **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: minPay=0.1ETH ==> use 100**15 (Solidity) or 100e15 (MEW) uint256 public minPay; uint256 ethWeiRaised; uint256 nonEthWeiRaised; uint256 weiPreSale; uint256 public tokenReserved; DistributorRefundVault public vault; SVTAllocation public lockedAllocation; ICOType ICO = ICOType.preSale; uint256 allToken; bool public team = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); event Initialized(); function Crowdsale(Token _token) public { // Initially, all next 5-7 roles/wallets are given to the Manager. The Manager is an employee of the company // with knowledge of IT, who publishes the contract and sets it up. However, money and tokens require // a Beneficiary and other roles (Accountant, Team, etc.). The Manager will not have the right // to receive them. To enable this, the Manager must either enter specific wallets here, or perform // this via method changeWallet. In the finalization methods it is written which wallet and // what percentage of tokens are received. // Receives all the money (when finalizing pre-ICO & ICO) wallets[uint8(Roles.beneficiary)] = 0x8d6b447f443ce7cAA12399B60BC9E601D03111f9; // Receives all the tokens for non-ETH investors (when finalizing pre-ICO & ICO) wallets[uint8(Roles.accountant)] = 0x99a280Dc34A996474e5140f34434CE59b5e65879; // All rights except the rights to receive tokens or money. Has the right to change any other // wallets (Beneficiary, Accountant, ...), but only if the round has not started. Once the // round is initialized, the Manager has lost all rights to change the wallets. // If the ICO is conducted by one person, then nothing needs to be changed. Permit all 7 roles // point to a single wallet. wallets[uint8(Roles.manager)] = msg.sender; // Has only the right to call paymentsInOtherCurrency (please read the document) wallets[uint8(Roles.observer)] = 0x8baf8F18256952362E485fEF1D0909F21f9a886C; // When the round is finalized, all team tokens are transferred to a special freezing // contract. As soon as defrosting is over, only the Team wallet will be able to // collect all the tokens. It does not store the address of the freezing contract, // but the final wallet of the project team. wallets[uint8(Roles.team)] = 0x25365d4B293Ec34c39C00bBac3e5C5Ff2dC81F4F; // startTime, endDiscountTime, endTime (then you can change it in the setup) changePeriod(1510311600, 1511607600, 1511607600); // softCap & hardCap (then you can change it in the setup) changeTargets(0 ether, 51195 ether); // $15 000 000 / $293 // rate (10^3), overLimit (10^18), minPay (10^18) (then you can change it in the setup) changeRate(61250, 500 ether, 10 ether); // minProfit, maxProfit, stepProfit changeDiscount(0,0,0); token = _token; token.setOwner(); token.pause(); // block exchange tokens token.addUnpausedWallet(msg.sender); // The return of funds to investors & pay fee for partner vault = new DistributorRefundVault(0x793ADF4FB1E8a74Dfd548B5E2B5c55b6eeC9a3f8, 10 ether); } // Returns the name of the current round in plain text. Constant. function ICOSaleType() public constant returns(string){ return (ICO == ICOType.preSale)?'pre ICO':'ICO'; } // Transfers the funds of the investor to the contract of return of funds. Internal. function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // Check for the possibility of buying tokens. Inside. Constant. function validPurchase() internal constant returns (bool) { // The round started and did not end bool withinPeriod = (now > startTime && now < endTime); // Rate is greater than or equal to the minimum bool nonZeroPurchase = msg.value >= minPay; // hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit); // round is initialized and no "Pause of trading" is set return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale; } // Check for the ability to finalize the round. Constant. function hasEnded() public constant returns (bool) { bool timeReached = now > endTime; bool capReached = weiRaised() >= hardCap; return (timeReached || capReached) && isInitialized; } // Finalize. Only available to the Manager and the Beneficiary. If the round failed, then // anyone can call the finalization to unlock the return of funds to investors // You must call a function to finalize each round (after the pre-ICO & after the ICO) function finalize() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender || !goalReached()); require(!isFinalized); require(hasEnded()); isFinalized = true; finalization(); Finalized(); } // The logic of finalization. Internal function finalization() internal { // If the goal of the achievement if (goalReached()) { // Send ether to Beneficiary vault.close(wallets[uint8(Roles.beneficiary)]); // if there is anything to give if (tokenReserved > 0) { // Issue tokens of non-eth investors to Accountant account token.mint(wallets[uint8(Roles.accountant)],tokenReserved); // Reset the counter tokenReserved = 0; } // If the finalization is Round 1 pre-ICO if (ICO == ICOType.preSale) { // Reset settings isInitialized = false; isFinalized = false; // Switch to the second round (to ICO) ICO = ICOType.sale; // Reset the collection counter weiPreSale = weiRaised(); ethWeiRaised = 0; nonEthWeiRaised = 0; // Re-start a refund contract vault.restart(); } else // If the second round is finalized { // Record how many tokens we have issued allToken = token.totalSupply(); // Permission to collect tokens to those who can pick them up team = true; } } else // If they failed round { // Allow investors to withdraw their funds vault.enableRefunds(); } } // The Manager freezes the tokens for the Team. // You must call a function to finalize Round 2 (only after the ICO) function finalize1() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(team); team = false; lockedAllocation = new SVTAllocation(token, wallets[uint8(Roles.team)]); token.addUnpausedWallet(lockedAllocation); // 20% - tokens to Team wallet after freeze (80% for investors) // *** CHECK THESE NUMBERS *** token.mint(lockedAllocation,allToken.mul(20).div(80)); } // Initializing the round. Available to the manager. After calling the function, // the Manager loses all rights: Manager can not change the settings (setup), change // wallets, prevent the beginning of the round, etc. You must call a function after setup // for the initial round (before the Pre-ICO and before the ICO) function initialize() public{ // Only the Manager require(wallets[uint8(Roles.manager)] == msg.sender); // If not yet initialized require(!isInitialized); // And the specified start time has not yet come // If initialization return an error, check the start date! require(now <= startTime); initialization(); Initialized(); isInitialized = true; } function initialization() internal { // no code } // At the request of the investor, we raise the funds (if the round has failed because of the hardcap) function claimRefund() public{ vault.refund(msg.sender); } // We check whether we collected the necessary minimum funds. Constant. function goalReached() public constant returns (bool) { return weiRaised() >= softCap; } // Customize. The arguments are described in the constructor above. function setup(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap, uint256 _rate, uint256 _overLimit, uint256 _minPay, uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit) public{ changePeriod(_startTime, _endDiscountTime, _endTime); changeTargets(_softCap, _hardCap); changeRate(_rate, _overLimit, _minPay); changeDiscount(_minProfit, _maxProfit, _stepProfit); } // Change the date and time: the beginning of the round, the end of the bonus, the end of the round. Available to Manager // Description in the Crowdsale constructor function changePeriod(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime) public{ require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); // Date and time are correct require(now <= _startTime); require(_endDiscountTime > _startTime && _endDiscountTime <= _endTime); startTime = _startTime; endTime = _endTime; endDiscountTime = _endDiscountTime; } // We change the purpose of raising funds. Available to the manager. // Description in the Crowdsale constructor. function changeTargets(uint256 _softCap, uint256 _hardCap) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); // The parameters are correct require(_softCap <= _hardCap); softCap = _softCap; hardCap = _hardCap; } // Change the price (the number of tokens per 1 eth), the maximum hardCap for the last bet, // the minimum bet. Available to the Manager. // Description in the Crowdsale constructor function changeRate(uint256 _rate, uint256 _overLimit, uint256 _minPay) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); require(_rate > 0); rate = _rate; overLimit = _overLimit; minPay = _minPay; } // We change the parameters of the discount:% min bonus,% max bonus, number of steps. // Available to the manager. Description in the Crowdsale constructor function changeDiscount(uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); // The parameters are correct require(_stepProfit <= _maxProfit.sub(_minProfit)); // If not zero steps if(_stepProfit > 0){ // We will specify the maximum percentage at which it is possible to provide // the specified number of steps without fractional parts maxProfit = _maxProfit.sub(_minProfit).div(_stepProfit).mul(_stepProfit).add(_minProfit); }else{ // to avoid a divide to zero error, set the bonus as static maxProfit = _minProfit; } minProfit = _minProfit; stepProfit = _stepProfit; } // Collected funds for the current round. Constant. function weiRaised() public constant returns(uint256){ return ethWeiRaised.add(nonEthWeiRaised); } // Returns the amount of fees for both phases. Constant. function weiTotalRaised() public constant returns(uint256){ return weiPreSale.add(weiRaised()); } // Returns the percentage of the bonus on the current date. Constant. function getProfitPercent() public constant returns (uint256){ return getProfitPercentForData(now); } // Returns the percentage of the bonus on the given date. Constant. function getProfitPercentForData(uint256 timeNow) public constant returns (uint256) { // if the discount is 0 or zero steps, or the round does not start, we return the minimum discount if(maxProfit == 0 || stepProfit == 0 || timeNow > endDiscountTime) { return minProfit.add(100); } // if the round is over - the maximum if(timeNow<=startTime) { return maxProfit.add(100); } // bonus period uint256 range = endDiscountTime.sub(startTime); // delta bonus percentage uint256 profitRange = maxProfit.sub(minProfit); // Time left uint256 timeRest = endDiscountTime.sub(timeNow); // Divide the delta of time into uint256 profitProcent = profitRange.div(stepProfit).mul(timeRest.mul(stepProfit.add(1)).div(range)); return profitProcent.add(minProfit).add(100); } // The ability to quickly check pre-ICO (only for Round 1, only 1 time). Completes the pre-ICO by // transferring the specified number of tokens to the Accountant's wallet. Available to the Manager. // Use only if this is provided by the script and white paper. In the normal scenario, it // does not call and the funds are raised normally. We recommend that you delete this // function entirely, so as not to confuse the auditors. Initialize & Finalize not needed. // ** QUINTILIONS ** 10^18 / 1**18 / 1e18 function fastICO(uint256 _totalSupply) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(ICO == ICOType.preSale && !isInitialized); token.mint(wallets[uint8(Roles.accountant)], _totalSupply); ICO = ICOType.sale; } // Remove the "Pause of exchange". Available to the manager at any time. If the // manager refuses to remove the pause, then 120 days after the successful // completion of the ICO, anyone can remove a pause and allow the exchange to continue. // The manager does not interfere and will not be able to delay the term. // He can only cancel the pause before the appointed time. function tokenUnpause() public { require(wallets[uint8(Roles.manager)] == msg.sender || (now > endTime + 120 days && ICO == ICOType.sale && isFinalized && goalReached())); token.unpause(); } // Enable the "Pause of exchange". Available to the manager until the ICO is completed. // The manager cannot turn on the pause, for example, 3 years after the end of the ICO. function tokenPause() public { require(wallets[uint8(Roles.manager)] == msg.sender && !isFinalized); token.pause(); } // Pause of sale. Available to the manager. function crowdsalePause() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(isPausedCrowdsale == false); isPausedCrowdsale = true; } // Withdrawal from the pause of sale. Available to the manager. function crowdsaleUnpause() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(isPausedCrowdsale == true); isPausedCrowdsale = false; } // Checking whether the rights to address ignore the "Pause of exchange". If the // wallet is included in this list, it can translate tokens, ignoring the pause. By default, // only the following wallets are included: // - Accountant wallet (he should immediately transfer tokens, but not to non-ETH investors) // - Contract for freezing the tokens for the Team (but Team wallet not included) // Inside. Constant. function unpausedWallet(address _wallet) internal constant returns(bool) { bool _accountant = wallets[uint8(Roles.accountant)] == _wallet; return _accountant; } // For example - After 5 years of the project's existence, all of us suddenly decided collectively // (company + investors) that it would be more profitable for everyone to switch to another smart // contract responsible for tokens. The company then prepares a new token, investors // disassemble, study, discuss, etc. After a general agreement, the manager allows any investor: // - to burn the tokens of the previous contract // - generate new tokens for a new contract // It is understood that after a general solution through this function all investors // will collectively (and voluntarily) move to a new token. function moveTokens(address _migrationAgent) public { require(wallets[uint8(Roles.manager)] == msg.sender); token.setMigrationAgent(_migrationAgent); } // Change the address for the specified role. // Available to any wallet owner except the observer. // Available to the manager until the round is initialized. // The Observer's wallet or his own manager can change at any time. function changeWallet(Roles _role, address _wallet) public { require( (msg.sender == wallets[uint8(_role)] && _role != Roles.observer) || (msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer)) ); address oldWallet = wallets[uint8(_role)]; wallets[uint8(_role)] = _wallet; if(!unpausedWallet(oldWallet)) token.delUnpausedWallet(oldWallet); if(unpausedWallet(_wallet)) token.addUnpausedWallet(_wallet); } // If a little more than a year has elapsed (ICO start date + 460 days), a smart contract // will allow you to send all the money to the Beneficiary, if any money is present. This is // possible if you mistakenly launch the ICO for 30 years (not 30 days), investors will transfer // money there and you will not be able to pick them up within a reasonable time. It is also // possible that in our checked script someone will make unforeseen mistakes, spoiling the // finalization. Without finalization, money cannot be returned. This is a rescue option to // get around this problem, but available only after a year (460 days). // Another reason - the ICO was a failure, but not all ETH investors took their money during the year after. // Some investors may have lost a wallet key, for example. // The method works equally with the pre-ICO and ICO. When the pre-ICO starts, the time for unlocking // the distructVault begins. If the ICO is then started, then the term starts anew from the first day of the ICO. // Next, act independently, in accordance with obligations to investors. // Within 400 days of the start of the Round, if it fails only investors can take money. After // the deadline this can also include the company as well as investors, depending on who is the first to use the method. function distructVault() public { require(wallets[uint8(Roles.beneficiary)] == msg.sender); require(now > startTime + 400 days); vault.del(wallets[uint8(Roles.beneficiary)]); } // We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC). // Perhaps other types of cryptocurrency - see the original terms in the white paper and on the ICO website. // We release tokens on Ethereum. During the pre-ICO and ICO with a smart contract, you directly transfer // the tokens there and immediately, with the same transaction, receive tokens in your wallet. // When paying in any other currency, for example in BTC, we accept your money via one common wallet. // Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart // contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis. // The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract // monitors softcap and hardcap, so as not to go beyond this framework. // In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several // transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total. // In this case, we will refund all the amounts above, in order not to exceed the hardcap. // Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published // everywhere (in a white paper, on the ICO website, on Telegram, on Bitcointalk, in this code, etc.) // Anyone interested can check that the administrator of the smart contract writes down exactly the amount // in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in // BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to // paymentsInOtherCurrency however, this threat is leveled. // Any user can check the amounts in BTC and the variable of the smart contract that accounts for this // (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract // on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the ICO, // simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection) // and the actual transactions in BTC. The company strictly adheres to the described principles of openness. // The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you // cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as // brakes on the Ethereum network, this operation may be difficult. You should only worry if the // administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet // receives significant amounts. // This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap. // Our BTC wallet for audit in this function: 1CAyLcES1tNuatRhnL1ooPViZ32vF5KQ4A // ** QUINTILLIONS ** 10^18 / 1**18 / 1e18 function paymentsInOtherCurrency(uint256 _token, uint256 _value) public { require(wallets[uint8(Roles.observer)] == msg.sender); bool withinPeriod = (now >= startTime && now <= endTime); bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit); require(withinPeriod && withinCap && isInitialized); nonEthWeiRaised = _value; tokenReserved = _token; } // The function for obtaining smart contract funds in ETH. If all the checks are true, the token is // transferred to the buyer, taking into account the current bonus. function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 ProfitProcent = getProfitPercent(); // calculate token amount to be created uint256 tokens = weiAmount.mul(rate).mul(ProfitProcent).div(100000); // update state ethWeiRaised = ethWeiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // buyTokens alias function () public payable { buyTokens(msg.sender); } } // (B) // The contract for freezing tokens for the team.. contract SVTAllocation { using SafeMath for uint256; Token public token; address public owner; uint256 public unlockedAt; uint256 tokensCreated = 0; // The contract takes the ERC20 coin address from which this contract will work and from the // owner (Team wallet) who owns the funds. function SVTAllocation(Token _token, address _owner) public{ // How many days to freeze from the moment of finalizing ICO unlockedAt = now + 365 days; // freeze TEAM tokens for 1 year token = _token; owner = _owner; } // If the time of freezing expired will return the funds to the owner. function unlock() public{ require(now >= unlockedAt); require(token.transfer(owner,token.balanceOf(this))); } }
assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b * c + a % b); There is no case in which this does not hold
function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; }
2,524,372
[ 1, 4625, 348, 7953, 560, 30, 225, 1815, 12, 70, 405, 374, 1769, 225, 348, 7953, 560, 6635, 1216, 1347, 3739, 10415, 635, 374, 1815, 12, 69, 422, 324, 380, 276, 397, 279, 738, 324, 1769, 225, 6149, 353, 1158, 648, 316, 1492, 333, 1552, 486, 6887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xB2189eDD7A76775332dE02ab69F6C88bb05Aeeed/sources/MasterChefStageOne.sol
calculate modified weight : 10% self + 5% invitees
uint256 nextTermInviteesModifiedWeight = user.termInfo[nextTerm].inviteeWeight;
3,333,655
[ 1, 4625, 348, 7953, 560, 30, 225, 4604, 4358, 3119, 294, 1728, 9, 365, 397, 1381, 9, 19035, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1024, 4065, 22730, 281, 4575, 6544, 273, 729, 18, 6408, 966, 63, 4285, 4065, 8009, 27154, 73, 6544, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xE3eB157642964E9335E4459F7AF9761333bc89B3/sources/ATMLiquidityMining.sol
*/*/*/*/*/*/*/*/*/*/*/* @dev Collection of functions related to the address type/
library Address { @notice This interface defines the functions to manage the Escrow contracts associated to borrowers and loans. @author [email protected] } function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; return (codehash != accountHash && codehash != 0x0); } assembly { codehash := extcodehash(account) } 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"); } }
8,700,348
[ 1, 4625, 348, 7953, 560, 30, 1195, 5549, 5549, 5549, 5549, 5549, 5549, 5549, 5549, 5549, 5549, 14, 632, 5206, 2200, 434, 4186, 3746, 358, 326, 1758, 618, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5267, 288, 203, 565, 632, 20392, 1220, 1560, 11164, 326, 4186, 358, 10680, 326, 512, 1017, 492, 20092, 3627, 358, 29759, 414, 471, 437, 634, 18, 203, 203, 565, 632, 4161, 17196, 36, 19261, 749, 18, 926, 1359, 203, 97, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 1731, 1578, 2236, 2310, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 203, 565, 289, 203, 203, 3639, 19931, 288, 981, 2816, 519, 1110, 710, 2816, 12, 4631, 13, 289, 203, 565, 445, 358, 9148, 429, 12, 2867, 2236, 13, 2713, 16618, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1758, 12, 11890, 16874, 12, 4631, 10019, 203, 565, 289, 203, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1545, 3844, 16, 315, 1887, 30, 2763, 11339, 11013, 8863, 203, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 18, 1132, 12, 8949, 13, 2932, 8863, 203, 3639, 2583, 12, 4768, 16, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 8863, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x2d2F65e372d4808e020e2e3E7c0c6A7DfBd28f51/sources/FarmProRata.sol
If there are any undistributed or unclaimed tokens left in contract after this time Admin can claim them
uint public constant adminCanCl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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 5381, 3981, 2568, 9762, 4436, 273, 16647, 6824, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) external restricted { last_completed_migration = completed; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/INut.sol"; import "./lib/Governable.sol"; contract Nut is ERC20, Governable, INut { using SafeMath for uint; address public distributor; uint public constant MAX_TOKENS = 1000000 ether; // total amount of NUT tokens uint public constant SINK_FUND = 200000 ether; // 20% of tokens goes to sink fund constructor (string memory name, string memory symbol, address sinkAddr) ERC20(name, symbol) { _mint(sinkAddr, SINK_FUND); __Governable__init(); } /// @dev Set the new distributor function setNutDistributor(address addr) external onlyGov { distributor = addr; } /// @dev Mint nut tokens to receipt function mint(address receipt, uint256 amount) external override { require(msg.sender == distributor, "must be called by distributor"); require(amount.add(this.totalSupply()) < MAX_TOKENS, "cannot mint more than MAX_TOKENS"); _mint(receipt, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface INut { function mint(address receipt, uint amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/Initializable.sol"; contract Governable is Initializable { address public governor; address public pendingGovernor; modifier onlyGov() { require(msg.sender == governor, 'bad gov'); _; } function __Governable__init() internal initializer { governor = msg.sender; } function __Governable__init(address _governor) internal initializer { governor = _governor; } /// @dev Set the pending governor, which will be the governor once accepted. /// @param addr The address of the pending governor. function setPendingGovernor(address addr) external onlyGov { pendingGovernor = addr; } /// @dev Accept to become the new governor. Must be called by the pending governor. function acceptGovernor() external { require(msg.sender == pendingGovernor, 'no pend'); pendingGovernor = address(0); governor = msg.sender; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/INutDistributor.sol"; import "./interfaces/INut.sol"; import "./interfaces/IPriceOracle.sol"; import "./lib/Governable.sol"; /* This contract distributes nut tokens based on staking unstaking during the staking period. It generates an array of "value times blocks" for each token/lender pair and "total value times block" for each token. It then distributes the rewards across the array. One issue is that each unstake/stake requires a calculation to determine the fraction of the pool owned by a lender. To avoid having to loop across all epochs and use up gas, this algorithm relies on the fact that all future epochs have the same value. So the vtb and totalVtb arrays keep an index of the last epoch in which there was a partial stake and unstake of tokens and then the epochs beyond that all of the same value which is stored in futureVtbMap and futureTotalVtbMap. */ contract NutDistributor is Governable, INutDistributor { using SafeMath for uint; using SafeERC20 for IERC20; struct Echo { uint id; uint endBlock; uint amount; } address public nutmeg; address public nut; address public oracle; uint public constant MAX_NUM_POOLS = 256; uint public DIST_START_BLOCK; // starting block of echo 0 uint public constant NUM_EPOCH = 15; // # of epochs uint public BLOCKS_PER_EPOCH; // # of blocks per epoch uint public constant DIST_START_AMOUNT = 250000 ether; // # of tokens distributed at epoch 0 uint public constant DIST_MIN_AMOUNT = 18750 ether; // min # of tokens distributed at any epoch uint public CURRENT_EPOCH; mapping(address => bool) addedPoolMap; address[] public pools; mapping(uint => Echo) public echoMap; mapping(uint => bool) public distCompletionMap; // the term vtb is short for value times blocks mapping(address => uint[15]) public totalVtbMap; // pool => total vtb, i.e., valueTimesBlocks. mapping(address => uint[15]) public totalNutMap; // pool => total Nut awarded. mapping(address => mapping( address => uint[15] ) ) public vtbMap; // pool => lender => vtb. mapping(address => uint) futureTotalVtbMap; mapping(address => mapping( address => uint) ) futureVtbMap; mapping(address => uint) futureTotalVtbEpoch; mapping(address => mapping( address => uint) ) futureVtbEpoch; modifier onlyNutmeg() { require(msg.sender == nutmeg, 'only nutmeg can call'); _; } /// @dev Set the Nutmeg function setNutmegAddress(address addr) external onlyGov { nutmeg = addr; } /// @dev Set the oracle function setPriceOracle(address addr) external onlyGov { oracle = addr; } function initialize(address nutAddr, address _governor) public initializer{ nut = nutAddr; DIST_START_BLOCK = block.number; BLOCKS_PER_EPOCH = 80640; __Governable__init(_governor); // config echoMap which indicates how many tokens will be distributed at each epoch for (uint i = 0; i < NUM_EPOCH; i++) { Echo storage echo = echoMap[i]; echo.id = i; echo.endBlock = DIST_START_BLOCK.add(BLOCKS_PER_EPOCH.mul(i.add(1))); uint amount = DIST_START_AMOUNT.div(i.add(1)); if (amount < DIST_MIN_AMOUNT) { amount = DIST_MIN_AMOUNT; } echo.amount = amount; } } function inNutDistribution() external override view returns(bool) { return (block.number >= DIST_START_BLOCK && block.number < DIST_START_BLOCK.add(BLOCKS_PER_EPOCH.mul(NUM_EPOCH))); } /// @notice Update valueTimesBlocks of pools and the lender when they stake or unstake /// @param token Base token of the pool. /// @param lender Address of the lender. /// @param incAmount to stake or unstake /// @param decAmount false=subtract/unstake true=add/stake function updateVtb(address token, address lender, uint incAmount, uint decAmount) external override onlyNutmeg { require(block.number >= DIST_START_BLOCK, 'updateVtb: invalid block number'); require(incAmount == 0 || decAmount == 0, 'updateVtb: update amount is invalid'); uint amount = incAmount.add(decAmount); require(amount > 0, 'updateVtb: update amount should be positive'); // get current epoch CURRENT_EPOCH = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); if (CURRENT_EPOCH >= NUM_EPOCH) return; _fillVtbGap(token, lender); _fillTotalVtbGap(token); uint dv = echoMap[CURRENT_EPOCH].endBlock.sub( block.number ).mul(amount); uint epochDv = BLOCKS_PER_EPOCH.mul(amount); if (incAmount > 0) { vtbMap[token][lender][CURRENT_EPOCH] = vtbMap[token][lender][CURRENT_EPOCH].add(dv); totalVtbMap[token][CURRENT_EPOCH] = totalVtbMap[token][CURRENT_EPOCH].add(dv); futureVtbMap[token][lender] = futureVtbMap[token][lender].add(epochDv); futureTotalVtbMap[token] = futureTotalVtbMap[token].add(epochDv); } else { vtbMap[token][lender][CURRENT_EPOCH] = vtbMap[token][lender][CURRENT_EPOCH].sub(dv); totalVtbMap[token][CURRENT_EPOCH] = totalVtbMap[token][CURRENT_EPOCH].sub(dv); futureVtbMap[token][lender] = futureVtbMap[token][lender].sub(epochDv); futureTotalVtbMap[token] = futureTotalVtbMap[token].sub(epochDv); } if (!addedPoolMap[token]) { pools.push(token); addedPoolMap[token] = true; } } // @dev This function fills the array between the last epoch at which things were calculated and the current epoch. function _fillVtbGap(address token, address lender) internal { if (futureVtbEpoch[token][lender] > CURRENT_EPOCH || CURRENT_EPOCH >= NUM_EPOCH ) return; uint futureVtb = futureVtbMap[token][lender]; for (uint i = futureVtbEpoch[token][lender]; i <= CURRENT_EPOCH; i++) { vtbMap[token][lender][i] = futureVtb; } futureVtbEpoch[token][lender] = CURRENT_EPOCH.add(1); } // @dev This function fills the array between the last epoch at which things were calculated and the current epoch. function _fillTotalVtbGap(address token) internal { if (futureTotalVtbEpoch[token] > CURRENT_EPOCH || CURRENT_EPOCH >= NUM_EPOCH ) return; uint futureTotalVtb = futureTotalVtbMap[token]; for (uint i = futureTotalVtbEpoch[token]; i <= CURRENT_EPOCH; i++) { totalVtbMap[token][i] = futureTotalVtb; } futureTotalVtbEpoch[token] = CURRENT_EPOCH.add(1); } /// @dev Distribute NUT tokens for the previous epoch function distribute() external onlyGov { require(oracle != address(0), 'distribute: no oracle available'); // get current epoch uint currEpochId = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); require(currEpochId > 0, 'distribute: nut token distribution not ready'); require(currEpochId < NUM_EPOCH.add(1), 'distribute: nut token distribution is over'); // distribute the nut tokens for the previous epoch. uint prevEpochId = currEpochId.sub(1); require(!distCompletionMap[prevEpochId], 'distribute: distribution is completed'); // mint nut tokens uint amount = echoMap[prevEpochId].amount; INut(nut).mint(address(this), amount); uint numOfPools = pools.length < MAX_NUM_POOLS ? pools.length : MAX_NUM_POOLS; uint sumOfDv; uint actualSumOfNut; for (uint i = 0; i < numOfPools; i++) { uint price = IPriceOracle(oracle).getPrice(pools[i]); uint dv = price.mul(getTotalVtb(pools[i],prevEpochId)); sumOfDv = sumOfDv.add(dv); } if (sumOfDv > 0) { for (uint i = 0; i < numOfPools; i++) { uint price = IPriceOracle(oracle).getPrice(pools[i]); uint dv = price.mul(getTotalVtb(pools[i], prevEpochId)); uint nutAmount = dv.mul(amount).div(sumOfDv); actualSumOfNut = actualSumOfNut.add(nutAmount); totalNutMap[pools[i]][prevEpochId] = nutAmount; } } require(actualSumOfNut <= amount, "distribute: overflow"); distCompletionMap[prevEpochId] = true; } /// @dev Collect Nut tokens function collect() external { uint epochId = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); require(epochId > 0, 'collect: distribution is completed'); address lender = msg.sender; uint numOfPools = pools.length < MAX_NUM_POOLS ? pools.length : MAX_NUM_POOLS; uint totalAmount; for (uint i = 0; i < numOfPools; i++) { address pool = pools[i]; for (uint j = 0; j < epochId && j < NUM_EPOCH; j++) { uint vtb = getVtb(pool, lender, j); if (vtb > 0 && getTotalVtb(pool, j) > 0) { uint amount = vtb.mul(totalNutMap[pool][j]).div(getTotalVtb(pool, j)); totalAmount = totalAmount.add(amount); vtbMap[pool][lender][j] = 0; } } } if (totalAmount > 0) { require( IERC20(nut).approve(address(this), 0), 'distributor approve failed' ); require( IERC20(nut).approve(address(this), totalAmount), 'NutDist approve amount failed' ); require( IERC20(nut).transferFrom(address(this), lender, totalAmount), 'NutDist transfer failed' ); } } /// @dev getCollectionAmount get the # of NUT tokens for collection function getCollectionAmount() external view returns(uint) { uint epochId = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); require(epochId > 0, 'getCollectionAmount: distribution is completed'); address lender = msg.sender; uint numOfPools = pools.length < MAX_NUM_POOLS ? pools.length : MAX_NUM_POOLS; uint totalAmount; for (uint i = 0; i < numOfPools; i++) { address pool = pools[i]; for (uint j = 0; j < epochId && j < NUM_EPOCH; j++) { uint vtb = getVtb(pool, lender, j); if (vtb > 0 && getTotalVtb(pool, j) > 0) { uint amount = vtb.mul(totalNutMap[pool][j]).div(getTotalVtb(pool, j)); totalAmount = totalAmount.add(amount); } } } return totalAmount; } function getVtb(address pool, address lender, uint i) public view returns(uint) { require(i < NUM_EPOCH, 'vtb idx err'); return i < futureVtbEpoch[pool][lender] ? vtbMap[pool][lender][i] : futureVtbMap[pool][lender]; } function getTotalVtb(address pool, uint i) public view returns (uint) { require(i < NUM_EPOCH, 'totalVtb idx err'); return i < futureTotalVtbEpoch[pool] ? totalVtbMap[pool][i] : futureTotalVtbMap[pool]; } //@notice output version string function getVersionString() external virtual pure returns (string memory) { return "1"; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface INutDistributor { function updateVtb(address token, address lender, uint incAmount, uint decAmount) external; function inNutDistribution() external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IPriceOracle { function getPrice(address token) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import './lib/Governable.sol'; import './lib/Math.sol'; import "./interfaces/IAdapter.sol"; import "./interfaces/INutmeg.sol"; import "./interfaces/INutDistributor.sol"; import "./interfaces/IPriceOracle.sol"; contract Nutmeg is Initializable, Governable, INutmeg { using SafeMath for uint; using SafeERC20 for IERC20; address public nutDistributor; address public nut; uint private constant INVALID_POSITION_ID = type(uint).max; uint private constant NOT_LOCKED = 0; uint private constant LOCKED = 1; uint private constant TRANCHE_BBB = uint(Tranche.BBB); uint private constant TRANCHE_A = uint(Tranche.A); uint private constant TRANCHE_AA = uint(Tranche.AA); uint private constant MULTIPLIER = 10**18; uint private constant NUM_BLOCK_PER_YEAR = 2102400; address private constant INVALID_ADAPTER = address(2); uint public constant MAX_NUM_POOL = 256; uint public constant LIQUIDATION_COMMISSION = 5; uint public constant MAX_INTEREST_RATE_PER_BLOCK = 100000; // 1000.00% uint public constant MIN_INTEREST_RATE_PER_BLOCK = 500; // 5.00% uint public constant VERSION_ID = 1; uint public POOL_LOCK; uint public EXECUTION_LOCK; uint public STAKE_COUNTER; uint public POSITION_COUNTER; uint public CURR_POSITION_ID; address public CURR_SENDER; address public CURR_ADAPTER; // treasury pool array and map address[] public pools; // array of treasury pools mapping(address => Pool) public poolMap; // baseToken => pool mapping. // stake mapping(address => mapping (address => Stake[3])) public stakeMap; // baseToken => sender => tranche. mapping(address => uint[]) lenderStakeMap; // all stakes of a lender. address => stakeId // adapter address[] public adapters; mapping(address => bool) public adapterMap; // position mapping(uint => Position) public positionMap; mapping(address => uint[]) borrowerPositionMap; // all positions of a borrower. address => positionId mapping(address => mapping(address => uint)) minNut4Borrowers; // pool => adapter => uint /// @dev Reentrancy lock guard. modifier poolLock() { require(POOL_LOCK == NOT_LOCKED, 'pl lck'); POOL_LOCK = LOCKED; _; POOL_LOCK = NOT_LOCKED; } /// @dev Reentrancy lock guard for execution. modifier inExecution() { require(CURR_POSITION_ID != INVALID_POSITION_ID, 'not exc'); require(CURR_ADAPTER == msg.sender, 'bad adpr'); require(EXECUTION_LOCK == NOT_LOCKED, 'exc lock'); EXECUTION_LOCK = LOCKED; _; EXECUTION_LOCK = NOT_LOCKED; } /// @dev Accrue interests in a pool modifier accrue(address token) { accrueInterest(token); _; } /// @dev Initialize the smart contract, using msg.sender as the first governor. function initialize(address _governor) external initializer { __Governable__init(_governor); POOL_LOCK = NOT_LOCKED; EXECUTION_LOCK = NOT_LOCKED; STAKE_COUNTER = 1; POSITION_COUNTER = 1; CURR_POSITION_ID = INVALID_POSITION_ID; CURR_ADAPTER = INVALID_ADAPTER; } function setNutDistributor(address addr) external onlyGov { nutDistributor = addr; } function setNut(address addr) external onlyGov { nut = addr; } function setMinNut4Borrowers(address poolAddr, address adapterAddr, uint val) external onlyGov { require(adapterMap[adapterAddr], 'setMin no adpr'); Pool storage pool = poolMap[poolAddr]; require(pool.isExists, 'setMin no pool'); minNut4Borrowers[poolAddr][adapterAddr] = val; } /// @notice Get all stake IDs of a lender function getStakeIds(address lender) external override view returns (uint[] memory){ return lenderStakeMap[lender]; } /// @notice Get all position IDs of a borrower function getPositionIds(address borrower) external override view returns (uint[] memory){ return borrowerPositionMap[borrower]; } /// @notice Return current position ID function getCurrPositionId() external override view returns (uint) { return CURR_POSITION_ID; } /// @notice Return next position ID function getNextPositionId() external override view returns (uint) { return POSITION_COUNTER; } /// @notice Get position information function getPosition(uint id) external override view returns (Position memory) { return positionMap[id]; } /// @dev get current sender function getCurrSender() external override view returns (address) { return CURR_SENDER; } /// @dev Get all treasury pools function getPools() external view returns (address[] memory) { return pools; } /// @dev Get a specific pool given address function getPool(address addr) external view returns (Pool memory) { return poolMap[addr]; } /// @dev Add a new treasury pool. /// @param token The underlying base token for the pool, e.g., DAI. /// @param interestRate The interest rate per block of Tranche A. function addPool(address token, uint interestRate) external poolLock onlyGov { require(pools.length < MAX_NUM_POOL, 'addPl pl > max'); require(_isInterestRateValid(interestRate), 'addPl bad ir'); Pool storage pool = poolMap[token]; require(!pool.isExists, 'addPl pool exts'); pool.isExists = true; pool.baseToken = token; pool.interestRates = [interestRate.div(2), interestRate, interestRate.mul(2)]; pools.push(token); emit addPoolEvent(token, interestRate); pool.lossMultiplier = [ MULTIPLIER, MULTIPLIER, MULTIPLIER ]; } /// @dev Update interest rate of the pool /// @param token The underlying base token for the pool, e.g., DAI. /// @param interestRate The interest rate per block of Tranche A. Input 316 for 3.16% APY function updateInterestRates(address token, uint interestRate) external poolLock onlyGov { require(_isInterestRateValid(interestRate), 'upIR bad ir'); Pool storage pool = poolMap[token]; require(pool.isExists, 'upIR no pool'); pool.interestRates = [interestRate.div(2), interestRate, interestRate.mul(2)]; } function _isInterestRateValid(uint interestRate) internal pure returns(bool) { return (interestRate <= MAX_INTEREST_RATE_PER_BLOCK && interestRate >= MIN_INTEREST_RATE_PER_BLOCK); } /// @notice Stake to a treasury pool. /// @param token The contract address of the base token of the pool. /// @param tranche The tranche of the pool, 0 - AA, 1 - A, 2 - BBB. /// @param principal The amount of principal function stake(address token, uint tranche, uint principal) external poolLock accrue(token) { require(tranche < 3, 'stk bad trnch'); require(principal > 0, 'stk bad prpl'); Pool storage pool = poolMap[token]; require(pool.isExists, 'stk no pool'); if (tranche == TRANCHE_BBB) { require(principal.add(pool.principals[TRANCHE_BBB]) <= pool.principals[TRANCHE_AA], 'stk BBB full'); } // 1. transfer the principal to the pool. IERC20(pool.baseToken).safeTransferFrom(msg.sender, address(this), principal); // 2. add or update a stake Stake storage stk = stakeMap[token][msg.sender][tranche]; uint sumIpp = pool.sumIpp[tranche]; uint scaledPrincipal = 0; if (stk.id == 0) { // new stk stk.id = STAKE_COUNTER++; stk.status = StakeStatus.Open; stk.owner = msg.sender; stk.pool = token; stk.tranche = tranche; } else { // add liquidity to an existing stk scaledPrincipal = _scaleByLossMultiplier( stk, stk.principal ); uint interest = scaledPrincipal.mul( sumIpp.sub(stk.sumIppStart)).div(MULTIPLIER); stk.earnedInterest = _scaleByLossMultiplier(stk, stk.earnedInterest ).add(interest); } stk.sumIppStart = sumIpp; stk.principal = scaledPrincipal.add(principal); stk.lossZeroCounterBase = pool.lossZeroCounter[tranche]; stk.lossMultiplierBase = pool.lossMultiplier[tranche]; lenderStakeMap[stk.owner].push(stk.id); // update pool information pool.principals[tranche] = pool.principals[tranche].add(principal); updateInterestRateAdjustment(token); if (INutDistributor(nutDistributor).inNutDistribution()) { INutDistributor(nutDistributor).updateVtb(token, stk.owner, principal, 0); } emit stakeEvent(token, msg.sender, tranche, principal, stk.id); } /// @notice Unstake from a treasury pool. /// @param token The address of the pool. /// @param tranche The tranche of the pool, 0 - AA, 1 - A, 2 - BBB. /// @param amount The amount of principal that owner want to withdraw function unstake(address token, uint tranche, uint amount) external poolLock accrue(token) { require(tranche < 3, 'unstk bad trnch'); Pool storage pool = poolMap[token]; Stake storage stk = stakeMap[token][msg.sender][tranche]; require(stk.id > 0, 'unstk no dpt'); uint activePrincipal = _scaleByLossMultiplier( stk, stk.principal ); require(amount > 0 && amount <= activePrincipal, 'unstk bad amt'); require(stk.status == StakeStatus.Open, 'unstk bad status'); // get the available amount to remove uint withdrawAmt = _getWithdrawAmount(poolMap[stk.pool], amount); uint interest = activePrincipal.mul(pool.sumIpp[tranche].sub(stk.sumIppStart)).div(MULTIPLIER); uint totalInterest = _scaleByLossMultiplier( stk, stk.earnedInterest ).add(interest); if (totalInterest > pool.interests[tranche]) { // unlikely, but just in case. totalInterest = pool.interests[tranche]; } // transfer liquidity to the lender uint actualWithdrawAmt = withdrawAmt.add(totalInterest); IERC20(pool.baseToken).safeTransfer(msg.sender, actualWithdrawAmt); // update stake information stk.principal = activePrincipal.sub(withdrawAmt); stk.sumIppStart = pool.sumIpp[tranche]; stk.lossZeroCounterBase = pool.lossZeroCounter[tranche]; stk.lossMultiplierBase = pool.lossMultiplier[tranche]; stk.earnedInterest = 0; if (stk.principal == 0) { stk.status = StakeStatus.Closed; } // update pool principal and interest information pool.principals[tranche] = pool.principals[tranche].sub(withdrawAmt); pool.interests[tranche] = pool.interests[tranche].sub(totalInterest); updateInterestRateAdjustment(token); if (INutDistributor(nutDistributor).inNutDistribution() && withdrawAmt > 0) { INutDistributor(nutDistributor).updateVtb(token, stk.owner, 0, withdrawAmt); } emit unstakeEvent(token, msg.sender, tranche, withdrawAmt, stk.id); } function _scaleByLossMultiplier(Stake memory stk, uint quantity) internal view returns (uint) { Pool memory pool = poolMap[stk.pool]; return stk.lossZeroCounterBase < pool.lossZeroCounter[stk.tranche] ? 0 : quantity.mul( pool.lossMultiplier[stk.tranche] ).div( stk.lossMultiplierBase ); } /// @notice Accrue interest for a given pool. /// @param token Address of the pool. function accrueInterest(address token) internal { Pool storage pool = poolMap[token]; require(pool.isExists, 'accrIr no pool'); uint totalLoan = Math.sumOf3UintArray(pool.loans); uint currBlock = block.number; if (currBlock <= pool.latestAccruedBlock) return; if (totalLoan > 0 ) { uint interestRate = pool.interestRates[TRANCHE_A]; if (!pool.isIrAdjustPctNegative) { interestRate = interestRate.mul(pool.irAdjustPct.add(100)).div(100); } else { interestRate = interestRate.mul(uint(100).sub(pool.irAdjustPct)).div(100); } uint rtb = interestRate.mul(currBlock.sub(pool.latestAccruedBlock)); // update pool sumRtb. pool.sumRtb = pool.sumRtb.add(rtb); // update tranche sumIpp. for (uint idx = 0; idx < pool.loans.length; idx++) { if (pool.principals[idx] > 0) { uint interest = (pool.loans[idx].mul(rtb)).div(NUM_BLOCK_PER_YEAR.mul(10000)); pool.interests[idx] = pool.interests[idx].add(interest); pool.sumIpp[idx]= pool.sumIpp[idx].add(interest.mul(MULTIPLIER).div(pool.principals[idx])); } } } pool.latestAccruedBlock = block.number; } /// @notice Get pool information /// @param token The base token function getPoolInfo(address token) external view override returns(uint, uint, uint) { Pool memory pool = poolMap[token]; require(pool.isExists, 'getPolInf no pol'); return (Math.sumOf3UintArray(pool.principals), Math.sumOf3UintArray(pool.loans), pool.totalCollateral); } /// @notice Get interest a position need to pay /// @param token Address of the pool. /// @param posId Position ID. function getPositionInterest(address token, uint posId) public override view returns(uint) { Pool storage pool = poolMap[token]; require(pool.isExists, 'getPosIR no pool'); Position storage pos = positionMap[posId]; require(pos.baseToken == pool.baseToken, 'getPosIR bad match'); return Math.sumOf3UintArray(pos.loans).mul(pool.sumRtb.sub(pos.sumRtbStart)).div( NUM_BLOCK_PER_YEAR.mul(10000) ); } /// @dev Update the interest rate adjustment of the pool /// @param token Address of the pool function updateInterestRateAdjustment(address token) public { Pool storage pool = poolMap[token]; require(pool.isExists, 'updtIRAdj no pool'); uint totalPrincipal = Math.sumOf3UintArray(pool.principals); uint totalLoan = Math.sumOf3UintArray(pool.loans); if (totalPrincipal > 0 ) { uint urPct = totalLoan >= totalPrincipal ? 100 : totalLoan.mul(100).div(totalPrincipal); if (urPct > 90) { // 0% + 50 * (UR - 90%) pool.irAdjustPct = urPct.sub(90).mul(50); pool.isIrAdjustPctNegative = false; } else if (urPct < 90) { // UR - 90% pool.irAdjustPct = (uint(90).sub(urPct)); pool.isIrAdjustPctNegative = true; } } } function _getWithdrawAmount(Pool memory pool, uint amount) internal pure returns (uint) { uint availPrincipal = Math.sumOf3UintArray(pool.principals).sub( Math.sumOf3UintArray(pool.loans) ); return amount > availPrincipal ? availPrincipal : amount; } /// @dev Get the collateral ratio of the pool. /// @param baseToken Base token of the pool. /// @param baseAmt The collateral from the borrower. function _getCollateralRatioPct(address baseToken, uint baseAmt) public view returns (uint) { Pool storage pool = poolMap[baseToken]; require(pool.isExists, '_getCollRatPct no pool'); uint totalPrincipal = Math.sumOf3UintArray(pool.principals); uint totalLoan = Math.sumOf3UintArray(pool.loans); uint urPct = (totalPrincipal == 0) ? 100 : ((totalLoan.add(baseAmt)).mul(100)).div(totalPrincipal); if (urPct > 100) { // not likely, but just in case. urPct = 100; } if (urPct > 90) { // 10% + 9 * (UR - 90%) return (urPct.sub(90).mul(9)).add(10); } // 10% - 0.1 * (90% - UR) return (urPct.div(10)).add(1); } /// @notice Get the maximum available borrow amount /// @param baseToken Base token of the pool /// @param baseAmt The collateral from the borrower function getMaxBorrowAmount(address baseToken, uint baseAmt) public override view returns (uint) { uint crPct = _getCollateralRatioPct(baseToken, baseAmt); return (baseAmt.mul(100).div(crPct)).sub(baseAmt); } /// @notice Get stakes of a user in a pool /// @param token The address of the pool /// @param owner The address of the owner function getStake(address token, address owner) public view returns (Stake[3] memory) { return stakeMap[token][owner]; } /// @dev Add adapter to Nutmeg /// @param token The address of the adapter function addAdapter(address token) external poolLock onlyGov { adapters.push(token); adapterMap[token] = true; } /// @dev Remove adapter from Nutmeg /// @param token The address of the adapter function removeAdapter(address token) external poolLock onlyGov { adapterMap[token] = false; } /// @notice Borrow tokens from the pool. Must only be called by adapter while under execution. /// @param baseToken The token to borrow from the pool. /// @param collToken The token borrowers got from the 3rd party pool. /// @param baseAmt The amount of collateral from borrower. /// @param borrowAmt The amount of tokens to borrow, x time leveraged already. function borrow(address baseToken, address collToken, uint baseAmt, uint borrowAmt) external override accrue(baseToken) inExecution { // check pool and position. Pool storage pool = poolMap[baseToken]; require(pool.isExists, 'brw no pool'); Position storage position = positionMap[CURR_POSITION_ID]; require(position.baseToken == address(0), 'brw no rebrw'); // check borrowAmt uint maxBorrowAmt = getMaxBorrowAmount(baseToken, baseAmt); require(borrowAmt <= maxBorrowAmt, "brw too bad"); require(borrowAmt > baseAmt, "brw brw < coll"); // check available principal per tranche. uint[3] memory availPrincipals; for (uint i = 0; i < 3; i++) { availPrincipals[i] = pool.principals[i].sub(pool.loans[i]); } uint totalAvailPrincipal = Math.sumOf3UintArray(availPrincipals); require(borrowAmt <= totalAvailPrincipal, 'brw asset low'); // calculate loan amount from each tranche. uint[3] memory loans; for (uint i = 0; i < 3; i++) { loans[i] = borrowAmt.mul(availPrincipals[i]).div(totalAvailPrincipal); } loans[2] = borrowAmt.sub(loans[0].add(loans[1])); // handling rounding numbers // transfer base tokens from borrower to contract as the collateral. IERC20(pool.baseToken).safeApprove(address(this), 0); IERC20(pool.baseToken).safeApprove(address(this), baseAmt); IERC20(pool.baseToken).safeTransferFrom(position.owner, address(this), baseAmt); // transfer borrowed assets to the adapter IERC20(pool.baseToken).safeTransfer(msg.sender, borrowAmt); // update position information position.status = PositionStatus.Open; position.baseToken = pool.baseToken; position.collToken = collToken; position.baseAmt = baseAmt; position.borrowAmt = borrowAmt; position.loans = loans; position.sumRtbStart = pool.sumRtb; borrowerPositionMap[position.owner].push(position.id); // update pool information for (uint i = 0; i < 3; i++) { pool.loans[i] = pool.loans[i].add(loans[i]); } pool.totalCollateral = pool.totalCollateral.add(baseAmt); updateInterestRateAdjustment(baseToken); } function _getRepayAmount(uint[3] memory loans, uint totalAmt) public pure returns(uint[3] memory) { uint totalLoan = Math.sumOf3UintArray(loans); uint amount = totalLoan < totalAmt ? totalLoan : totalAmt; uint[3] memory repays = [uint(0), uint(0), uint(0)]; for (uint i; i < 3; i++) { repays[i] = (loans[i].mul(amount)).div(totalLoan); } repays[2] = amount.sub(repays[0].add(repays[1])); return repays; } /// @notice Repay tokens to the pool and close the position. Must only be called while under execution. /// @param baseToken The token to borrow from the pool. /// @param repayAmt The amount of base token repaid from adapter. function repay(address baseToken, uint repayAmt) external override accrue(baseToken) inExecution { Position storage pos = positionMap[CURR_POSITION_ID]; Pool storage pool = poolMap[pos.baseToken]; require(pool.isExists, 'rpy no pool'); require(adapterMap[pos.adapter] && msg.sender == pos.adapter, 'repay: no such adapter'); uint totalLoan = Math.sumOf3UintArray(pos.loans); // owe to lenders uint interest = getPositionInterest(pool.baseToken, pos.id); // already paid to lenders uint totalRepayAmt = repayAmt.add(pos.baseAmt).sub(interest); // total amount used for repayment uint change = totalRepayAmt > totalLoan ? totalRepayAmt.sub(totalLoan) : 0; // profit of the borrower // transfer total redeemed amount from adapter to the pool IERC20(baseToken).safeTransferFrom(msg.sender, address(this), repayAmt); if (totalRepayAmt < totalLoan) { pos.repayDeficit = totalLoan.sub(totalRepayAmt); } uint[3] memory repays = _getRepayAmount(pos.loans, repayAmt); // update position information pos.status = PositionStatus.Closed; for (uint i; i < 3; i++) { pos.loans[i] = pos.loans[i].sub(repays[i]); } // update pool information pool.totalCollateral = pool.totalCollateral.sub(pos.baseAmt); for (uint i; i < 3; i++) { pool.loans[i] = pool.loans[i].sub(repays[i]); } // send profit, if any to the borrower. if (change > 0) { IERC20(baseToken).safeTransfer(pos.owner, change); } } /// @notice Liquidate a position when conditions are satisfied /// @param baseToken The base token of the pool. /// @param liquidateAmt The repay amount from adapter. function liquidate( address baseToken, uint liquidateAmt) external override accrue(baseToken) inExecution { Position storage pos = positionMap[CURR_POSITION_ID]; Pool storage pool = poolMap[baseToken]; require(pool.isExists, 'lqt no pool'); require(pool.baseToken == baseToken, "lqt base no match"); require(adapterMap[pos.adapter] && msg.sender == pos.adapter, 'lqt no adpr'); require(liquidateAmt > 0, 'lqt bad rpy'); // transfer liquidateAmt of base tokens from adapter to pool. IERC20(baseToken).safeTransferFrom(msg.sender, address(this), liquidateAmt); uint totalLoan = Math.sumOf3UintArray(pos.loans); uint interest = getPositionInterest(pool.baseToken, pos.id); uint totalRepayAmt = liquidateAmt.add(pos.baseAmt).sub(interest); // total base tokens from liquidated uint bonusAmt = LIQUIDATION_COMMISSION.mul(totalRepayAmt).div(100); // bonus for liquidator. uint repayAmt = totalRepayAmt.sub(bonusAmt); // amount to pay lenders and the borrower uint change = totalLoan < repayAmt ? repayAmt.sub(totalLoan) : 0; uint[3] memory repays = _getRepayAmount(pos.loans, liquidateAmt); // transfer bonus to the liquidator. IERC20(baseToken).safeTransfer(tx.origin, bonusAmt); // update position information pos.status = PositionStatus.Liquidated; for (uint i; i < 3; i++) { pos.loans[i] = pos.loans[i].sub(repays[i]); } // update pool information pool.totalCollateral = pool.totalCollateral.sub(pos.baseAmt); for (uint i; i < 3; i++) { pool.loans[i] = pool.loans[i].sub(repays[i]); } // send leftover to position owner if (change > 0) { IERC20(baseToken).safeTransfer(pos.owner, change); } if (totalRepayAmt < totalLoan) { pos.repayDeficit = totalLoan.sub(totalRepayAmt); } } /// @notice Settle credit event callback /// @param baseToken Base token of the pool. /// @param collateralLoss Loss to be distributed /// @param poolLoss Loss to be distributed function distributeCreditLosses( address baseToken, uint collateralLoss, uint poolLoss) external override accrue(baseToken) inExecution { Pool storage pool = poolMap[baseToken]; require(pool.isExists, 'dstCrd no pool'); require(collateralLoss <= pool.totalCollateral, 'dstCrd col high'); if (collateralLoss >= 0) { pool.totalCollateral = pool.totalCollateral.sub(collateralLoss); } if (poolLoss == 0) { return; } uint totalPrincipal = Math.sumOf3UintArray(pool.principals); uint runningLoss = poolLoss; for (uint i = 0; i < 3; i++) { uint j = 3 - i - 1; // The running totals are based on the principal, // however, when I calculate the multipliers, I // take into account accured interest uint tranchePrincipal = pool.principals[j]; uint trancheValue = pool.principals[j] + pool.interests[j]; // Do not scale pool.sumIpp. Since I am scaling the // principal, this will cause the interest rate // calcuations to take into account the losses when // a lender position is unstaked. if (runningLoss >= tranchePrincipal) { pool.principals[j] = 0; pool.interests[j] = 0; pool.lossZeroCounter[j] = block.number; pool.lossMultiplier[j] = MULTIPLIER; runningLoss = runningLoss.sub(tranchePrincipal); } else { uint valueRemaining = tranchePrincipal.sub(runningLoss); pool.principals[j] = pool.principals[j].mul(valueRemaining).div(trancheValue); pool.interests[j] = pool.interests[j].mul(valueRemaining).div(trancheValue); pool.lossMultiplier[j] = valueRemaining.mul(MULTIPLIER).div(trancheValue); break; } } // subtract the pool loss from the total loans // this keeps principal - loans the same so that // we have a correct accounting of the amount of // liquidity available for borrows. uint totalLoans = pool.loans[0].add(pool.loans[1]).add(pool.loans[2]); totalPrincipal = (poolLoss <= totalPrincipal) ? totalPrincipal.sub(poolLoss) : 0; totalLoans = (poolLoss <= totalLoans) ? totalLoans.sub(poolLoss) : 0; for (uint i = 0; i < pool.loans.length; i++) { pool.loans[i] = totalPrincipal == 0 ? 0 : totalLoans.mul(pool.principals[i]).div(totalPrincipal); } } /// @notice Add collateral token to position. Must be called during execution. /// @param posId Position id /// @param collAmt The amount of the collateral token from 3rd party pool. function addCollToken(uint posId, uint collAmt) external override inExecution { Position storage pos = positionMap[CURR_POSITION_ID]; require(pos.id == posId, "addCollTk bad pos"); pos.collAmt = collAmt; } function getEarnedInterest( address token, address owner, Tranche tranche ) external view returns (uint256) { Pool storage pool = poolMap[token]; require(pool.isExists, 'gtErndIr no pool'); Stake memory stk = getStake(token, owner)[uint(tranche)]; return _scaleByLossMultiplier( stk, stk.earnedInterest.add( stk.principal.mul( pool.sumIpp[uint(tranche)].sub(stk.sumIppStart) ).div(MULTIPLIER)) ); } /// ------------------------------------------------------------------- /// functions to adapter function beforeExecution( uint posId, IAdapter adapter ) internal { require(POOL_LOCK == NOT_LOCKED, 'pol lck'); POOL_LOCK = LOCKED; address adapterAddr = address(adapter); require(adapterMap[adapterAddr], 'no adpr'); if (posId == 0) { // create a new position posId = POSITION_COUNTER++; positionMap[posId].id = posId; positionMap[posId].owner = msg.sender; positionMap[posId].adapter = adapterAddr; } else { require(posId < POSITION_COUNTER, 'no pos'); require(positionMap[posId].status == PositionStatus.Open, 'only open pos'); } CURR_POSITION_ID = posId; CURR_ADAPTER = adapterAddr; CURR_SENDER = msg.sender; } function afterExecution() internal { CURR_POSITION_ID = INVALID_POSITION_ID; CURR_ADAPTER = INVALID_ADAPTER; POOL_LOCK = NOT_LOCKED; CURR_SENDER = address(0); } function openPosition( uint posId, IAdapter adapter, address baseToken, address collToken, uint baseAmt, uint borrowAmt ) external { uint balance = IERC20(nut).balanceOf(msg.sender); require(minNut4Borrowers[baseToken][address(adapter)] <= balance, 'NUT low'); beforeExecution(posId, adapter); adapter.openPosition( baseToken, collToken, baseAmt, borrowAmt ); afterExecution(); } function closePosition( uint posId, IAdapter adapter ) external returns (uint) { beforeExecution(posId, adapter); uint redeemAmt = adapter.closePosition(); afterExecution(); return redeemAmt; } function liquidatePosition( uint posId, IAdapter adapter ) external { beforeExecution(posId, adapter); adapter.liquidate(); afterExecution(); } function settleCreditEvent( IAdapter adapter, address baseToken, uint collateralLoss, uint poolLoss ) onlyGov external { beforeExecution(0, adapter); adapter.settleCreditEvent( baseToken, collateralLoss, poolLoss ); afterExecution(); } function getMaxUnstakePrincipal(address token, address owner, uint tranche) external view returns (uint) { Stake memory stk = stakeMap[token][owner][tranche]; return _getWithdrawAmount(poolMap[stk.pool], stk.principal); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; library Math { using SafeMath for uint; function sumOf3UintArray(uint[3] memory data) internal pure returns(uint) { return data[0].add(data[1]).add(data[2]); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IAdapter { function openPosition( address baseToken, address collToken, uint collAmount, uint borrowAmount ) external; function closePosition() external returns (uint); function liquidate() external; function settleCreditEvent( address baseToken, uint collateralLoss, uint poolLoss) external; event openPositionEvent(uint positionId, address caller, uint baseAmt, uint borrowAmount); event closePositionEvent(uint positionId, address caller, uint amount); event liquidateEvent(uint positionId, address caller); event creditEvent(address token, uint collateralLoss, uint poolLoss); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; interface INutmeg { enum Tranche {AA, A, BBB} enum StakeStatus {Uninitialized, Open, Closed, Settled} enum PositionStatus {Uninitialized, Open, Closed, Liquidated, Settled} struct Pool { bool isExists; address baseToken; // base token of this pool, e.g., WETH, DAI. uint[3] interestRates; // interest rate per block of each tranche. supposed to be updated everyday. uint[3] principals; // principals of each tranche, from lenders uint[3] loans; // loans of each tranche, from borrowers. uint[3] interests; // interests accrued from loans for each tranche. uint totalCollateral; // total collaterals in base token from borrowers. uint latestAccruedBlock; // the block number of the latest interest accrual action. uint sumRtb; // sum of interest rate per block (after adjustment) times # of blocks uint irAdjustPct; // interest rate adjustment in percentage, e.g., 1, 99. bool isIrAdjustPctNegative; // whether interestRateAdjustPct is negative uint[3] sumIpp; // sum of interest per principal. uint[3] lossMultiplier; uint[3] lossZeroCounter; } struct Stake { uint id; StakeStatus status; address owner; address pool; uint tranche; // tranche of the pool, 0 - AA, 1 - A, 2 - BBB. uint principal; uint sumIppStart; uint earnedInterest; uint lossMultiplierBase; uint lossZeroCounterBase; } struct Position { uint id; // id of the position. PositionStatus status; // status of the position, Open, Close, and Liquidated. address owner; // borrower's address address adapter; // adapter's address address baseToken; // base token that the borrower borrows from the pool address collToken; // collateral token that the borrower got from 3rd party pool. uint[3] loans; // loans of all tranches uint baseAmt; // amount of the base token the borrower put into pool as the collateral. uint collAmt; // amount of collateral token the borrower got from 3rd party pool. uint borrowAmt; // amount of base tokens borrowed from the pool. uint sumRtbStart; // rate times block when the position is created. uint repayDeficit; // repay pool loss } struct NutDist { uint endBlock; uint amount; } /// @dev Get all stake IDs of a lender function getStakeIds(address lender) external view returns (uint[] memory); /// @dev Get all position IDs of a borrower function getPositionIds(address borrower) external view returns (uint[] memory); /// @dev Get the maximum available borrow amount function getMaxBorrowAmount(address token, uint collAmount) external view returns(uint); /// @dev Get the current position while under execution. function getCurrPositionId() external view returns (uint); /// @dev Get the next position ID while under execution. function getNextPositionId() external view returns (uint); /// @dev Get the current sender while under execution function getCurrSender() external view returns (address); function getPosition(uint id) external view returns (Position memory); function getPositionInterest(address token, uint positionId) external view returns(uint); function getPoolInfo(address token) external view returns(uint, uint, uint); /// @dev Add Collateral token from the 3rd party pool to a position function addCollToken(uint posId, uint collAmt) external; /// @dev Borrow tokens from the pool. function borrow(address token, address collAddr, uint baseAmount, uint borrowAmount) external; /// @dev Repays tokens to the pool. function repay(address token, uint repayAmount) external; /// @dev Liquidate a position when conditions are satisfied function liquidate(address token, uint repayAmount) external; /// @dev Settle credit event function distributeCreditLosses( address baseToken, uint collateralLoss, uint poolLoss) external; event addPoolEvent(address bank, uint interestRateA); event stakeEvent(address bank, address owner, uint tranche, uint amount, uint depId); event unstakeEvent(address bank, address owner, uint tranche, uint amount, uint depId); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ICERC20.sol"; import "../interfaces/IAdapter.sol"; import "../interfaces/INutmeg.sol"; import "../lib/Governable.sol"; import "../lib/Math.sol"; contract CompoundAdapter is Governable, IAdapter { using SafeERC20 for IERC20; using SafeMath for uint; struct PosInfo { uint posId; uint collAmt; uint sumIpcStart; } INutmeg public immutable nutmeg; uint private constant MULTIPLIER = 10**18; address[] public baseTokens; // array of base tokens mapping(address => bool) public baseTokenMap; // e.g., Dai mapping(address => address) public tokenPairs; // Dai -> cDai or cDai -> Dai; mapping(address => uint) public totalMintAmt; mapping(address => uint) public sumIpcMap; mapping(uint => PosInfo) public posInfoMap; mapping(address => uint) public totalLoan; mapping(address => uint) public totalCollateral; mapping(address => uint) public totalLoss; constructor(INutmeg nutmegAddr) { nutmeg = nutmegAddr; __Governable__init(); } modifier onlyNutmeg() { require(msg.sender == address(nutmeg), 'only nutmeg can call'); _; } /// @dev Add baseToken collToken pairs function addTokenPair(address baseToken, address collToken) external onlyGov { baseTokenMap[baseToken] = true; tokenPairs[baseToken] = collToken; baseTokens.push(baseToken); } /// @dev Remove baseToken collToken pairs function removeTokenPair(address baseToken) external onlyGov { baseTokenMap[baseToken] = false; tokenPairs[baseToken] = address(0); } /// @notice Open a position. /// @param baseToken Base token of the position. /// @param collToken Collateral token of the position. /// @param baseAmt Amount of collateral in base token. /// @param borrowAmt Amount of base token to be borrowed from nutmeg. function openPosition(address baseToken, address collToken, uint baseAmt, uint borrowAmt) external onlyNutmeg override { require(baseAmt > 0, 'openPosition: invalid base amount'); require(baseTokenMap[baseToken], 'openPosition: invalid baseToken address'); require(tokenPairs[baseToken] == collToken, 'openPosition: invalid cToken address'); uint posId = nutmeg.getCurrPositionId(); INutmeg.Position memory pos = nutmeg.getPosition(posId); require(nutmeg.getCurrSender() == pos.owner, 'openPosition: only owner can initialize this call'); require(IERC20(baseToken).balanceOf(pos.owner) >= baseAmt, 'openPosition: insufficient balance'); // check borrowAmt uint maxBorrowAmt = nutmeg.getMaxBorrowAmount(baseToken, baseAmt); require(borrowAmt <= maxBorrowAmt, "openPosition: borrowAmt exceeds maximum"); require(borrowAmt > baseAmt, "openPosition: borrowAmt is less than collateral"); // borrow base tokens from nutmeg nutmeg.borrow(baseToken, collToken, baseAmt, borrowAmt); _increaseDebtAndCollateral(baseToken, posId); // mint collateral tokens from compound pos = nutmeg.getPosition(posId); (uint result, uint mintAmt) = _doMint(pos, borrowAmt); require(result == 0, 'opnPos: _doMint fail'); if (mintAmt > 0) { uint currSumIpc = _calcLatestSumIpc(collToken); totalMintAmt[collToken] = totalMintAmt[collToken].add(mintAmt); PosInfo storage posInfo = posInfoMap[posId]; posInfo.sumIpcStart = currSumIpc; posInfo.collAmt = mintAmt; // add mintAmt to the position in nutmeg. nutmeg.addCollToken(posId, mintAmt); } emit openPositionEvent(posId, nutmeg.getCurrSender(), baseAmt, borrowAmt); } /// @notice Close a position by the borrower function closePosition() external onlyNutmeg override returns (uint) { uint posId = nutmeg.getCurrPositionId(); INutmeg.Position memory pos = nutmeg.getPosition(posId); require(pos.owner == nutmeg.getCurrSender(), 'closePosition: original caller is not the owner'); uint collAmt = _getCollTokenAmount(pos); (uint result, uint redeemAmt) = _doRedeem(pos, collAmt); require(result == 0, 'clsPos: rdm fail'); // allow nutmeg to receive redeemAmt from the adapter IERC20(pos.baseToken).safeApprove(address(nutmeg), 0); IERC20(pos.baseToken).safeApprove(address(nutmeg), redeemAmt); // repay to nutmeg _decreaseDebtAndCollateral(pos.baseToken, pos.id, redeemAmt); nutmeg.repay(pos.baseToken, redeemAmt); pos = nutmeg.getPosition(posId); totalLoss[pos.baseToken] = totalLoss[pos.baseToken].add(pos.repayDeficit); totalMintAmt[pos.collToken] = totalMintAmt[pos.collToken].sub(pos.collAmt); emit closePositionEvent(posId, nutmeg.getCurrSender(), redeemAmt); return redeemAmt; } /// @notice Liquidate a position function liquidate() external override onlyNutmeg { uint posId = nutmeg.getCurrPositionId(); INutmeg.Position memory pos = nutmeg.getPosition(posId); require(_okToLiquidate(pos), 'liquidate: position is not ready for liquidation yet.'); uint amount = _getCollTokenAmount(pos); (uint result, uint redeemAmt) = _doRedeem(pos, amount); require(result == 0, 'lqdte: rdm fail'); IERC20(pos.baseToken).safeApprove(address(nutmeg), 0); IERC20(pos.baseToken).safeApprove(address(nutmeg), redeemAmt); // liquidate the position in nutmeg. _decreaseDebtAndCollateral(pos.baseToken, posId, redeemAmt); nutmeg.liquidate(pos.baseToken, redeemAmt); pos = nutmeg.getPosition(posId); totalLoss[pos.baseToken] = totalLoss[pos.baseToken].add(pos.repayDeficit); totalMintAmt[pos.collToken] = totalMintAmt[pos.collToken].sub(pos.collAmt); emit liquidateEvent(posId, nutmeg.getCurrSender()); } /// @notice Get value of credit tokens function creditTokenValue(address baseToken) public returns (uint) { address collToken = tokenPairs[baseToken]; require(collToken != address(0), "settleCreditEvent: invalid collateral token" ); uint collTokenBal = ICERC20(collToken).balanceOf(address(this)); return collTokenBal.mul(ICERC20(collToken).exchangeRateCurrent()); } /// @notice Settle credit event /// @param baseToken The base token address function settleCreditEvent( address baseToken, uint collateralLoss, uint poolLoss) external override onlyNutmeg { require(baseTokenMap[baseToken] , "settleCreditEvent: invalid base token" ); require(collateralLoss <= totalCollateral[baseToken], "settleCreditEvent: invalid collateral" ); require(poolLoss <= totalLoan[baseToken], "settleCreditEvent: invalid poolLoss" ); nutmeg.distributeCreditLosses(baseToken, collateralLoss, poolLoss); emit creditEvent(baseToken, collateralLoss, poolLoss); totalLoss[baseToken] = 0; totalLoan[baseToken] = totalLoan[baseToken].sub(poolLoss); totalCollateral[baseToken] = totalCollateral[baseToken].sub(collateralLoss); } function _increaseDebtAndCollateral(address token, uint posId) internal { INutmeg.Position memory pos = nutmeg.getPosition(posId); for (uint i = 0; i < 3; i++) { totalLoan[token] = totalLoan[token].add(pos.loans[i]); } totalCollateral[token] = totalCollateral[token].add(pos.baseAmt); } /// @dev decreaseDebtAndCollateral function _decreaseDebtAndCollateral(address token, uint posId, uint redeemAmt) internal { INutmeg.Position memory pos = nutmeg.getPosition(posId); uint totalLoans = pos.loans[0] + pos.loans[1] + pos.loans[2]; if (redeemAmt >= totalLoans) { totalLoan[token] = totalLoan[token].sub(totalLoans); } else { totalLoan[token] = totalLoan[token].sub(redeemAmt); } totalCollateral[token] = totalCollateral[token].sub(pos.baseAmt); } /// @dev Do the mint from the 3rd party pool.this function _doMint(INutmeg.Position memory pos, uint amount) internal returns(uint, uint) { uint balBefore = ICERC20(pos.collToken).balanceOf(address(this)); require(IERC20(pos.baseToken).approve(pos.collToken, 0), '_doMint approve error'); require(IERC20(pos.baseToken).approve(pos.collToken, amount), '_doMint approve amount error'); uint result = ICERC20(pos.collToken).mint(amount); require(result == 0, '_doMint mint error'); uint balAfter = ICERC20(pos.collToken).balanceOf(address(this)); uint mintAmount = balAfter.sub(balBefore); return (result, mintAmount); } /// @dev Do the redeem from the 3rd party pool. function _doRedeem(INutmeg.Position memory pos, uint amount) internal returns(uint, uint) { uint balBefore = IERC20(pos.baseToken).balanceOf(address(this)); uint result = ICERC20(pos.collToken).redeem(amount); uint balAfter = IERC20(pos.baseToken).balanceOf(address(this)); uint redeemAmt = balAfter.sub(balBefore); return (result, redeemAmt); } /// @dev Get the amount of collToken a position. function _getCollTokenAmount(INutmeg.Position memory pos) internal returns(uint) { uint currSumIpc = _calcLatestSumIpc(pos.collToken); PosInfo storage posInfo = posInfoMap[pos.id]; uint interest = posInfo.collAmt.mul(currSumIpc.sub(posInfo.sumIpcStart)).div(MULTIPLIER); return posInfo.collAmt.add(interest); } /// @dev Calculate the latest sumIpc. /// @param collToken The cToken. function _calcLatestSumIpc(address collToken) internal returns(uint) { uint balance = ICERC20(collToken).balanceOf(address(this)); uint mintBalance = totalMintAmt[collToken]; uint interest = mintBalance > balance ? mintBalance.sub(balance) : 0; uint currIpc = (mintBalance == 0) ? 0 : (interest.mul(MULTIPLIER)).div(mintBalance); if (currIpc > 0){ sumIpcMap[collToken] = sumIpcMap[collToken].add(currIpc); } return sumIpcMap[collToken]; } /// @dev Check if the position is eligible to be liquidated. function _okToLiquidate(INutmeg.Position memory pos) internal view returns(bool) { bool ok = false; uint interest = nutmeg.getPositionInterest(pos.baseToken, pos.id); if (interest.mul(2) >= pos.baseAmt) { ok = true; } return ok; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICERC20 { function mint(uint) external returns (uint); function redeem(uint) external returns (uint); function transfer(address dst, uint amount) external returns (bool); function balanceOf(address) external view returns (uint); function redeemUnderlying(uint) external returns (uint); function exchangeRateCurrent() external returns (uint); function supplyRatePerBlock() external returns (uint); function approve(address spender, uint amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IWETH { function balanceOf(address user) external returns (uint); function approve(address to, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function deposit() external payable; function withdraw(uint) external; } // SPDX-License-Identifier: MIT // Modified from original alphahomora which used 0.6.12 pragma solidity 0.7.6; interface ICErc20 { function decimals() external returns (uint8); function underlying() external returns (address); function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function balanceOf(address user) external view returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../Nutmeg.sol"; // @notice This contract is a version of Nutmeg that contains additional // interfaces for testing contract NutmegAltA is Nutmeg { //@notice output version string function getVersionString() external virtual pure returns (string memory) { return "nutmegalta"; } } contract NutmegAltB is Nutmeg { //@notice output version string function getVersionString() external virtual pure returns (string memory) { return "nutmegaltb"; } } import "../NutDistributor.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // @notice This contract is a version of NutDistributor that allows // the epoch intervals to be changed for testing contract NutDistributorAltA is NutDistributor { //@notice output version string function getVersionString() external virtual pure override returns (string memory) { return "nutdistributoralta"; } } contract NutDistributorAltB is NutDistributor { //@notice output version string function getVersionString() external virtual pure override returns (string memory) { return "nutdistributoraltb"; } } import "./MockERC20.sol"; contract MockERC20AltA is MockERC20("MockERC20AltA", "MOCKERC20ALTA", 18) { } contract MockERC20AltB is MockERC20("MockERC20AltB", "MOCKERC20ALTB", 18) { } contract MockERC20AltC is MockERC20("MockERC20AltC", "MOCKERC20ALTC", 6) { } import "./MockCERC20.sol"; contract MockCERC20AltA is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base(tokenAddr, "MockCERC20 AltA", "MOCKCERC20ALTA", 18) { } } contract MockCERC20AltB is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base(tokenAddr, "MockCERC20 AltB", "MOCKCERC20ALTB", 18) { } } contract MockCERC20AltC is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base(tokenAddr, "MockCERC20 AltC", "MOCKCERC20ALTC", 6) { } } import "../adapters/CompoundAdapter.sol"; import "../interfaces/INutmeg.sol"; contract CompoundAdapterAltA is CompoundAdapter { constructor(INutmeg nutmegAddr) CompoundAdapter(nutmegAddr) { } } contract CompoundAdapterAltB is CompoundAdapter { constructor(INutmeg nutmegAddr) CompoundAdapter(nutmegAddr) { } } // SPDX-License-Identifier: MIT // Mock ERC20 token for testing pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) ERC20(name, symbol) { _setupDecimals(decimals); } function mint(address to, uint amount) external { _mint(to, amount); } } // SPDX-License-Identifier: MIT // Mock ERC20 token for testing pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/ICERC20.sol"; contract MockCERC20Base is ICERC20, ERC20 { address public immutable token; using SafeERC20 for IERC20; using SafeMath for uint; uint private constant MULTIPLIER = 10**18; uint public exchangeRate; bool public returnError; constructor( address tokenAddr, string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) { token = tokenAddr; exchangeRate = MULTIPLIER; returnError = false; _setupDecimals(decimals_); } function mint(uint amount) external override returns (uint) { if (returnError) return 1; IERC20(token).safeTransferFrom(msg.sender, address(this), amount); _mint(msg.sender, amount.mul(MULTIPLIER).div(exchangeRate)); return 0; } function redeem(uint amount) external override returns (uint) { if (returnError) return 1; IERC20(token).safeTransfer( msg.sender, amount.mul(exchangeRate).div(MULTIPLIER) ); _burn(msg.sender, amount); return 0; } function redeemUnderlying(uint amount) external override returns (uint) { if (returnError) return 1; IERC20(token).safeTransfer(msg.sender, amount); _burn( msg.sender, amount.mul(MULTIPLIER).div(exchangeRate) ); return 0; } function exchangeRateCurrent() external view override returns (uint) { return exchangeRate; } function supplyRatePerBlock() external pure override returns (uint) { return 0; } function balanceOf(address account) public override(ERC20, ICERC20) view returns (uint) { return ERC20.balanceOf(account); } function approve(address account, uint amount) public override(ERC20, ICERC20) returns (bool) { return ERC20.approve(account, amount); } function transfer(address dst, uint amount) public override(ERC20, ICERC20) returns (bool) { return ERC20.transfer(dst, amount); } function setExchangeRate(uint e) external { exchangeRate = e; } function setError(bool b) external { returnError = b; } } contract MockCERC20 is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base( tokenAddr, "MockCERC20", "MCERC20", 18 ) { } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import './IERC20Mock.sol'; // Export ICEther interface for mainnet-fork testing. interface ICEtherMock is IERC20Mock { function mint() external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Export IERC20 interface for mainnet-fork testing. interface IERC20Mock is IERC20 { function name() external view returns (string memory); function owner() external view returns (address); function issue(uint) external; function issue(address, uint) external; function mint(address, uint) external; function mint( address, uint, uint ) external returns (bool); function configureMinter(address, uint) external returns (bool); function masterMinter() external view returns (address); function deposit() external payable; function deposit(uint) external; function decimals() external view returns (uint); function target() external view returns (address); function erc20Impl() external view returns (address); function custodian() external view returns (address); function requestPrint(address, uint) external returns (bytes32); function confirmPrint(bytes32) external; function invest(uint) external; function increaseSupply(uint) external; function supplyController() external view returns (address); function getModules() external view returns (address[] memory); function addMinter(address) external; function governance() external view returns (address); function core() external view returns (address); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function symbol() external view returns (string memory); function getFinalTokens() external view returns (address[] memory); function joinPool(uint, uint[] memory) external; function getBalance(address) external view returns (uint); function createTokens(uint) external returns (bool); function resolverAddressesRequired() external view returns (bytes32[] memory addresses); function exchangeRateStored() external view returns (uint); function accrueInterest() external returns (uint); function resolver() external view returns (address); function repository(bytes32) external view returns (address); function underlying() external view returns (address); function mint(uint) external returns (uint); function redeem(uint) external returns (uint); function redeemUnderlying(uint) external returns (uint); function minter() external view returns (address); function borrow(uint) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IUNISWAP { function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual payable returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../lib/Math.sol'; contract Formula { using SafeMath for uint; constructor (){} function div(uint a, uint b) external pure returns(uint){ return a.div(b); } function mul(uint a, uint b) external pure returns(uint){ return a.mul(b); } function add(uint a, uint b) external pure returns(uint){ return a.add(b); } function sub(uint a, uint b) external pure returns(uint){ return a.sub(b); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/proxy/Initializable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import '../adapters/CompoundAdapter.sol'; import '../interfaces/IAdapter.sol'; import '../interfaces/INutmeg.sol'; contract MockAdapter is CompoundAdapter { using SafeERC20 for IERC20; using SafeMath for uint; event Received(address, uint); address public immutable weth; constructor(INutmeg nutmegAddr, address wethAddr) CompoundAdapter(nutmegAddr) { weth = wethAddr; } function test() external pure { } function testFail() external pure { require(false, "fail"); } function testBorrow(uint amount) external { INutmeg(nutmeg).borrow(weth, address(this), amount-10, amount); } function testCurrPositionId(uint pos) external view { uint posret = INutmeg(nutmeg).getCurrPositionId(); require(pos == posret, 'testCurrentPosition failed'); } function testPosition(uint pos) external view { INutmeg.Position memory p = INutmeg(nutmeg).getPosition(pos); require(p.id == pos, 'testPosition failed'); } function testRepay(address token, uint repayAmount) external { INutmeg(nutmeg).repay(token, repayAmount); } receive() external payable { emit Received(msg.sender, msg.value); } } /* Local Variables: */ /* mode: javascript */ /* js-indent-level: 2 */ /* End: */ // SPDX-License-Identifier: MIT // Mock WETH token for testing pragma solidity 0.7.6; contract MockWETH { string public constant name = 'Wrapped Ether'; string public constant symbol = 'WETH'; uint8 public constant decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; receive() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) external { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; payable(msg.sender).transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() external view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) external returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != type(uint).max) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../NutDistributor.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // @notice This contract is a version of NutDistributor that allows // the epoch intervals to be changed for testing contract TestNutDistributor is NutDistributor { using SafeMath for uint; function initialize ( address nutAddr, address _governor, uint blocks_per_epoch ) external initializer { initialize(nutAddr, _governor); BLOCKS_PER_EPOCH = blocks_per_epoch; // config echoMap which indicates how many tokens will be distributed at each epoch for (uint i = 0; i < NUM_EPOCH; i++) { Echo storage echo = echoMap[i]; echo.id = i; echo.endBlock = DIST_START_BLOCK.add(BLOCKS_PER_EPOCH.mul(i.add(1))); uint amount = DIST_START_AMOUNT.div(i.add(1)); if (amount < DIST_MIN_AMOUNT) { amount = DIST_MIN_AMOUNT; } echo.amount = amount; } } //@notice output version string function getVersionString() external virtual pure override returns (string memory) { return "test.nutdistrib"; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../Nutmeg.sol"; // @notice This contract is a version of Nutmeg that contains additional // interfaces for testing contract TestNutmeg is Nutmeg { function _testSetBaseAmt ( uint posId, uint baseAmt ) external { positionMap[posId].baseAmt = baseAmt; } function _forceAccrueInterest( address token ) external { accrueInterest(token); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../lib/Governable.sol'; import "../interfaces/IPriceOracle.sol"; contract PriceOracle is IPriceOracle, Governable { mapping(address => uint) public priceMap; event setPriceEvent(address token, uint price); constructor() { __Governable__init(); } /// @notice Return the value of the given token in ETH. /// @param token The ERC20 token function getPrice(address token) external view override returns (uint) { uint price = priceMap[token]; require(price != 0, 'getPrice: price not found.'); return price; } /// @notice Set the prices of the given tokens. /// @param tokens The tokens to set the prices. /// @param prices The prices of tokens. function setPrices(address[] memory tokens, uint[] memory prices) external onlyGov { require(tokens.length == prices.length, 'setPrices: lengths do not match'); for (uint i = 0; i < tokens.length; i++) { priceMap[tokens[i]] = prices[i]; emit setPriceEvent(tokens[i], prices[i]); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // 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; 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"); } } }
@notice Return current position ID
function getCurrPositionId() external override view returns (uint) { return CURR_POSITION_ID; }
1,495,864
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 2000, 783, 1754, 1599, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14135, 86, 2555, 548, 1435, 3903, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 4706, 54, 67, 15258, 67, 734, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; contract SimpleStorage { uint storedData; event LogSet(address sender, uint newValue); function set(uint x) public { storedData = x; emit LogSet(msg.sender, x); } function get() public view returns (uint) { return storedData; } struct Organization { string organizationName; mapping(uint => Group) groups; mapping(uint => Member) members; } Organization thisOrganization; // @dev Sets serviceProvider to the address that instantiated the project // @dev Sets the appropriate project details // when going back to vscode: string memory organizationName, thisOrganization.name = organizationName constructor() public { thisOrganization.organizationName = "Google"; } function readOrganizationName() public view returns(string memory) { return thisOrganization.organizationName; } struct Member { string memberName; address memberAddress; } // @dev Used to track member numbers uint public memberIdGenerator = 1; function createMember(string memory memberName, address memberAddress) public returns(uint) { // require that member address not already belong to a member Member storage newMember = thisOrganization.members[memberIdGenerator]; newMember.memberName = memberName; newMember.memberAddress = memberAddress; memberIdGenerator++; return memberIdGenerator - 1; } struct Group { uint subGroupOf; string groupName; uint[] membersInGroup; uint numberOfMembersInGroup; } // @dev Used to track group numbers uint public groupIdGenerator = 1; function createGroup(string memory groupName, uint subGroupOf) public returns(uint) { Group storage newGroup = thisOrganization.groups[memberIdGenerator]; newGroup.groupName = groupName; newGroup.subGroupOf = subGroupOf; groupIdGenerator++; return groupIdGenerator - 1; } // @param number of member who will be joining // @param number of group that member will join function joinGroup(uint memberNumber, uint groupNumber) public { thisOrganization.groups[groupNumber].membersInGroup.push(memberNumber); thisOrganization.groups[groupNumber].numberOfMembersInGroup++; } function readGroup(uint groupNumber) public view returns(uint, uint, string memory, uint) // group number, subGroupOf, group name, number of members in group { uint subGroupOf = thisOrganization.groups[groupNumber].subGroupOf; uint numberOfMembersInGroup = thisOrganization.groups[groupNumber].numberOfMembersInGroup; string memory groupName = thisOrganization.groups[groupNumber].groupName; return (groupNumber, subGroupOf, groupName, numberOfMembersInGroup); } function readMember(uint memberNumber) public view returns (uint, string memory, address) { string memory memberName = thisOrganization.members[memberNumber].memberName; address memberAddress = thisOrganization.members[memberNumber].memberAddress; return (memberNumber, memberName, memberAddress); } function readMemberListInGroup(uint groupNumber) public view returns (uint[] memory) { uint[] memory membersInGroup = thisOrganization.groups[groupNumber].membersInGroup; return(membersInGroup); } struct Vote { uint memberNumber; bool yesIfTrue; } mapping (uint => Vote) votes; //return error if member has already voted function executeVote(uint memberNumber, bool yesIfTrue) public { votes[memberNumber].memberNumber = memberNumber; votes[memberNumber].yesIfTrue = yesIfTrue; } // i think this is not needed in UI, just for testing // return error if member has not voted function readMemberVote(uint memberNumber) public view returns (bool) { bool memberVote = votes[memberNumber].yesIfTrue; return memberVote; } // uses for loop to count votes from votes mapping // if majority in favor returns true // called by splitGroup function // i think this is not needed in UI, just for testing function countVotes(uint groupNumber) public view returns(bool) { uint yesVote = 0; uint noVote = 0; uint[] memory membersInGroup = readMemberListInGroup(groupNumber); for (uint i = 0; i < membersInGroup.length; i++) { if (readMemberVote(membersInGroup[i]) == true) { yesVote++; } if (readMemberVote(membersInGroup[i]) == false) { noVote++; } } if (yesVote > noVote) { return true; } else { return false; } } uint[] newOldArray; // state variable needs is global for solidity workaround function splitGroup(uint oldGroupNumber, uint[] memory membersToSplit, uint newGroupNumber) public { require(countVotes(oldGroupNumber) == true, "Cannot split group because members have not voted in favor"); uint[] memory oldArray = thisOrganization.groups[oldGroupNumber].membersInGroup; //uint[] memory newArray = thisOrganization.groups[newGroupNumber].membersInGroup; //uint[] memory newOldArray; // this array will replace membersInGroup in old group bool found = false; for (uint i=0; i < oldArray.length; i++) { found = false; for (uint j=0; j < membersToSplit.length; j++) { if (oldArray[i] == membersToSplit[j]) { found = true; break; } } if (found == false) { newOldArray.push(oldArray[i]); } } thisOrganization.groups[oldGroupNumber].membersInGroup = newOldArray; thisOrganization.groups[newGroupNumber].membersInGroup = membersToSplit; } }
uses for loop to count votes from votes mapping if majority in favor returns true called by splitGroup function i think this is not needed in UI, just for testing
function countVotes(uint groupNumber) public view returns(bool) { uint yesVote = 0; uint noVote = 0; uint[] memory membersInGroup = readMemberListInGroup(groupNumber); for (uint i = 0; i < membersInGroup.length; i++) { if (readMemberVote(membersInGroup[i]) == true) { yesVote++; } if (readMemberVote(membersInGroup[i]) == false) { noVote++; } } if (yesVote > noVote) { return true; return false; } }
2,478,361
[ 1, 4625, 348, 7953, 560, 30, 225, 4692, 364, 2798, 358, 1056, 19588, 628, 19588, 2874, 309, 7888, 560, 316, 18552, 1135, 638, 2566, 635, 1416, 1114, 445, 277, 15507, 333, 353, 486, 3577, 316, 6484, 16, 2537, 364, 7769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 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31, 203, 3639, 2254, 8526, 3778, 4833, 31138, 273, 855, 4419, 682, 31138, 12, 1655, 1854, 1769, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 4833, 31138, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 896, 4419, 19338, 12, 7640, 31138, 63, 77, 5717, 422, 638, 13, 288, 203, 7734, 12465, 19338, 9904, 31, 203, 5411, 289, 203, 5411, 309, 261, 896, 4419, 19338, 12, 7640, 31138, 63, 77, 5717, 422, 629, 13, 288, 203, 7734, 1158, 19338, 9904, 31, 203, 5411, 289, 203, 2398, 203, 3639, 289, 203, 3639, 309, 261, 9707, 19338, 405, 1158, 19338, 13, 288, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.6; import "./Token.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TokenBank { uint tokenEthRate = 1; event BuyTokens(address buyer, uint256 amountOfETH, uint256 amountOfTokens); Token private token; constructor(Token _token) public { token = _token; } function buyTokens() public payable { require(msg.value > 0, "Invalid Amount"); uint amountToBuy = (msg.value / 10**18 )* tokenEthRate; uint bankTokenBalance = token.balanceOf(address(this)); require(bankTokenBalance >= amountToBuy,"Token Bank Has Insufficient Tokens"); bool sent = token.transfer(msg.sender, amountToBuy); require(sent, "Failed to transfer token to user"); emit BuyTokens(msg.sender,msg.value,amountToBuy); } function sellTokens(uint256 tokenAmountToSell) public { //does not work yet // Check that the requested amount of tokens to sell is more than 0 require(tokenAmountToSell > 0, "Specify an amount of token greater than zero"); // Check that the user's token balance is enough to do the swap uint256 userBalance = token.balanceOf(msg.sender); require(userBalance >= tokenAmountToSell, "Your balance is lower than the amount of tokens you want to sell"); // Check that the Vendor's balance is enough to do the swap uint256 amountOfETHToTransfer = tokenAmountToSell / tokenEthRate; uint256 bankEthBalance = address(this).balance; require(bankEthBalance >= amountOfETHToTransfer, "Vendor has not enough funds to accept the sell request"); (bool sent) = token.transferFrom(msg.sender, address(this), tokenAmountToSell); require(sent, "Failed to transfer tokens from user to vendor"); (sent,) = msg.sender.call{value: amountOfETHToTransfer}(""); require(sent, "Failed to send ETH to the user"); } }
Check that the Vendor's balance is enough to do the swap
uint256 amountOfETHToTransfer = tokenAmountToSell / tokenEthRate;
12,721,778
[ 1, 4625, 348, 7953, 560, 30, 225, 2073, 716, 326, 776, 5227, 1807, 11013, 353, 7304, 358, 741, 326, 7720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3844, 951, 1584, 44, 774, 5912, 273, 1147, 6275, 774, 55, 1165, 342, 1147, 41, 451, 4727, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xb8EC5Ee136A409ce5035AE59B1d95E244ee2a1b2/sources/contracts/StarFarm.sol
We do some fancy math here. Basically, any point in time, the amount of STARs entitled to a user but is pending to be distributed is: pending reward = (user.amount * pool.accStarPerShare) - user.rewardDebt Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: 1. The pool's `accStarPerShare` (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.
struct UserInfo { uint256 lastDeposit; }
13,264,575
[ 1, 4625, 348, 7953, 560, 30, 225, 1660, 741, 2690, 31701, 4233, 2674, 18, 7651, 1230, 16, 1281, 1634, 316, 813, 16, 326, 3844, 434, 21807, 87, 3281, 305, 1259, 358, 279, 729, 1496, 353, 4634, 358, 506, 16859, 353, 30, 282, 4634, 19890, 273, 261, 1355, 18, 8949, 380, 2845, 18, 8981, 18379, 2173, 9535, 13, 300, 729, 18, 266, 2913, 758, 23602, 3497, 4009, 502, 279, 729, 443, 917, 1282, 578, 598, 9446, 87, 511, 52, 2430, 358, 279, 2845, 18, 13743, 1807, 4121, 10555, 30, 282, 404, 18, 1021, 2845, 1807, 1375, 8981, 18379, 2173, 9535, 68, 261, 464, 1375, 2722, 17631, 1060, 1768, 24065, 5571, 3526, 18, 282, 576, 18, 2177, 17024, 326, 4634, 19890, 3271, 358, 18423, 19, 1614, 1758, 18, 282, 890, 18, 2177, 1807, 1375, 8949, 68, 5571, 3526, 18, 282, 1059, 18, 2177, 1807, 1375, 266, 2913, 758, 23602, 68, 5571, 3526, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 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, 25003, 288, 203, 3639, 2254, 5034, 1142, 758, 1724, 31, 203, 565, 289, 203, 202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; contract Owned { address public aOwner; address public coOwner1; address public coOwner2; constructor() public { aOwner = msg.sender; coOwner1 = msg.sender; coOwner2 = msg.sender; } /* Modifiers */ modifier onlyOwner { require(msg.sender == aOwner || msg.sender == coOwner1 || msg.sender == coOwner2); _; } function setCoOwner1(address _coOwner) public onlyOwner { coOwner1 = _coOwner; } function setCoOwner2(address _coOwner) public onlyOwner { coOwner2 = _coOwner; } } contract XEther is Owned { /* Structurs and variables */ uint256 public totalInvestmentAmount = 0; uint256 public ownerFeePercent = 50; // 5% uint256 public investorsFeePercent = 130; // 13% uint256 public curIteration = 1; uint256 public depositsCount = 0; uint256 public investorsCount = 1; uint256 public bankAmount = 0; uint256 public feeAmount = 0; uint256 public toGwei = 1000000000; // or 1e9, helper vars uint256 public minDepositAmount = 20000000; // minimum deposit uint256 public minLotteryAmount = 100000000; // minimum to participate in lottery uint256 public minInvestmentAmount = 5 ether; // min for investment bool public isWipeAllowed = true; // wipe only if bank almost became empty uint256 public investorsCountLimit = 7; // maximum investors uint256 public lastTransaction = now; // Stage variables uint256 private stageStartTime = now; uint private currentStage = 1; uint private stageTime = 86400; // time of stage in minutes uint private stageMin = 0; uint private stageMax = 72; // lottery uint256 public jackpotBalance = 0; uint256 public jackpotPercent = 20; // 2% uint256 _seed; // Deposits mapping mapping(uint256 => address) public depContractidToAddress; mapping(uint256 => uint256) public depContractidToAmount; mapping(uint256 => bool) public depContractidToLottery; // Investors mapping mapping(uint256 => address) public investorsAddress; mapping(uint256 => uint256) public investorsInvested; mapping(uint256 => uint256) public investorsComissionPercent; mapping(uint256 => uint256) public investorsEarned; /* Events */ event EvDebug ( uint amount ); /* New income transaction*/ event EvNewDeposit ( uint256 iteration, uint256 bankAmount, uint256 index, address sender, uint256 amount, uint256 multiplier, uint256 time ); /* New investment added */ event EvNewInvestment ( uint256 iteration, uint256 bankAmount, uint256 index, address sender, uint256 amount, uint256[] investorsFee ); /* Collect investors earned, when some one get payment */ event EvInvestorsComission ( uint256 iteration, uint256[] investorsComission ); /* Bank amount increased */ event EvUpdateBankAmount ( uint256 iteration, uint256 deposited, uint256 balance ); /* Payout for deposit */ event EvDepositPayout ( uint256 iteration, uint256 bankAmount, uint256 index, address receiver, uint256 amount, uint256 fee, uint256 jackpotBalance ); /* newIteration */ event EvNewIteration ( uint256 iteration ); /* No more funds in the bank, need actions (e.g. new iteration) */ event EvBankBecomeEmpty ( uint256 iteration, uint256 index, address receiver, uint256 payoutAmount, uint256 bankAmount ); /* Investor get payment */ event EvInvestorPayout ( uint256 iteration, uint256 bankAmount, uint256 index, uint256 amount, bool status ); /* Investors get payment */ event EvInvestorsPayout ( uint256 iteration, uint256 bankAmount, uint256[] payouts, bool[] statuses ); /* New stage - time of withdraw is tapered */ event EvStageChanged ( uint256 iteration, uint timeDiff, uint stage ); /* Lottery numbers */ event EvLotteryWin ( uint256 iteration, uint256 contractId, address winer, uint256 amount ); /* Check address with code*/ event EvConfimAddress ( address sender, bytes16 code ); /* Lottery numbers */ event EvLotteryNumbers ( uint256 iteration, uint256 index, uint256[] lotteryNumbers ); /* Manually update Jackpot amount */ event EvUpdateJackpot ( uint256 iteration, uint256 amount, uint256 balance ); /*---------- constructor ------------*/ constructor() public { investorsAddress[0] = aOwner; investorsInvested[0] = 0; investorsComissionPercent[0] = 0; investorsEarned[0] = 0; } /*--------------- public methods -----------------*/ function() public payable { require(msg.value > 0 && msg.sender != address(0)); uint256 amount = msg.value / toGwei; // convert to gwei if (amount >= minDepositAmount) { lastTransaction = block.timestamp; newDeposit(msg.sender, amount); } else { bankAmount += amount; } } function newIteration() public onlyOwner { require(isWipeAllowed); payoutInvestors(); investorsInvested[0] = 0; investorsCount = 1; totalInvestmentAmount = 0; bankAmount = 0; feeAmount = 0; depositsCount = 0; // Stage vars update currentStage = 1; stageStartTime = now; stageMin = 0; stageMax = 72; curIteration += 1; emit EvNewIteration(curIteration); uint256 realBalance = address(this).balance - (jackpotBalance * toGwei); if (realBalance > 0) { aOwner.transfer(realBalance); } } function updateBankAmount() public onlyOwner payable { require(msg.value > 0 && msg.sender != address(0)); uint256 amount = msg.value / toGwei; isWipeAllowed = false; bankAmount += amount; totalInvestmentAmount += amount; emit EvUpdateBankAmount(curIteration, amount, bankAmount); recalcInvestorsFee(msg.sender, amount); } function newInvestment() public payable { require(msg.value >= minInvestmentAmount && msg.sender != address(0)); address sender = msg.sender; uint256 investmentAmount = msg.value / toGwei; // convert to gwei addInvestment(sender, investmentAmount); } /* Payout */ function depositPayout(uint depositIndex, uint pAmount) public onlyOwner returns(bool) { require(depositIndex < depositsCount && depositIndex >= 0 && depContractidToAmount[depositIndex] > 0); require(pAmount <= 5); uint256 payoutAmount = depContractidToAmount[depositIndex]; payoutAmount += (payoutAmount * pAmount) / 100; if (payoutAmount > bankAmount) { isWipeAllowed = true; // event payment not enaught bank amount emit EvBankBecomeEmpty(curIteration, depositIndex, depContractidToAddress[depositIndex], payoutAmount, bankAmount); return false; } uint256 ownerComission = (payoutAmount * ownerFeePercent) / 1000; investorsEarned[0] += ownerComission; uint256 addToJackpot = (payoutAmount * jackpotPercent) / 1000; jackpotBalance += addToJackpot; uint256 investorsComission = (payoutAmount * investorsFeePercent) / 1000; uint256 payoutComission = ownerComission + addToJackpot + investorsComission; uint256 paymentAmount = payoutAmount - payoutComission; bankAmount -= payoutAmount; feeAmount += ownerComission + investorsComission; emit EvDepositPayout(curIteration, bankAmount, depositIndex, depContractidToAddress[depositIndex], paymentAmount, payoutComission, jackpotBalance); updateInvestorsComission(investorsComission); depContractidToAmount[depositIndex] = 0; paymentAmount *= toGwei; // get back to wei depContractidToAddress[depositIndex].transfer(paymentAmount); if (depContractidToLottery[depositIndex]) { lottery(depContractidToAddress[depositIndex], depositIndex); } return true; } /* Payout to investors */ function payoutInvestors() public { uint256 paymentAmount = 0; bool isSuccess = false; uint256[] memory payouts = new uint256[](investorsCount); bool[] memory statuses = new bool[](investorsCount); uint256 mFeeAmount = feeAmount; uint256 iteration = curIteration; for (uint256 i = 0; i < investorsCount; i++) { uint256 iEarned = investorsEarned[i]; if (iEarned == 0) { continue; } paymentAmount = iEarned * toGwei; // get back to wei mFeeAmount -= iEarned; investorsEarned[i] = 0; isSuccess = investorsAddress[i].send(paymentAmount); payouts[i] = iEarned; statuses[i] = isSuccess; } emit EvInvestorsPayout(iteration, bankAmount, payouts, statuses); feeAmount = mFeeAmount; } /* Payout to investor */ function payoutInvestor(uint256 investorId) public { require (investorId < investorsCount && investorsEarned[investorId] > 0); uint256 paymentAmount = investorsEarned[investorId] * toGwei; // get back to wei feeAmount -= investorsEarned[investorId]; investorsEarned[investorId] = 0; bool isSuccess = investorsAddress[investorId].send(paymentAmount); emit EvInvestorPayout(curIteration, bankAmount, investorId, paymentAmount, isSuccess); } /* Helper function to check sender */ function confirmAddress(bytes16 code) public { emit EvConfimAddress(msg.sender, code); } /* Show depositers and investors info */ function depositInfo(uint256 contractId) view public returns(address _address, uint256 _amount, bool _participateInLottery) { return (depContractidToAddress[contractId], depContractidToAmount[contractId] * toGwei, depContractidToLottery[contractId]); } /* Show investors info by id */ function investorInfo(uint256 contractId) view public returns( address _address, uint256 _invested, uint256 _comissionPercent, uint256 earned ) { return (investorsAddress[contractId], investorsInvested[contractId] * toGwei, investorsComissionPercent[contractId], investorsEarned[contractId] * toGwei); } function showBankAmount() view public returns(uint256 _bankAmount) { return bankAmount * toGwei; } function showInvestorsComission() view public returns(uint256 _investorsComission) { return feeAmount * toGwei; } function showJackpotBalance() view public returns(uint256 _jackpotBalance) { return jackpotBalance * toGwei; } function showStats() view public returns( uint256 _ownerFeePercent, uint256 _investorsFeePercent, uint256 _jackpotPercent, uint256 _minDepositAmount, uint256 _minLotteryAmount,uint256 _minInvestmentAmount, string info ) { return (ownerFeePercent, investorsFeePercent, jackpotPercent, minDepositAmount * toGwei, minLotteryAmount * toGwei, minInvestmentAmount, 'To get real percentages divide them to 10'); } /* Function to change variables */ function updateJackpotBalance() public onlyOwner payable { require(msg.value > 0 && msg.sender != address(0)); jackpotBalance += msg.value / toGwei; emit EvUpdateJackpot(curIteration, msg.value, jackpotBalance); } /* Allow withdraw jackpot only if there are no transactions more then month*/ function withdrawJackpotBalance(uint amount) public onlyOwner { require(jackpotBalance >= amount / toGwei && msg.sender != address(0)); // withdraw jacpot if no one dont play more then month require(now - lastTransaction > 4 weeks); uint256 tmpJP = amount / toGwei; jackpotBalance -= tmpJP; // Lottery payment aOwner.transfer(amount); emit EvUpdateJackpot(curIteration, amount, jackpotBalance); } /*--------------- private methods -----------------*/ function newDeposit(address _address, uint depositAmount) private { uint256 randMulti = random(100) + 200; uint256 rndX = random(1480); uint256 _time = getRandomTime(rndX); // Check is depositer hit the bonus number. Else return old multiplier. randMulti = checkForBonuses(rndX, randMulti); uint256 contractid = depositsCount; depContractidToAddress[contractid] = _address; depContractidToAmount[contractid] = (depositAmount * randMulti) / 100; depContractidToLottery[contractid] = depositAmount >= minLotteryAmount; depositsCount++; bankAmount += depositAmount; emit EvNewDeposit(curIteration, bankAmount, contractid, _address, depositAmount, randMulti, _time); } function addInvestment(address sender, uint256 investmentAmount) private { require( (totalInvestmentAmount < totalInvestmentAmount + investmentAmount) && (bankAmount < bankAmount + investmentAmount) ); totalInvestmentAmount += investmentAmount; bankAmount += investmentAmount; recalcInvestorsFee(sender, investmentAmount); } function recalcInvestorsFee(address sender, uint256 investmentAmount) private { uint256 investorIndex = 0; bool isNewInvestor = true; uint256 investorFeePercent = 0; uint256[] memory investorsFee = new uint256[](investorsCount+1); for (uint256 i = 0; i < investorsCount; i++) { if (investorsAddress[i] == sender) { investorIndex = i; isNewInvestor = false; investorsInvested[i] += investmentAmount; } investorFeePercent = percent(investorsInvested[i], totalInvestmentAmount, 3); investorsComissionPercent[i] = investorFeePercent; investorsFee[i] = investorFeePercent; } if (isNewInvestor) { if (investorsCount > investorsCountLimit) revert(); // Limit investors count investorFeePercent = percent(investmentAmount, totalInvestmentAmount, 3); investorIndex = investorsCount; investorsAddress[investorIndex] = sender; investorsInvested[investorIndex] = investmentAmount; investorsComissionPercent[investorIndex] = investorFeePercent; investorsEarned[investorIndex] = 0; investorsFee[investorIndex] = investorFeePercent; investorsCount++; } emit EvNewInvestment(curIteration, bankAmount, investorIndex, sender, investmentAmount, investorsFee); } function updateInvestorsComission(uint256 amount) private { uint256 investorsTotalIncome = 0; uint256[] memory investorsComission = new uint256[](investorsCount); for (uint256 i = 1; i < investorsCount; i++) { uint256 investorIncome = (amount * investorsComissionPercent[i]) / 1000; investorsEarned[i] += investorIncome; investorsComission[i] = investorsEarned[i]; investorsTotalIncome += investorIncome; } investorsEarned[0] += amount - investorsTotalIncome; emit EvInvestorsComission(curIteration, investorsComission); } function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) { uint _numerator = numerator * 10 ** (precision+1); uint _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); } function random(uint numMax) private returns (uint256 result) { _seed = uint256(keccak256(abi.encodePacked( _seed, blockhash(block.number - 1), block.coinbase, block.difficulty ))); return _seed % numMax; } function getRandomTime(uint num) private returns (uint256 result) { uint rndHours = random(68) + 4; result = 72 - (2 ** ((num + 240) / 60) + 240) % rndHours; checkStageCondition(); result = numStageRecalc(result); return (result < 4) ? 4 : result; } function checkForBonuses(uint256 number, uint256 multiplier) private pure returns (uint256 newMultiplier) { if (number == 8) return 1000; if (number == 12) return 900; if (number == 25) return 800; if (number == 37) return 700; if (number == 42) return 600; if (number == 51) return 500; if (number == 63 || number == 65 || number == 67) { return 400; } return multiplier; } /* * Check for time of current stage, in case of timeDiff bigger then stage time * new stage states set. */ function checkStageCondition() private { uint timeDiff = now - stageStartTime; if (timeDiff > stageTime && currentStage < 3) { currentStage++; stageMin += 10; stageMax -= 10; stageStartTime = now; emit EvStageChanged(curIteration, timeDiff, currentStage); } } /* * Recalculate hours regarding current stage and counting chance of bonus. */ function numStageRecalc(uint256 curHours) private returns (uint256 result) { uint chance = random(110) + 1; if (currentStage > 1 && chance % 9 != 0) { if (curHours > stageMax) return stageMax; if (curHours < stageMin) return stageMin; } return curHours; } /* * Lottery main function */ function lottery(address sender, uint256 index) private { bool lotteryWin = false; uint256[] memory lotteryNumbers = new uint256[](7); (lotteryWin, lotteryNumbers) = randomizerLottery(blockhash(block.number - 1), sender); emit EvLotteryNumbers(curIteration, index, lotteryNumbers); if (lotteryWin) { emit EvLotteryWin(curIteration, index, sender, jackpotBalance); uint256 tmpJP = jackpotBalance * toGwei; // get back to wei jackpotBalance = 0; // Lottery payment sender.transfer(tmpJP); } } /* * Lottery generator numbers by given hash. */ function randomizerLottery(bytes32 hash, address sender) private returns(bool, uint256[] memory) { uint256[] memory lotteryNumbers = new uint256[](7); bytes32 userHash = keccak256(abi.encodePacked( hash, sender, random(999) )); bool win = true; for (uint i = 0; i < 7; i++) { uint position = i + random(1); bytes1 charAtPos = charAt(userHash, position); uint8 firstNums = getLastN(charAtPos, 4); uint firstNumInt = uint(firstNums); if (firstNumInt > 9) { firstNumInt = 16 - firstNumInt; } lotteryNumbers[i] = firstNumInt; if (firstNums != 7) { win = false; } } return (win, lotteryNumbers); } function charAt(bytes32 b, uint char) private pure returns (bytes1) { return bytes1(uint8(uint(b) / (2**((31 - char) * 8)))); } function getLastN(bytes1 a, uint8 n) private pure returns (uint8) { uint8 lastN = uint8(a) % uint8(2) ** n; return lastN; } }
time of stage in minutes
uint private stageTime = 86400;
1,715,622
[ 1, 4625, 348, 7953, 560, 30, 225, 813, 434, 6009, 316, 6824, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3238, 6009, 950, 273, 21451, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableMapUpgradeable.sol"; import "../libraries/SafeCastExtended.sol"; import "../interfaces/IERC721Mintable.sol"; import "../interfaces/IRewardManager.sol"; /** * @title CryptoVikings NFT * @author JaboiNads * @notice An ERC-721 compliant implementation of the CryptoVikings NFT. */ contract CryptoVikings is OwnableUpgradeable, PausableUpgradeable, ERC721EnumerableUpgradeable, IERC721Mintable { using AddressUpgradeable for address payable; using CountersUpgradeable for CountersUpgradeable.Counter; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using ERC165CheckerUpgradeable for address; using SafeCastExtended for uint256; /** * @dev Configuration properties. */ struct Config { // The cost to mint a Viking. uint128 mintFee; // The wallet to send developer payments to. address developerWallet; // The shared reward rate. uint16 sharedRewardRate; // The maximum number of mints allowed in a single transaction. uint8 maxMintsPerTransaction; // The reward manager instance. IRewardManager rewardManager; } // The reward precision calculator. uint256 private constant RATE_PRECISION_SCALAR = 1_000; // Base URI for token metadata. string private constant BASE_TOKEN_URI = "https://api.cryptovikings.art/token/viking/"; // The maximum supply of Vikings that can ever be minted. uint256 public constant MAX_SUPPLY = 10_000; // The configuration properties instance. Config private _config; // Maps a token to the address that minted it. EnumerableMapUpgradeable.UintToAddressMap private _minters; // Counter for generating new token IDs. CountersUpgradeable.Counter private _tokenIdCounter; /** * @notice Emitted when the mint fee changes. * @param oldMintFee The old mint fee. * @param newMintFee The new mint fee. */ event MintFeeChanged( uint128 oldMintFee, uint128 newMintFee ); /** * @notice Emitted when the reward rate changes. * @param oldRewardRate The old reward rate. * @param newRewardRate The new reward rate. */ event RewardRateChanged( uint16 oldRewardRate, uint16 newRewardRate ); /** * @notice Emitted when the maximum mints per transaction changes. * @param oldMaxMintsPerTransaction The old maximum mints per transaction. * @param newMaxMintsPerTransaction The new maximum mints per transaction. */ event MaxMintsPerTransactionChanged( uint8 oldMaxMintsPerTransaction, uint8 newMaxMintsPerTransaction ); /** * @notice Emitted when the reward manager changes. * @param oldRewardManager The old reward manager. * @param newRewardManager The new reward manager. */ event RewardManagerChanged( IRewardManager oldRewardManager, IRewardManager newRewardManager ); /** * @notice Emitted when the developer wallet changes. * @param oldDeveloperWallet The old developer wallet. * @param newDeveloperWallet The new developer wallet. */ event DeveloperWalletChanged( address oldDeveloperWallet, address newDeveloperWallet ); /** * @notice Emitted whenever a new Viking is minted. * @param minter The wallet that minted the token. * @param tokenId The id of the token that was minted. * @param price The price that the token was minted at. */ event Minted( address indexed minter, uint48 indexed tokenId, uint128 price ); function initialize( address developerWallet ) public initializer { __Ownable_init(); __Pausable_init_unchained(); __ERC721_init_unchained("CryptoVikings", "VIKING"); __ERC721Enumerable_init_unchained(); __CryptoVikings_init_unchained(developerWallet); } // solhint-disable-next-line func-name-mixedcase function __CryptoVikings_init_unchained( address developerWallet ) internal onlyInitializing { setMintFee(2 ether); setSharedRewardRate(100); // 10.0% setMaxMintsPerTransaction(10); setDeveloperWallet(developerWallet); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return interfaceId == type(IERC721Mintable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Mintable-minterOf}. */ function minterOf( uint256 tokenId ) public view returns (address) { return _minters.get(tokenId); } /** * @notice Sets the mint fee. * @param mintFee The new mint fee, must be non-zero. */ function setMintFee( uint128 mintFee ) public onlyOwner { require(mintFee > 0, "invalid mint fee"); emit MintFeeChanged(_config.mintFee, mintFee); _config.mintFee = mintFee; } /** * @notice Sets the shared reward rate for every mint. * @param sharedRewardRate The new reward rate (0.1% precision), must be non-zero. */ function setSharedRewardRate( uint16 sharedRewardRate ) public onlyOwner { require(sharedRewardRate > 0 && sharedRewardRate <= RATE_PRECISION_SCALAR, "bad reward rate"); emit RewardRateChanged(_config.sharedRewardRate, sharedRewardRate); _config.sharedRewardRate = sharedRewardRate; } /** * @notice Sets the reward manager instance. * @param rewardManager The new rewards manager. */ function setRewardManager( IRewardManager rewardManager ) public onlyOwner { require(address(rewardManager).supportsInterface(type(IRewardManager).interfaceId), "invalid reward manager"); emit RewardManagerChanged(_config.rewardManager, rewardManager); _config.rewardManager = rewardManager; } /** * @notice Sets the developer wallet. * @param developerWallet The new developer wallet. */ function setDeveloperWallet( address developerWallet ) public onlyOwner { require(developerWallet != address(0), "invalid developer wallet"); emit DeveloperWalletChanged(_config.developerWallet, developerWallet); _config.developerWallet = developerWallet; } /** * @notice Sets the maximum number of mints per transaction. * @param maxMintsPerTransaction The maximum number of mints per transaction. */ function setMaxMintsPerTransaction( uint8 maxMintsPerTransaction ) public onlyOwner { require(maxMintsPerTransaction > 0, "invalid max mints"); emit MaxMintsPerTransactionChanged(_config.maxMintsPerTransaction, maxMintsPerTransaction); _config.maxMintsPerTransaction = maxMintsPerTransaction; } /** * @notice Gets the current mint fee. */ function getMintFee() external view returns (uint128) { return _config.mintFee; } /** * @notice Gets the maximum number of mints per transaction. */ function getMaxMintsPerTransaction() external view returns (uint8) { return _config.maxMintsPerTransaction; } /** * @notice Pauses the contract functionality. */ function pause() external onlyOwner { _pause(); } /** * @notice Unpauses contract functionality. */ function unpause() external onlyOwner { _unpause(); } /** * @notice Airdrops tokens to holders. * @param tokenIds The ids of the tokens to airdrop. * @param minters The addresses that minted the tokens. * @param owners The addresses that currently own the tokens. */ function airdrop( uint256[] memory tokenIds, address[] memory minters, address[] memory owners ) external onlyOwner { require(tokenIds.length == minters.length && tokenIds.length == owners.length, "array length mismatch"); for (uint256 i = 0; i < tokenIds.length; i++) { _tokenIdCounter.increment(); require(tokenIds[i] == _tokenIdCounter.current(), "token id mismatch"); _safeMint(owners[i], tokenIds[i]); _minters.set(tokenIds[i], minters[i]); } } /** * @notice Mints new vikings and transfers ownership to the minter. * @param minter The address to transfer ownership of the newly minted tokens to. * @param amount The number of new tokens to mint. */ function mint( address minter, uint8 amount ) external payable whenNotPaused { require(totalSupply() + amount <= MAX_SUPPLY, "exceeds supply"); require(amount > 0 && amount <= _config.maxMintsPerTransaction, "bad mint amount"); // Owner can mint Vikings for free for promos. uint128 price = (_msgSender() == owner()) ? 0 : amount * _config.mintFee; require(msg.value == price, "wrong amount paid"); // Mint each of the vikings and initialize them with the reward manager. for (uint8 i = 0; i < amount; i++) { // Generates the next token id, starting at #1. _tokenIdCounter.increment(); uint256 tokenId = _tokenIdCounter.current(); _safeMint(minter, tokenId); _minters.set(tokenId, minter); emit Minted(minter, tokenId.toUint48(), price / amount); _config.rewardManager.initializeToken(tokenId); } if (price > 0) { // Calculate the reward cut to be distributed to holders. uint256 rewardAmount = (price * _config.sharedRewardRate) / RATE_PRECISION_SCALAR; _config.rewardManager.depositSharedReward{value: rewardAmount}(); // Transfer the remaining mint fee to the developers. payable(_config.developerWallet).sendValue(msg.value - rewardAmount); } } /** * @notice Gets the list of tokens owned by the specified address. * @param owner The address to get the owned tokens of. */ function getTokensForOwner( address owner ) external view returns (uint48[] memory) { uint256 balance = balanceOf(owner); uint48[] memory tokens = new uint48[](balance); for (uint256 i = 0; i < balance; i++) { tokens[i] = tokenOfOwnerByIndex(owner, i).toUint48(); } return tokens; } }
* @dev See {IERC721Mintable-minterOf}./
function minterOf( uint256 tokenId ) public view returns (address) { return _minters.get(tokenId); }
12,957,888
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2164, 288, 45, 654, 39, 27, 5340, 49, 474, 429, 17, 1154, 387, 951, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1131, 387, 951, 12, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 1154, 5432, 18, 588, 12, 2316, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.20; /** * @author FadyAro * * 22.07.2018 * * */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused, 'Contract Paused!'); _; } modifier whenPaused() { require(paused, 'Contract Active!'); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract EtherDrop is Pausable { uint constant PRICE_WEI = 2e16; /* * blacklist flag */ uint constant FLAG_BLACKLIST = 1; /* * subscription queue size: should be power of 10 */ uint constant QMAX = 1000; /* * randomness order construction conform to QMAX * e.g. random [0 to 999] is of order 3 => rand = 100*x + 10*y + z */ uint constant DMAX = 3; /* * this event is when we have a new subscription * note that it may be fired sequentially just before => NewWinner */ event NewDropIn(address addr, uint round, uint place, uint value); /* * this event is when we have a new winner * it is as well a new round start => (round + 1) */ event NewWinner(address addr, uint round, uint place, uint value, uint price); struct history { /* * user black listed comment */ uint blacklist; /* * user rounds subscriptions number */ uint size; /* * array of subscribed rounds indexes */ uint[] rounds; /* * array of rounds subscription's inqueue indexes */ uint[] places; /* * array of rounds's ether value subscription >= PRICE */ uint[] values; /* * array of 0's initially, update to REWARD PRICE in win situations */ uint[] prices; } /* * active subscription queue */ address[] private _queue; /* * winners history */ address[] private _winners; /* * winner comment 32 left */ bytes32[] private _wincomma; /* * winner comment 32 right */ bytes32[] private _wincommb; /* * winners positions */ uint[] private _positions; /* * on which block we got a winner */ uint[] private _blocks; /* * active round index */ uint public _round; /* * active round queue pointer */ uint public _counter; /* * allowed collectibles */ uint private _collectibles = 0; /* * users history mapping */ mapping(address => history) private _history; /** * get current round details */ function currentRound() public view returns (uint round, uint counter, uint round_users, uint price) { return (_round, _counter, QMAX, PRICE_WEI); } /** * get round stats by index */ function roundStats(uint index) public view returns (uint round, address winner, uint position, uint block_no) { return (index, _winners[index], _positions[index], _blocks[index]); } /** * * @dev get the total number of user subscriptions * * @param user the specific user * * @return user rounds size */ function userRounds(address user) public view returns (uint) { return _history[user].size; } /** * * @dev get user subscription round number details * * @param user the specific user * * @param index the round number * * @return round no, user placing, user drop, user reward */ function userRound(address user, uint index) public view returns (uint round, uint place, uint value, uint price) { history memory h = _history[user]; return (h.rounds[index], h.places[index], h.values[index], h.prices[index]); } /** * round user subscription */ function() public payable whenNotPaused { /* * check subscription price */ require(msg.value >= PRICE_WEI, 'Insufficient Ether'); /* * start round ahead: on QUEUE_MAX + 1 * draw result */ if (_counter == QMAX) { uint r = DMAX; uint winpos = 0; _blocks.push(block.number); bytes32 _a = blockhash(block.number - 1); for (uint i = 31; i >= 1; i--) { if (uint8(_a[i]) >= 48 && uint8(_a[i]) <= 57) { winpos = 10 * winpos + (uint8(_a[i]) - 48); if (--r == 0) break; } } _positions.push(winpos); /* * post out winner rewards */ uint _reward = (QMAX * PRICE_WEI * 90) / 100; address _winner = _queue[winpos]; _winners.push(_winner); _winner.transfer(_reward); /* * update round history */ history storage h = _history[_winner]; h.prices[h.size - 1] = _reward; /* * default winner blank comments */ _wincomma.push(0x0); _wincommb.push(0x0); /* * log the win event: winpos is the proof, history trackable */ emit NewWinner(_winner, _round, winpos, h.values[h.size - 1], _reward); /* * update collectibles */ _collectibles += address(this).balance - _reward; /* * reset counter */ _counter = 0; /* * increment round */ _round++; } h = _history[msg.sender]; /* * user is not allowed to subscribe twice */ require(h.size == 0 || h.rounds[h.size - 1] != _round, 'Already In Round'); /* * create user subscription: N.B. places[_round] is the result proof */ h.size++; h.rounds.push(_round); h.places.push(_counter); h.values.push(msg.value); h.prices.push(0); /* * initial round is a push, others are 'on set' index */ if (_round == 0) { _queue.push(msg.sender); } else { _queue[_counter] = msg.sender; } /* * log subscription */ emit NewDropIn(msg.sender, _round, _counter, msg.value); /* * increment counter */ _counter++; } /** * * @dev let the user comment 64 letters for a winning round * * @param round the winning round * * @param a the first 32 letters comment * * @param b the second 32 letters comment * * @return user comment */ function comment(uint round, bytes32 a, bytes32 b) whenNotPaused public { address winner = _winners[round]; require(winner == msg.sender, 'not a winner'); require(_history[winner].blacklist != FLAG_BLACKLIST, 'blacklisted'); _wincomma[round] = a; _wincommb[round] = b; } /** * * @dev blacklist a user for its comments behavior * * @param user address * */ function blackList(address user) public onlyOwner { history storage h = _history[user]; if (h.size > 0) { h.blacklist = FLAG_BLACKLIST; } } /** * * @dev get the user win round comment * * @param round the winning round number * * @return user comment */ function userComment(uint round) whenNotPaused public view returns (address winner, bytes32 comma, bytes32 commb) { if (_history[_winners[round]].blacklist != FLAG_BLACKLIST) { return (_winners[round], _wincomma[round], _wincommb[round]); } else { return (0x0, 0x0, 0x0); } } /* * etherdrop team R&D support collectibles */ function collect() public onlyOwner { owner.transfer(_collectibles); } }
* @dev let the user comment 64 letters for a winning round @param round the winning round @param a the first 32 letters comment @param b the second 32 letters comment @return user comment/
function comment(uint round, bytes32 a, bytes32 b) whenNotPaused public { address winner = _winners[round]; require(winner == msg.sender, 'not a winner'); require(_history[winner].blacklist != FLAG_BLACKLIST, 'blacklisted'); _wincomma[round] = a; _wincommb[round] = b; }
6,355,296
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2231, 326, 729, 2879, 5178, 13768, 364, 279, 5657, 2093, 3643, 632, 891, 3643, 326, 5657, 2093, 3643, 632, 891, 279, 326, 1122, 3847, 13768, 2879, 632, 891, 324, 326, 2205, 3847, 13768, 2879, 632, 2463, 729, 2879, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2879, 12, 11890, 3643, 16, 1731, 1578, 279, 16, 1731, 1578, 324, 13, 1347, 1248, 28590, 1071, 288, 203, 203, 3639, 1758, 5657, 1224, 273, 389, 8082, 9646, 63, 2260, 15533, 203, 203, 3639, 2583, 12, 91, 7872, 422, 1234, 18, 15330, 16, 296, 902, 279, 5657, 1224, 8284, 203, 3639, 2583, 24899, 8189, 63, 91, 7872, 8009, 22491, 480, 10972, 67, 14618, 3649, 7085, 16, 296, 11223, 18647, 8284, 203, 203, 3639, 389, 8082, 25034, 63, 2260, 65, 273, 279, 31, 203, 3639, 389, 8082, 832, 1627, 63, 2260, 65, 273, 324, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol'; import './BLOBLeague.sol'; import './BLOBUtils.sol'; import './BLOBRegistry.sol'; import './BLOBTeam.sol'; contract BLOBPlayer is ERC721, ERC721Holder, WithRegistry { enum Position { CENTER, POWER_FORWARD, SMALL_FORWARD, POINT_GUARD, SHOOTING_GUARD } struct Player { // basic profile // generates when a player is minted uint id; Position position; string name; string photoUrl; // ageable uint8 age; uint8 physicalStrength; uint8 maturity; bool retired; // offence skills: [1, 100] // generates when a player is minted uint8 shot; uint8 shot3Point; uint8 assist; // defence skills: [1, 100] // generates when a player is minted uint8 rebound; uint8 blockage; uint8 steal; uint8 freeThrow; } struct GameTime { uint playerId; // in minutes, [0, 48] uint8 playTime; // percentage of shots allocated for this player [0, 50] uint8 shotAllocation; // percentage of 3 point shots allocated for this player [0, 50] uint8 shot3PAllocation; // starting lineup bool starter; } event PlayerMinted( uint playerId, uint seasonId, uint8 position, uint8 age, uint8 physicalStrength, uint8 maturity, uint8 shot, uint8 shot3Point, uint8 assist, uint8 rebound, uint8 blockage, uint8 steal, uint8 freeThrow, bool retired ); event PlayerUpdated( uint playerId, uint8 age, uint8 physicalStrength, uint8 maturity, bool retired ); using Percentage for uint8; uint public nextId; // ageable uint8 constant DEBUT_AGE_MIN = 18; uint8 constant DEBUT_AGE_MAX = 22; uint8 constant RETIRE_AGE_MIN = 38; uint8 constant RETIRE_AGE_MAX = 42; uint8 constant PEAK_AGE_MEAN = 30; uint8 constant PHY_STRENGTH_MIN = 50; uint8 constant PHY_STRENGTH_MAX = 100; uint8 constant PHY_STRENGTH_INC_UNIT = 2; uint8 constant DRAFT_MATURITY_MIN = 20; uint8 constant DRAFT_MATURITY_MAX = 40; uint8 constant DEBUT_MATURITY_MAX = 80; uint8 constant MATURITY_MAX = 100; uint8 constant MATURITY_INC_UNIT = 2; uint8[7][5] positionToSkills; uint8[4] playerGrades = [85, 70, 55, 40]; mapping(uint => Player) private idToPlayer; mapping(uint => GameTime) private playerToGameTime; // other contracts BLOBTeam TeamContract; constructor( string memory _name, string memory _symbol, address _registryContractAddr) ERC721(_name, _symbol) WithRegistry(_registryContractAddr) { // takes the max percentage per each position // [shot, shot3Point, assist, rebound, blockage, steal, freeThrows] positionToSkills[uint8(Position.CENTER)] = [100, 40, 80, 100, 100, 40, 100]; positionToSkills[uint8(Position.POWER_FORWARD)] = [100, 60, 80, 100, 80, 40, 100]; positionToSkills[uint8(Position.SMALL_FORWARD)] = [100, 100, 80, 80, 60, 60, 100]; positionToSkills[uint8(Position.SHOOTING_GUARD)] = [100, 100, 80, 60, 40, 100, 100]; positionToSkills[uint8(Position.POINT_GUARD)] = [100, 100, 100, 60, 40, 100, 100]; } modifier playerExists(uint _playerId) { require( _exists(_playerId), uint8(BLOBLeague.ErrorCode.INVALID_PLAYER_ID).toStr() ); _; } function Init() external leagueOnly { TeamContract = BLOBTeam(RegistryContract.TeamContract()); } // Ageable function IsRetired(uint _playerId) external view returns(bool) { return idToPlayer[_playerId].retired; } function UpdatePlayerConditions(uint _playerId, uint16 _playerSeasonMinutesAvg, uint16 _playMinutesInSeason, uint _seed) external seasonOnly returns(uint seed) { Player storage player = idToPlayer[_playerId]; if (!player.retired) { uint8 playTimePct = Percentage.dividePctU16( _playMinutesInSeason, _playerSeasonMinutesAvg); // update physical strength and maturity uint8 physicalStrength = player.physicalStrength; uint8 maturity = player.maturity; if (player.age < PEAK_AGE_MEAN - 5) { // age < 25: physicalStrength increases 4 percentage points physicalStrength += 2 * PHY_STRENGTH_INC_UNIT; maturity += (3 * MATURITY_INC_UNIT).multiplyPct(playTimePct); } else if (player.age >= PEAK_AGE_MEAN - 5 && player.age < PEAK_AGE_MEAN) { // 25 <= age < 30: physicalStrength increases 2 percentage points physicalStrength += PHY_STRENGTH_INC_UNIT; maturity += (2 * MATURITY_INC_UNIT).multiplyPct(playTimePct); } else if (player.age >= PEAK_AGE_MEAN && player.age < PEAK_AGE_MEAN + 5) { // 30 <= age < 35: physicalStrength decreases 2 percentage points, physicalStrength -= PHY_STRENGTH_INC_UNIT; maturity += MATURITY_INC_UNIT.multiplyPct(playTimePct); } else if (player.age >= PEAK_AGE_MEAN + 5) { // 35 <= age: physicalStrength decreases 4 percentage points, physicalStrength -= 2 * PHY_STRENGTH_INC_UNIT; } if (physicalStrength > PHY_STRENGTH_MAX) player.physicalStrength = PHY_STRENGTH_MAX; else if (physicalStrength < PHY_STRENGTH_MIN) player.physicalStrength = PHY_STRENGTH_MIN; else player.physicalStrength = physicalStrength; player.maturity = maturity > MATURITY_MAX ? MATURITY_MAX : maturity; // increment age and calculate retirement uint8 retireAge; (retireAge, seed) = Random.randrange(RETIRE_AGE_MIN, RETIRE_AGE_MAX, _seed); player.age++; if (player.age >= retireAge) player.retired = true; emit PlayerUpdated( _playerId, player.age, player.physicalStrength, player.maturity, player.retired); } } function mintPlayers(uint[] memory newPlayerIds, uint _seasonId, uint8 _countPerPosistion, bool _forDraft, uint _seed) private returns (uint){ for (uint i=0; i<5; i++) { for (uint8 j=0; j<_countPerPosistion; j++) { uint playerId; (playerId, _seed) = mintAPlayer(Position(i), _forDraft , _seasonId, _seed+j); newPlayerIds[i*_countPerPosistion + j] = playerId; } } return _seed; } function MintPlayersForDraft(uint _seasonId, uint8 _countPerPosistion) external seasonOnly returns (uint[] memory newPlayerIds){ newPlayerIds = new uint[](5 * _countPerPosistion); // mint 2 players for each position and another 2 players for random position uint seed = block.timestamp; mintPlayers(newPlayerIds, _seasonId, _countPerPosistion, true, seed); } function MintPlayersForTeam(uint _seasonId, uint8 _countPerPosistion, uint8 _countAdditional) external teamOnly returns (uint[] memory newPlayerIds){ // mint 2 players for each position and another 2 players for random position newPlayerIds = new uint[](5 * _countPerPosistion + _countAdditional); uint seed = block.timestamp; seed = mintPlayers(newPlayerIds, _seasonId, _countPerPosistion, false, seed); uint playerId; for (uint i=0; i<_countAdditional; i++) { (playerId, seed) = mintAPlayer(Position(seed % 5), false, _seasonId, seed); newPlayerIds[5 * _countPerPosistion + i] = playerId; } } function GetPlayer(uint _playerId) view external playerExists(_playerId) returns(Player memory player) { player = idToPlayer[_playerId]; } function GetPlayerGameTime(uint _playerId) view external playerExists(_playerId) returns(BLOBPlayer.GameTime memory playerGameTime) { playerGameTime = playerToGameTime[_playerId]; } function SetPlayerGameTime(GameTime calldata _gameTime) external teamOnly { delete playerToGameTime[_gameTime.playerId]; playerToGameTime[_gameTime.playerId] = _gameTime; } function tokenURI(uint256 tokenId) public view override playerExists(tokenId) returns(string memory) { return idToPlayer[tokenId].photoUrl; } function SetPlayerNameAndImage(uint _playerId, string memory _name, string memory _photoUrl) external teamOnly playerExists(_playerId) { Player storage player = idToPlayer[_playerId]; require( keccak256(abi.encodePacked(player.name)) == keccak256(abi.encodePacked("")) && keccak256(abi.encodePacked(player.photoUrl)) == keccak256(abi.encodePacked("")), uint8(BLOBLeague.ErrorCode.PLAYER_NAME_IMAGE_ALREADY_SET).toStr() ); player.name = _name; player.photoUrl = _photoUrl; } function TransferPlayer(uint _playerId, address _to) external teamOnly { Player memory player = idToPlayer[_playerId]; require( player.retired, uint8(BLOBLeague.ErrorCode.PLAYER_NOT_ABLE_TO_CLAIM).toStr() ); _safeTransfer(RegistryContract.TeamContract(), _to, _playerId, ""); } function getGradeIndex(uint _seed) private view returns(uint8 gradeIndex, uint seed) { uint8 rnd; (rnd, seed) = Random.randrange(1, 10, _seed); gradeIndex = 0; // top 10% if (rnd > 1 && rnd <= 3) { gradeIndex = 1; // 20% } else if (rnd > 3 && rnd <= 8) { gradeIndex = 2; // 50% } else if (rnd > 8) { gradeIndex = 3; // bottom 20% } } function getOffenceDefenceGradeBase(uint _seed) private view returns(uint8 offenceGradeBase, uint8 defenceGradeBase, uint seed) { uint8 offenceGrade; (offenceGrade, seed) = getGradeIndex(_seed); uint8 defenceGrade; (defenceGrade, seed) = getGradeIndex(seed); offenceGradeBase = playerGrades[offenceGrade]; defenceGradeBase = playerGrades[defenceGrade]; } function mintAPlayer(Position _position, bool _forDraft, uint _seasonId, uint _seed) private returns(uint playerId, uint seed) { uint8 offenceGradeBase; uint8 defenceGradeBase; (offenceGradeBase, defenceGradeBase, seed) = getOffenceDefenceGradeBase(_seed); // make rookie's debut age between [18, 22], otherwise [18, 37] uint8 age; // make rookie's maturity between [DEBUT_MATURITY_MIN , DEBUT_MATURITY_MAX], // otherwise [DEBUT_MATURITY_MAX, MATURITY_MAX] uint8 maturity; if (_forDraft) { (age, seed) = Random.randrange(DEBUT_AGE_MIN, DEBUT_AGE_MAX, seed); (maturity, seed) = Random.randrange(DRAFT_MATURITY_MIN, DRAFT_MATURITY_MAX, seed); } else { (age, seed) = Random.randrange(DEBUT_AGE_MIN, RETIRE_AGE_MIN-1, seed); (maturity, seed) = Random.randrange(DRAFT_MATURITY_MAX, DEBUT_MATURITY_MAX, seed); } uint8 physicalStrength; (physicalStrength, seed) = Random.randrange(PHY_STRENGTH_MIN, PHY_STRENGTH_MAX, seed); //[shot, shot3Point, assist, rebound, blockage, steal, freeThrow] uint8[] memory playerSkills; (playerSkills, seed) = Random.randuint8(7, 0, 15, seed); Player memory newPlayer = addPlayerAttributes(nextId, _position, age, physicalStrength, maturity, offenceGradeBase, defenceGradeBase, playerSkills); idToPlayer[nextId] = newPlayer; playerId = nextId; _safeMint(RegistryContract.TeamContract(), nextId++); emit PlayerMinted( playerId, _seasonId, uint8(_position), age, physicalStrength, maturity, newPlayer.shot, newPlayer.shot3Point, newPlayer.assist, newPlayer.rebound, newPlayer.blockage, newPlayer.steal, newPlayer.freeThrow, false ); } function addPlayerAttributes(uint _id, Position _position, uint8 _age, uint8 _physicalStrength, uint8 _maturity, uint8 _offenceGradeBase, uint8 _defenceGradeBase, uint8[] memory _playerSkills) private view returns(Player memory newPlayer) { uint8[7] memory playerSkillWeights = positionToSkills[uint8(_position)]; newPlayer = Player( { id: _id, name: "", photoUrl: "", retired: false, age: _age, position: _position, physicalStrength: _physicalStrength, maturity: _maturity, shot: (_offenceGradeBase + uint8(_playerSkills[0])).multiplyPct(playerSkillWeights[0]), shot3Point: (_offenceGradeBase + uint8(_playerSkills[1])).multiplyPct(playerSkillWeights[1]), assist: (_offenceGradeBase + uint8(_playerSkills[2])).multiplyPct(playerSkillWeights[2]), rebound: (_defenceGradeBase + uint8(_playerSkills[3])).multiplyPct(playerSkillWeights[3]), blockage: (_defenceGradeBase + uint8(_playerSkills[4])).multiplyPct(playerSkillWeights[4]), steal: (_defenceGradeBase + uint8(_playerSkills[5])).multiplyPct(playerSkillWeights[5]), freeThrow: (_offenceGradeBase + uint8(_playerSkills[6])).multiplyPct(playerSkillWeights[6]) } ); } }
update physical strength and maturity age < 25: physicalStrength increases 4 percentage points 25 <= age < 30: physicalStrength increases 2 percentage points 30 <= age < 35: physicalStrength decreases 2 percentage points, 35 <= age: physicalStrength decreases 4 percentage points,
function UpdatePlayerConditions(uint _playerId, uint16 _playerSeasonMinutesAvg, uint16 _playMinutesInSeason, uint _seed) external seasonOnly returns(uint seed) { Player storage player = idToPlayer[_playerId]; if (!player.retired) { uint8 playTimePct = Percentage.dividePctU16( _playMinutesInSeason, _playerSeasonMinutesAvg); uint8 physicalStrength = player.physicalStrength; uint8 maturity = player.maturity; if (player.age < PEAK_AGE_MEAN - 5) { physicalStrength += 2 * PHY_STRENGTH_INC_UNIT; maturity += (3 * MATURITY_INC_UNIT).multiplyPct(playTimePct); } else if (player.age >= PEAK_AGE_MEAN - 5 && player.age < PEAK_AGE_MEAN) { physicalStrength += PHY_STRENGTH_INC_UNIT; maturity += (2 * MATURITY_INC_UNIT).multiplyPct(playTimePct); } else if (player.age >= PEAK_AGE_MEAN && player.age < PEAK_AGE_MEAN + 5) { physicalStrength -= PHY_STRENGTH_INC_UNIT; maturity += MATURITY_INC_UNIT.multiplyPct(playTimePct); physicalStrength -= 2 * PHY_STRENGTH_INC_UNIT; } if (physicalStrength > PHY_STRENGTH_MAX) player.physicalStrength = PHY_STRENGTH_MAX; else if (physicalStrength < PHY_STRENGTH_MIN) player.physicalStrength = PHY_STRENGTH_MIN; else player.physicalStrength = physicalStrength; player.maturity = maturity > MATURITY_MAX ? MATURITY_MAX : maturity; (retireAge, seed) = Random.randrange(RETIRE_AGE_MIN, RETIRE_AGE_MAX, _seed); player.age++; if (player.age >= retireAge) player.retired = true; emit PlayerUpdated( _playerId, player.age, player.physicalStrength, player.maturity, player.retired); } }
12,663,311
[ 1, 4625, 348, 7953, 560, 30, 225, 1089, 11640, 21638, 471, 29663, 9388, 411, 6969, 30, 11640, 27624, 7033, 3304, 1059, 11622, 3143, 6969, 1648, 9388, 411, 5196, 30, 11640, 27624, 7033, 3304, 576, 11622, 3143, 5196, 1648, 9388, 411, 13191, 30, 11640, 27624, 23850, 3304, 576, 11622, 3143, 16, 13191, 1648, 9388, 30, 11640, 27624, 23850, 3304, 1059, 11622, 3143, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2315, 12148, 8545, 12, 11890, 389, 14872, 548, 16, 203, 4766, 565, 2254, 2313, 389, 14872, 1761, 2753, 13050, 22823, 16, 203, 4766, 565, 2254, 2313, 389, 1601, 13050, 382, 1761, 2753, 16, 203, 4766, 565, 2254, 389, 12407, 13, 203, 1377, 3903, 15874, 3386, 1135, 12, 11890, 5009, 13, 288, 203, 1377, 19185, 2502, 7291, 273, 612, 774, 12148, 63, 67, 14872, 548, 15533, 203, 1377, 309, 16051, 14872, 18, 1349, 2921, 13, 288, 203, 3639, 2254, 28, 6599, 950, 52, 299, 273, 21198, 410, 18, 2892, 831, 52, 299, 57, 2313, 12, 203, 1850, 389, 1601, 13050, 382, 1761, 2753, 16, 203, 1850, 389, 14872, 1761, 2753, 13050, 22823, 1769, 203, 3639, 2254, 28, 11640, 27624, 273, 7291, 18, 20441, 27624, 31, 203, 3639, 2254, 28, 29663, 273, 7291, 18, 7373, 2336, 31, 203, 3639, 309, 261, 14872, 18, 410, 411, 16628, 14607, 67, 2833, 67, 958, 1258, 300, 1381, 13, 288, 203, 1850, 11640, 27624, 1011, 576, 380, 15490, 61, 67, 882, 862, 4960, 2455, 67, 23213, 67, 15736, 31, 203, 1850, 29663, 1011, 261, 23, 380, 490, 789, 1099, 4107, 67, 23213, 67, 15736, 2934, 7027, 1283, 52, 299, 12, 1601, 950, 52, 299, 1769, 203, 203, 3639, 289, 469, 309, 261, 14872, 18, 410, 1545, 16628, 14607, 67, 2833, 67, 958, 1258, 300, 1381, 203, 10402, 597, 7291, 18, 410, 411, 16628, 14607, 67, 2833, 67, 958, 1258, 13, 288, 203, 1850, 11640, 27624, 1011, 15490, 61, 67, 882, 862, 4960, 2455, 67, 23213, 67, 15736, 31, 203, 1850, 29663, 1011, 261, 22, 380, 490, 789, 1099, 4107, 67, 23213, 67, 15736, 2934, 7027, 1283, 52, 299, 12, 1601, 950, 52, 299, 1769, 203, 203, 3639, 289, 469, 309, 261, 14872, 18, 410, 1545, 16628, 14607, 67, 2833, 67, 958, 1258, 203, 10402, 597, 7291, 18, 410, 411, 16628, 14607, 67, 2833, 67, 958, 1258, 397, 1381, 13, 288, 203, 1850, 11640, 27624, 3947, 15490, 61, 67, 882, 862, 4960, 2455, 67, 23213, 67, 15736, 31, 203, 1850, 29663, 1011, 490, 789, 1099, 4107, 67, 23213, 67, 15736, 18, 7027, 1283, 52, 299, 12, 1601, 950, 52, 299, 1769, 203, 203, 1850, 11640, 27624, 3947, 576, 380, 15490, 61, 67, 882, 862, 4960, 2455, 67, 23213, 67, 15736, 31, 203, 3639, 289, 203, 3639, 309, 261, 20441, 27624, 405, 15490, 61, 67, 882, 862, 4960, 2455, 67, 6694, 13, 203, 1850, 7291, 18, 20441, 27624, 273, 15490, 61, 67, 882, 862, 4960, 2455, 67, 6694, 31, 203, 3639, 469, 309, 261, 20441, 27624, 411, 15490, 61, 67, 882, 862, 4960, 2455, 67, 6236, 13, 203, 1850, 7291, 18, 20441, 27624, 273, 15490, 61, 67, 882, 862, 4960, 2455, 67, 6236, 31, 203, 3639, 469, 203, 1850, 7291, 18, 20441, 27624, 273, 11640, 27624, 31, 203, 203, 3639, 7291, 18, 7373, 2336, 273, 29663, 405, 490, 789, 1099, 4107, 67, 6694, 692, 490, 789, 1099, 4107, 67, 6694, 294, 29663, 31, 203, 203, 3639, 261, 1349, 577, 9692, 16, 5009, 13, 273, 8072, 18, 7884, 3676, 12, 10238, 45, 862, 67, 2833, 67, 6236, 16, 203, 4766, 2398, 10366, 45, 862, 67, 2833, 67, 6694, 16, 203, 4766, 2398, 389, 12407, 1769, 203, 3639, 7291, 18, 410, 9904, 31, 203, 3639, 309, 261, 14872, 18, 410, 1545, 325, 577, 9692, 13, 203, 1850, 7291, 18, 1349, 2921, 273, 638, 31, 203, 203, 3639, 3626, 19185, 7381, 12, 203, 1850, 389, 14872, 548, 16, 203, 1850, 7291, 18, 410, 16, 203, 1850, 7291, 18, 20441, 27624, 16, 203, 1850, 7291, 18, 7373, 2336, 16, 203, 1850, 7291, 18, 1349, 2921, 1769, 203, 1377, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/1287/0xA535E7ECA76BF1dbdbED9d8745b9158632Dca0d7/sources/project_/contracts/treasury/TreasuryCoreContract.sol
@dev Modifier to check that the caller is the treasury contract
modifier onlyTreasuryContract() { require( msg.sender == TREASURY_CONTRACT_ADDRESS, "UNAUTHORIZED: CANNOT_PERFORM_ACTION" ); _; }
7,096,861
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 12832, 358, 866, 716, 326, 4894, 353, 326, 9787, 345, 22498, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 56, 266, 345, 22498, 8924, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 399, 862, 3033, 1099, 61, 67, 6067, 2849, 1268, 67, 15140, 16, 203, 5411, 315, 2124, 28383, 30, 385, 16791, 67, 3194, 4983, 67, 12249, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import '@openzeppelin/contracts/access/Ownable.sol'; import './ModaAware.sol'; import './EscrowedModaERC20.sol'; /** * @title Moda Core Pool * * @notice Core pools represent permanent pools like MODA or MODA/ETH Pair pool, * core pools allow staking for arbitrary periods of time up to 1 year * * @dev Pulled from the original Factory code to provide the weight calculations. */ abstract contract ModaPoolFactory is ModaAware, Ownable { /** * @dev MODA/block determines yield farming reward base * used by the yield pools controlled by the factory */ uint256 public modaPerBlock; /** * @dev The yield is distributed proportionally to pool weights; * total weight is here to help in determining the proportion */ uint32 public totalWeight; /** * @dev MODA/block decreases by 3% every blocks/update (set to 91252 blocks during deployment); * an update is triggered by executing `updateMODAPerBlock` public function */ uint256 public immutable blocksPerUpdate; /** * @dev End block is the last block when MODA/block can be decreased; * it is implied that yield farming stops after that block */ uint256 public endBlock; /** * @dev Each time the MODA/block ratio gets updated, the block number * when the operation has occurred gets recorded into `lastRatioUpdate` * @dev This block number is then used to check if blocks/update `blocksPerUpdate` * has passed when decreasing yield reward by 3% */ uint256 public lastRatioUpdate; /** * @dev Fired in _changePoolWeight() * * @param _by an address which executed an action * @param poolAddress deployed pool instance address * @param weight new pool weight */ event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight); /** * @dev Fired in updateILVPerBlock() * * @param _by an address which executed an action * @param newIlvPerBlock new ILV/block value */ event ModaRatioUpdated(address indexed _by, uint256 newIlvPerBlock); /** * @dev Creates/deploys a factory instance * * @param _moda MODA ERC20 token address * @param _modaPerBlock initial MODA/block value for rewards * @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _initBlock block number to measure _blocksPerUpdate from * @param _endBlock block number when farming stops and rewards cannot be updated anymore */ constructor( address _moda, uint256 _modaPerBlock, uint256 _blocksPerUpdate, uint256 _initBlock, uint256 _endBlock ) ModaAware(_moda) { // verify the inputs are set require(_modaPerBlock > 0, 'MODA/block not set'); require(_blocksPerUpdate > 0, 'blocks/update not set'); require(_initBlock > 0, 'init block not set'); require(_endBlock > _initBlock, 'invalid end block: must be greater than init block'); // save the inputs into internal state variables modaPerBlock = _modaPerBlock; blocksPerUpdate = _blocksPerUpdate; lastRatioUpdate = _initBlock; endBlock = _endBlock; } /** * @dev Verifies if `blocksPerUpdate` has passed since last MODA/block * ratio update and if MODA/block reward can be decreased by 3% * * @return true if enough time has passed and `updateMODAPerBlock` can be executed */ function shouldUpdateRatio() internal view returns (bool) { // if yield farming period has ended if (block.number > endBlock) { // MODA/block reward cannot be updated anymore return false; } // check if blocks/update (91252 blocks) have passed since last update return block.number >= lastRatioUpdate + blocksPerUpdate; } /** * @notice Decreases MODA/block reward by 3%, can be executed * no more than once per `blocksPerUpdate` blocks */ function updateMODAPerBlock() internal { // checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed require(shouldUpdateRatio(), 'too frequent'); // decreases MODA/block reward by 3% modaPerBlock = (modaPerBlock * 97) / 100; // set current block as the last ratio update block lastRatioUpdate = block.number; // emit an event emit ModaRatioUpdated(msg.sender, modaPerBlock); } /** * @dev Mints MODA tokens; executed by MODA Pool only * * @dev Requires caller to have ROLE_TOKEN_CREATOR permission * on the MODA ERC20 token instance * * @param _to an address to mint tokens to * @param _amount amount of MODA tokens to mint */ function mintYieldTo(address _to, uint256 _amount) internal { // mint MODA tokens as required //console.log('ModaPoolFactory.mintYieldTo', address(this), _msgSender(), _to); mintModa(_to, _amount); } /** * @dev Provided a virtual accessor to the IPool.weight() * implemented in ModaPoolBase. * @dev This is used by _changePoolWeight in place of the * original implementation's pool address parameter. */ function _poolWeight() internal view virtual returns (uint32); /** * @dev Changes the weight of the pool; * executed by the pool itself or by the factory owner * * @param newWeight new weight value to set to */ function _changePoolWeight(uint32 newWeight) internal onlyOwner { // recalculate total weight totalWeight = totalWeight + newWeight - _poolWeight(); // emit an event emit WeightUpdated(msg.sender, address(this), newWeight); } }
* @notice Decreases MODA/block reward by 3%, can be executed no more than once per `blocksPerUpdate` blocks/ checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed decreases MODA/block reward by 3% set current block as the last ratio update block emit an event
function updateMODAPerBlock() internal { require(shouldUpdateRatio(), 'too frequent'); modaPerBlock = (modaPerBlock * 97) / 100; lastRatioUpdate = block.number; emit ModaRatioUpdated(msg.sender, modaPerBlock); }
6,352,998
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 31073, 3304, 8663, 37, 19, 2629, 19890, 635, 890, 9, 16, 848, 506, 7120, 1377, 1158, 1898, 2353, 3647, 1534, 1375, 7996, 2173, 1891, 68, 4398, 19, 4271, 309, 7169, 848, 506, 3526, 277, 18, 73, 18, 309, 4398, 19, 2725, 261, 29, 2138, 9401, 4398, 13, 1240, 2275, 23850, 3304, 8663, 37, 19, 2629, 19890, 635, 890, 9, 444, 783, 1203, 487, 326, 1142, 7169, 1089, 1203, 3626, 392, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1089, 6720, 37, 2173, 1768, 1435, 2713, 288, 203, 202, 202, 6528, 12, 13139, 1891, 8541, 9334, 296, 16431, 13821, 319, 8284, 203, 203, 202, 202, 1711, 69, 2173, 1768, 273, 261, 1711, 69, 2173, 1768, 380, 16340, 13, 342, 2130, 31, 203, 203, 202, 202, 2722, 8541, 1891, 273, 1203, 18, 2696, 31, 203, 203, 202, 202, 18356, 3431, 69, 8541, 7381, 12, 3576, 18, 15330, 16, 681, 69, 2173, 1768, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.6.12; 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; } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } function div(uint x, uint y) internal pure returns (uint z) { require(x > 0, "Divisor cannot be 0!"); z = x / y; require(x == y * z + x % y, "Divide must be safe!"); return z; } } library UniswapV2Library { using SafeMathUniswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'd07c8b370cfc8874f028a6668fbf9e0737f3144c2b09e9a8a923239fea9e2914' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // // 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'); } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // CynToken with Governance. contract CynToken is ERC20("CynToken", "CYN"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef or Router). modifier onlyAuth() { require(msg.sender == masterChef || msg.sender == router, "Ownable: caller is not the owner"); _; } function mint(address _to, uint256 _amount) public onlyAuth{ _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } address public masterChef; address public router; /// @notice set the owner (MasterChef or Router). only call it once. function setOwner(address _masterChef, address _router) public onlyOwner { masterChef = _masterChef; router = _router; renounceOwnership(); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CYN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CYN::delegateBySig: invalid nonce"); require(now <= expiry, "CYN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CYN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CYNs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CYN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } library MintRewardLibrary { using SafeMath for uint256; uint256 constant level0 = 40000 * 10**18; uint256 constant level1 = 265000 * 10**18; uint256 constant level2 = 1400000 * 10**18; uint256 constant level3 = 4000000 * 10**18; function getReward(uint256 tradeValueWithETH) internal pure returns (uint256 TB_X) { if (tradeValueWithETH <= level0) { // TLV *6.25E14  return tradeValueWithETH.mul(625 * 10**12).div(10**18); } else if (tradeValueWithETH > level0 && tradeValueWithETH <= level1) { // (TLV * 3.555555555555560E14 + 8.577777777777780E19)/4  return (tradeValueWithETH.mul(355555555555556).div(10**18).add(85777777777777800000)).div(4); } else if (tradeValueWithETH > level1 && tradeValueWithETH <= level2) { // (TLV * 1.938325991189430E14 + 1.286343612334800E20)/4 return (tradeValueWithETH.mul(193832599118943).div(10**18).add(128634361233480000000)).div(4); }else if (tradeValueWithETH > level2 && tradeValueWithETH <= level3) { // (TLV * 6.923076923076920E13 + 3.030769230769230E20)/4 return (tradeValueWithETH.mul(692307692307692).div(10**18).add(3030769230769230000000)).div(40); } else { // 145E18 return 145 * 10**18; } } } contract UniswapV2Router02 is IUniswapV2Router02, Ownable { using SafeMathUniswap for uint; address public immutable override factory; address public immutable override WETH; //uint256 public override tradeValueCovertETH; uint256 public currentEpoch = 0; uint256 public currentEpochBlockNumber; // TV in each epoch, epoch => LP => TV mapping (uint256 => mapping(address => uint256)) public epochTV; // The minimum period of mining (block number) uint256 public segment = 240; CynToken public cyn; address public devaddr; uint256 public capacity = 1000000000 * 10**18; uint256 public totalSupply = 0; struct TradeInfo { uint256 amount; // Total transaction amount in one segment . uint256 epoch; // epoch } // Info of each pool. mapping (address => uint256) public poolInfo; // account => LP => tradeInfo mapping (address => mapping(address => TradeInfo)) public trader; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } constructor(address _factory, CynToken _cyn, address _devaddr, address _WETH) public { factory = _factory; cyn = _cyn; devaddr = _devaddr; WETH = _WETH; currentEpochBlockNumber = block.number; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UniswapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IUniswapV2Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } function setCapacity(uint256 _capacity) public onlyOwner { require(_capacity > totalSupply, "New capacity must be larger than totalSupply"); capacity = _capacity; } // Add a new pair to the pool. Can only be called by the owner. function add(uint256 _allocPoint, address token0, address token1) public onlyOwner { address _lpToken = UniswapV2Library.pairFor(factory, token0, token1); if (poolInfo[_lpToken] > 0) { return; } poolInfo[_lpToken] = _allocPoint * 24; } // Update the given pool's CYN allocation point. Can only be called by the owner. function set(uint256 _allocPoint, address token0, address token1) public onlyOwner { address _lpToken = UniswapV2Library.pairFor(factory, token0, token1); poolInfo[_lpToken] = _allocPoint * 24; } // gets the value converted into eth function getValueConvertETH(uint256 amount, address token) public view returns (uint256) { if (token == WETH) { return amount; } else { address pair = IUniswapV2Factory(factory).getPair(token, WETH); if (pair != address(0)) { (uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves(); address token0 = IUniswapV2Pair(pair).token0(); (uint reserveA, uint reserveB) = token0 == WETH ? (reserve0, reserve1) : (reserve1, reserve0); return amount.mul(reserveA).div(reserveB); } else { return 0; } } } // claim cyn token function claimCynReward(address tokenA, address tokenB) public { address lpToken = UniswapV2Library.pairFor(factory, tokenA, tokenB); if (poolInfo[lpToken] == 0) { return; } TradeInfo storage tradeInfo = trader[msg.sender][lpToken]; if (tradeInfo.amount == 0) { return; } if ((tradeInfo.epoch < currentEpoch) || (currentEpochBlockNumber + segment < block.number)) { uint256 TV = epochTV[tradeInfo.epoch][lpToken]; if (TV == 0) { return; } // maximum number of bonus block is segment per epoch uint256 reward = MintRewardLibrary.getReward(TV).mul(segment); uint256 cynReward = reward.mul(poolInfo[lpToken]).mul(tradeInfo.amount).div(TV).div(100); if (cynReward.add(totalSupply) > capacity) { cynReward = capacity.sub(totalSupply); } if (cynReward == 0) { return ; } cyn.mint(msg.sender, cynReward); cyn.mint(devaddr, cynReward.div(10)); // mining for devaddr is additional, don't count totalSupply = totalSupply.add(cynReward); // reset tradeInfo.amount = 0; } } function queryEpochTB_T(uint256 epoch, address tokenA, address tokenB) public view returns (uint256) { address lpToken = UniswapV2Library.pairFor(factory, tokenA, tokenB); if (poolInfo[lpToken] == 0) { return 0; } uint256 TV = epochTV[epoch][lpToken]; if (TV == 0) { return 0; } uint blockNumber = (currentEpochBlockNumber + segment < block.number) ? segment : (block.number - currentEpochBlockNumber); return MintRewardLibrary.getReward(TV).mul(blockNumber).mul(poolInfo[lpToken]).div(100); } // query cyn token function queryCynReward(address _address, address tokenA, address tokenB) public view returns (uint256) { address lpToken = UniswapV2Library.pairFor(factory, tokenA, tokenB); if (poolInfo[lpToken] == 0) { return 0; } TradeInfo memory tradeInfo = trader[_address][lpToken]; if (tradeInfo.amount == 0) { return 0; } // ripe if ((tradeInfo.epoch < currentEpoch) || (currentEpochBlockNumber + segment < block.number)) { uint256 TV = epochTV[tradeInfo.epoch][lpToken]; if (TV == 0) { return 0; } // maximum number of bonus block is segment per epoch uint256 reward = MintRewardLibrary.getReward(TV).mul(segment); return reward.mul(poolInfo[lpToken]).mul(tradeInfo.amount).div(TV).div(100); } // growth stage return 0; } // update trade info function _updateTrader(uint256 tradeAmount, address[] memory path) internal virtual { address lpToken = UniswapV2Library.pairFor(factory, path[0], path[path.length - 1]); if (poolInfo[lpToken] == 0) { return; } if (tradeAmount == 0) { return; } // update epoch if ((currentEpochBlockNumber + segment < block.number) || (currentEpoch == 0)) { currentEpoch ++; currentEpochBlockNumber = block.number; } claimCynReward(path[0], path[path.length - 1]); TradeInfo storage tradeInfo = trader[msg.sender][lpToken]; if (tradeInfo.amount == 0) { tradeInfo.epoch = currentEpoch; } tradeInfo.amount = tradeInfo.amount.add(tradeAmount); epochTV[currentEpoch][lpToken] = epochTV[currentEpoch][lpToken].add(tradeAmount); } function _getSwapAmountConvertETH(uint[] memory amounts, address[] memory path) internal view virtual returns (uint256) { // path[0] (tokenA) uint256 tradeAmount = getValueConvertETH(amounts[0], path[0]); if (tradeAmount == 0) { // path[path.length - 1] (tokenB) (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, path[path.length - 2], path[path.length - 1]); // amount of path[path.length - 1] uint256 amount = reserveB.mul(amounts[path.length - 2]).div(reserveA); tradeAmount = getValueConvertETH(amount, path[path.length - 1]); } return tradeAmount; } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { uint256 tradeAmount = _getSwapAmountConvertETH(amounts, path); _updateTrader(tradeAmount, path); for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); // update TV // token in uint256 tradeAmount = getValueConvertETH(amountIn, path[0]); if (tradeAmount == 0) { // token out tradeAmount = getValueConvertETH(IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore), path[path.length - 1]); } _updateTrader(tradeAmount, path); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); // update TV _updateTrader(amountIn, path); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); // update TV _updateTrader(amountOut, path); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsIn(factory, amountOut, path); } }
query cyn token ripe
function queryCynReward(address _address, address tokenA, address tokenB) public view returns (uint256) { address lpToken = UniswapV2Library.pairFor(factory, tokenA, tokenB); if (poolInfo[lpToken] == 0) { return 0; } TradeInfo memory tradeInfo = trader[_address][lpToken]; if (tradeInfo.amount == 0) { return 0; } if ((tradeInfo.epoch < currentEpoch) || (currentEpochBlockNumber + segment < block.number)) { uint256 TV = epochTV[tradeInfo.epoch][lpToken]; if (TV == 0) { return 0; } return reward.mul(poolInf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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 843, 39, 878, 17631, 1060, 12, 2867, 389, 2867, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1758, 12423, 1345, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 6017, 1290, 12, 6848, 16, 1147, 37, 16, 1147, 38, 1769, 203, 3639, 309, 261, 6011, 966, 63, 9953, 1345, 65, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 2197, 323, 966, 3778, 18542, 966, 273, 1284, 765, 63, 67, 2867, 6362, 9953, 1345, 15533, 203, 3639, 309, 261, 20077, 966, 18, 8949, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 309, 14015, 20077, 966, 18, 12015, 411, 783, 14638, 13, 747, 261, 2972, 14638, 1768, 1854, 397, 3267, 411, 1203, 18, 2696, 3719, 288, 203, 5411, 2254, 5034, 399, 58, 273, 7632, 15579, 63, 20077, 966, 18, 12015, 6362, 9953, 1345, 15533, 203, 5411, 309, 261, 15579, 422, 374, 13, 288, 203, 7734, 327, 374, 31, 203, 5411, 289, 203, 5411, 327, 19890, 18, 16411, 12, 6011, 966, 63, 9953, 1345, 65, 2934, 16411, 12, 20077, 966, 18, 8949, 2934, 2892, 12, 15579, 2934, 2892, 12, 6625, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 // If you think you may have found a vulnerability // File: @opengsn/contracts/src/interfaces/IRelayRecipient.sol pragma solidity >=0.6.0; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise (if the call was made directly and not through the forwarder), return `msg.data` * should be used in the contract instead of msg.data, where this difference matters. */ function _msgData() internal virtual view returns (bytes calldata); function versionRecipient() external virtual view returns (string memory); } // File: @opengsn/contracts/src/BaseRelayRecipient.sol // solhint-disable no-inline-assembly pragma solidity >=0.6.9; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address private _trustedForwarder; function trustedForwarder() public virtual view returns (address){ return _trustedForwarder; } function _setTrustedForwarder(address _forwarder) internal { _trustedForwarder = _forwarder; } function isTrustedForwarder(address forwarder) public virtual override view returns(bool) { return forwarder == _trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { ret = msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise (if the call was made directly and not through the forwarder), return `msg.data` * should be used in the contract instead of msg.data, where this difference matters. */ function _msgData() internal override virtual view returns (bytes calldata ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { return msg.data[0:msg.data.length-20]; } else { return msg.data; } } } // File: contracts/lib/RelayRecipient.sol pragma solidity ^0.8.0; // import "@opengsn/gsn/contracts/BaseRelayRecipient.sol"; contract RelayRecipient is BaseRelayRecipient { function versionRecipient() external pure override returns (string memory) { return "1.0.0-beta.1/charged-particles.relay.recipient"; } } // File: contracts/lib/TokenInfo.sol // TokenInfo.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. pragma solidity ^0.8.0; library TokenInfo { /** * @dev Returns true if `account` is a contract. * @dev Taken from OpenZeppelin library * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * @dev Taken from OpenZeppelin library * * 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, uint256 gasLimit ) internal { require( address(this).balance >= amount, "TokenInfo: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = (gasLimit > 0) ? recipient.call{value: amount, gas: gasLimit}("") : recipient.call{value: amount}(""); require( success, "TokenInfo: unable to send value, recipient may have reverted" ); } } // 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: contracts/interfaces/ISignatureVerifier.sol pragma solidity ^0.8.0; interface ISignatureVerifier { function verify( address _signer, address _to, uint256 _amount, uint256 _nonce, bytes memory signature ) external pure returns (bool); } // File: contracts/interfaces/IChargedParticles.sol // IChargedParticles.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. pragma solidity ^0.8.0; /** * @notice Interface for Charged Particles */ interface IChargedParticles { /***********************************| | Public API | |__________________________________*/ function getStateAddress() external view returns (address stateAddress); function getSettingsAddress() external view returns (address settingsAddress); function getManagersAddress() external view returns (address managersAddress); function getFeesForDeposit(uint256 assetAmount) external view returns (uint256 protocolFee); function baseParticleMass( address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken ) external returns (uint256); function currentParticleCharge( address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken ) external returns (uint256); function currentParticleKinetics( address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken ) external returns (uint256); function currentParticleCovalentBonds( address contractAddress, uint256 tokenId, string calldata basketManagerId ) external view returns (uint256); /***********************************| | Particle Mechanics | |__________________________________*/ function energizeParticle( address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken, uint256 assetAmount, address referrer ) external returns (uint256 yieldTokensAmount); function dischargeParticle( address receiver, address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken ) external returns (uint256 creatorAmount, uint256 receiverAmount); function dischargeParticleAmount( address receiver, address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken, uint256 assetAmount ) external returns (uint256 creatorAmount, uint256 receiverAmount); function dischargeParticleForCreator( address receiver, address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken, uint256 assetAmount ) external returns (uint256 receiverAmount); function releaseParticle( address receiver, address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken ) external returns (uint256 creatorAmount, uint256 receiverAmount); function releaseParticleAmount( address receiver, address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken, uint256 assetAmount ) external returns (uint256 creatorAmount, uint256 receiverAmount); function covalentBond( address contractAddress, uint256 tokenId, string calldata basketManagerId, address nftTokenAddress, uint256 nftTokenId ) external returns (bool success); function breakCovalentBond( address receiver, address contractAddress, uint256 tokenId, string calldata basketManagerId, address nftTokenAddress, uint256 nftTokenId ) external returns (bool success); /***********************************| | Particle Events | |__________________________________*/ event Initialized(address indexed initiator); event ControllerSet(address indexed controllerAddress, string controllerId); event DepositFeeSet(uint256 depositFee); event ProtocolFeesCollected( address indexed assetToken, uint256 depositAmount, uint256 feesCollected ); } // File: contracts/interfaces/IChargedState.sol // IChargedSettings.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. pragma solidity ^0.8.0; /** * @notice Interface for Charged State */ interface IChargedState { /***********************************| | Only NFT Owner/Operator | |__________________________________*/ function setDischargeApproval( address contractAddress, uint256 tokenId, address operator ) external; function setReleaseApproval( address contractAddress, uint256 tokenId, address operator ) external; function setBreakBondApproval( address contractAddress, uint256 tokenId, address operator ) external; function setTimelockApproval( address contractAddress, uint256 tokenId, address operator ) external; function setApprovalForAll( address contractAddress, uint256 tokenId, address operator ) external; function setPermsForRestrictCharge( address contractAddress, uint256 tokenId, bool state ) external; function setPermsForAllowDischarge( address contractAddress, uint256 tokenId, bool state ) external; function setPermsForAllowRelease( address contractAddress, uint256 tokenId, bool state ) external; function setPermsForRestrictBond( address contractAddress, uint256 tokenId, bool state ) external; function setPermsForAllowBreakBond( address contractAddress, uint256 tokenId, bool state ) external; function setDischargeTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; function setReleaseTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; function setBreakBondTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; /***********************************| | Only NFT Contract | |__________________________________*/ function setTemporaryLock( address contractAddress, uint256 tokenId, bool isLocked ) external; } // 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/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) 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: @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/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: contracts/interfaces/IERC721Consumable.sol pragma solidity ^0.8.0; /// @title ERC-721 Consumer Role extension /// Note: the ERC-165 identifier for this interface is 0x953c8dfa interface IERC721Consumable is IERC721 { /// @notice Emitted when `owner` changes the `consumer` of an NFT /// The zero address for consumer indicates that there is no consumer address /// When a Transfer event emits, this also indicates that the consumer address /// for that NFT (if any) is set to none event ConsumerChanged( address indexed owner, address indexed consumer, uint256 indexed tokenId ); /// @notice Get the consumer address of an NFT /// @dev The zero address indicates that there is no consumer /// Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to get the consumer address for /// @return The consumer address for this NFT, or the zero address if there is none function consumerOf(uint256 _tokenId) external view returns (address); /// @notice Change or reaffirm the consumer address for an NFT /// @dev The zero address indicates there is no consumer address /// Throws unless `msg.sender` is the current NFT owner, an authorised /// operator of the current owner or approved address /// Throws if `_tokenId` is not valid NFT /// @param _consumer The new consumer of the NFT function changeConsumer(address _consumer, uint256 _tokenId) external; } // File: contracts/interfaces/IParticlon.sol // Particlon.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. pragma solidity ^0.8.0; // pragma experimental ABIEncoderV2; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; // import "@openzeppelin/contracts/utils/Counters.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; // import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // import "./BlackholePrevention.sol"; // import "./RelayRecipient.sol"; interface IParticlon is IERC721 { enum EMintPhase { CLOSED, CLAIM, WHITELIST, PUBLIC } /// @notice Andy was here event NewBaseURI(string indexed _uri); event NewSignerAddress(address indexed signer); event NewMintPhase(EMintPhase indexed mintPhase); event NewMintPrice(uint256 price); event AssetTokenSet(address indexed assetToken); event ChargedStateSet(address indexed chargedState); event ChargedSettingsSet(address indexed chargedSettings); event ChargedParticlesSet(address indexed chargedParticles); event SalePriceSet(uint256 indexed tokenId, uint256 salePrice); event CreatorRoyaltiesSet(uint256 indexed tokenId, uint256 royaltiesPct); event ParticlonSold( uint256 indexed tokenId, address indexed oldOwner, address indexed newOwner, uint256 salePrice, address creator, uint256 creatorRoyalties ); event RoyaltiesClaimed(address indexed receiver, uint256 amountClaimed); /***********************************| | Public | |__________________________________*/ function creatorOf(uint256 tokenId) external view returns (address); function getSalePrice(uint256 tokenId) external view returns (uint256); function getLastSellPrice(uint256 tokenId) external view returns (uint256); function getCreatorRoyalties(address account) external view returns (uint256); function getCreatorRoyaltiesPct(uint256 tokenId) external view returns (uint256); function getCreatorRoyaltiesReceiver(uint256 tokenId) external view returns (address); function buyParticlon(uint256 tokenId, uint256 gasLimit) external payable returns (bool); function claimCreatorRoyalties() external returns (uint256); // function createParticlonForSale( // address creator, // address receiver, // // string memory tokenMetaUri, // uint256 royaltiesPercent, // uint256 salePrice // ) external returns (uint256 newTokenId); function mint(uint256 amount) external payable returns (bool); function mintWhitelist( uint256 amountMint, uint256 amountAllowed, uint256 nonce, bytes calldata signature ) external payable returns (bool); function mintFree( uint256 amountMint, uint256 amountAllowed, uint256 nonce, bytes calldata signature ) external returns (bool); // function batchParticlonsForSale( // address creator, // uint256 annuityPercent, // uint256 royaltiesPercent, // uint256[] calldata salePrices // ) external; // function createParticlonsForSale( // address creator, // address receiver, // uint256 royaltiesPercent, // // string[] calldata tokenMetaUris, // uint256[] calldata salePrices // ) external returns (bool); // Andy was here /***********************************| | Only Token Creator/Owner | |__________________________________*/ function setSalePrice(uint256 tokenId, uint256 salePrice) external; function setRoyaltiesPct(uint256 tokenId, uint256 royaltiesPct) external; function setCreatorRoyaltiesReceiver(uint256 tokenId, address receiver) external; } // 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/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/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/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: contracts/lib/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; 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 1; } /** * @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 ) internal virtual { /// @dev Andy was here, made it internal virtual to work with Charged Particles 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 {} } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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' 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"); } } } // File: contracts/lib/BlackholePrevention.sol // BlackholePrevention.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. pragma solidity ^0.8.0; /** * @notice Prevents ETH or Tokens from getting stuck in a contract by allowing * the Owner/DAO to pull them out on behalf of a user * This is only meant to contracts that are not expected to hold tokens, but do handle transferring them. */ contract BlackholePrevention { using Address for address payable; using SafeERC20 for IERC20; event WithdrawStuckEther(address indexed receiver, uint256 amount); event WithdrawStuckERC20( address indexed receiver, address indexed tokenAddress, uint256 amount ); event WithdrawStuckERC721( address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId ); event WithdrawStuckERC1155( address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId, uint256 amount ); function _withdrawEther(address payable receiver, uint256 amount) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (address(this).balance >= amount) { receiver.sendValue(amount); emit WithdrawStuckEther(receiver, amount); } } function _withdrawERC20( address payable receiver, address tokenAddress, uint256 amount ) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (IERC20(tokenAddress).balanceOf(address(this)) >= amount) { IERC20(tokenAddress).safeTransfer(receiver, amount); emit WithdrawStuckERC20(receiver, tokenAddress, amount); } } function _withdrawERC721( address payable receiver, address tokenAddress, uint256 tokenId ) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (IERC721(tokenAddress).ownerOf(tokenId) == address(this)) { IERC721(tokenAddress).transferFrom( address(this), receiver, tokenId ); emit WithdrawStuckERC721(receiver, tokenAddress, tokenId); } } function _withdrawERC1155( address payable receiver, address tokenAddress, uint256 tokenId, uint256 amount ) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if ( IERC1155(tokenAddress).balanceOf(address(this), tokenId) >= amount ) { IERC1155(tokenAddress).safeTransferFrom( address(this), receiver, tokenId, amount, "" ); emit WithdrawStuckERC1155(receiver, tokenAddress, tokenId, amount); } } } // File: contracts/Particlon.sol // ParticlonB.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. pragma solidity ^0.8.0; contract Particlon is IParticlon, ERC721A, IERC721Consumable, Ownable, Pausable, RelayRecipient, ReentrancyGuard, BlackholePrevention { // using SafeMath for uint256; // not needed since solidity 0.8 using TokenInfo for address payable; using Strings for uint256; /// @dev In case we want to revoke the consumer part bool internal _revokeConsumerOnTransfer; /// @notice Address used to generate cryptographic signatures for whitelisted addresses address internal _signer = 0xE8cF9826C7702411bb916c447D759E0E631d2e68; uint256 internal _nonceClaim = 69; uint256 internal _nonceWL = 420; uint256 public constant MAX_SUPPLY = 10069; uint256 public constant INITIAL_PRICE = 0.15 ether; uint256 internal constant PERCENTAGE_SCALE = 1e4; // 10000 (100%) uint256 internal constant MAX_ROYALTIES = 8e3; // 8000 (80%) // Charged Particles V1 mainnet IChargedState internal _chargedState = IChargedState(0xB29256073C63960daAa398f1227D0adBC574341C); // IChargedSettings internal _chargedSettings; IChargedParticles internal _chargedParticles = IChargedParticles(0xaB1a1410EA40930755C1330Cc0fB3367897C8c41); /// @notice This needs to be set using the setAssetToken in order to get approved address internal _assetToken; // This right here drops the size so it doesn't break the limitation // Enable optimization also has to be tured on! ISignatureVerifier internal constant _signatureVerifier = ISignatureVerifier(0x47a0915747565E8264296457b894068fe5CA9186); uint256 internal _mintPrice; string internal _baseUri = "ipfs://QmQrdG1cESrBenNUaTmxckFm4gJwgLdkqTGxNLuh4t5vo8/"; // Mapping from token ID to consumer address mapping(uint256 => address) _tokenConsumers; mapping(uint256 => address) internal _tokenCreator; mapping(uint256 => uint256) internal _tokenCreatorRoyaltiesPct; mapping(uint256 => address) internal _tokenCreatorRoyaltiesRedirect; mapping(address => uint256) internal _tokenCreatorClaimableRoyalties; mapping(uint256 => uint256) internal _tokenSalePrice; mapping(uint256 => uint256) internal _tokenLastSellPrice; /// @notice Adhere to limits per whitelisted wallet for claim mint phase mapping(address => uint256) internal _mintPassMinted; /// @notice Adhere to limits per whitelisted wallet for whitelist mint phase mapping(address => uint256) internal _whitelistedAddressMinted; /// @notice set to CLOSED by default EMintPhase public mintPhase; /***********************************| | Initialization | |__________________________________*/ constructor() ERC721A("Particlon", "PART") { _mintPrice = INITIAL_PRICE; } /***********************************| | Public | |__________________________________*/ // Define an "onlyOwner" switch function setRevokeConsumerOnTransfer(bool state) external onlyOwner { _revokeConsumerOnTransfer = state; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(IERC165, ERC721A) returns (bool) { return interfaceId == type(IERC721Consumable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Consumable-consumerOf} */ function consumerOf(uint256 _tokenId) external view returns (address) { require( _exists(_tokenId), "ERC721Consumable: consumer query for nonexistent token" ); return _tokenConsumers[_tokenId]; } function creatorOf(uint256 tokenId) external view override returns (address) { return _tokenCreator[tokenId]; } function getSalePrice(uint256 tokenId) external view override returns (uint256) { return _tokenSalePrice[tokenId]; } function getLastSellPrice(uint256 tokenId) external view override returns (uint256) { return _tokenLastSellPrice[tokenId]; } function getCreatorRoyalties(address account) external view override returns (uint256) { return _tokenCreatorClaimableRoyalties[account]; } function getCreatorRoyaltiesPct(uint256 tokenId) external view override returns (uint256) { return _tokenCreatorRoyaltiesPct[tokenId]; } function getCreatorRoyaltiesReceiver(uint256 tokenId) external view override returns (address) { return _creatorRoyaltiesReceiver(tokenId); } function claimCreatorRoyalties() external override nonReentrant whenNotPaused returns (uint256) { return _claimCreatorRoyalties(_msgSender()); } /***********************************| | Create Multiple Particlons | |__________________________________*/ /// @notice Andy was here function mint(uint256 amount) external payable override nonReentrant whenNotPaused notBeforePhase(EMintPhase.PUBLIC) whenRemainingSupply requirePayment(amount) returns (bool) { // They may have minted 10, but if only 2 remain in supply, then they will only get 2, so only pay for 2 uint256 actualPrice = _mintAmount(amount, _msgSender()); _refundOverpayment(actualPrice, 0); // dont worry about gasLimit here as the "minter" could only hook themselves return true; } /// @notice Andy was here function mintWhitelist( uint256 amountMint, uint256 amountAllowed, uint256 nonce, bytes calldata signature ) external payable override nonReentrant whenNotPaused notBeforePhase(EMintPhase.WHITELIST) whenRemainingSupply requirePayment(amountMint) requireWhitelist(amountMint, amountAllowed, nonce, signature) returns (bool) { // They may have been whitelisted to mint 10, but if only 2 remain in supply, then they will only get 2, so only pay for 2 uint256 actualPrice = _mintAmount(amountMint, _msgSender()); _refundOverpayment(actualPrice, 0); return true; } function mintFree( uint256 amountMint, uint256 amountAllowed, uint256 nonce, bytes calldata signature ) external override whenNotPaused notBeforePhase(EMintPhase.CLAIM) whenRemainingSupply requirePass(amountMint, amountAllowed, nonce, signature) returns (bool) { // They may have been whitelisted to mint 10, but if only 2 remain in supply, then they will only get 2 _mintAmount(amountMint, _msgSender()); return true; } /***********************************| | Buy Particlons | |__________________________________*/ function buyParticlon(uint256 tokenId, uint256 gasLimit) external payable override nonReentrant whenNotPaused returns (bool) { _buyParticlon(tokenId, gasLimit); return true; } /***********************************| | Only Token Creator/Owner | |__________________________________*/ function setSalePrice(uint256 tokenId, uint256 salePrice) external override whenNotPaused onlyTokenOwnerOrApproved(tokenId) { _setSalePrice(tokenId, salePrice); } function setRoyaltiesPct(uint256 tokenId, uint256 royaltiesPct) external override whenNotPaused onlyTokenCreator(tokenId) onlyTokenOwnerOrApproved(tokenId) { _setRoyaltiesPct(tokenId, royaltiesPct); } function setCreatorRoyaltiesReceiver(uint256 tokenId, address receiver) external override whenNotPaused onlyTokenCreator(tokenId) { _tokenCreatorRoyaltiesRedirect[tokenId] = receiver; } /** * @dev See {IERC721Consumable-changeConsumer} */ function changeConsumer(address _consumer, uint256 _tokenId) external { address owner = this.ownerOf(_tokenId); require( _msgSender() == owner || _msgSender() == getApproved(_tokenId) || isApprovedForAll(owner, _msgSender()), "ERC721Consumable: changeConsumer caller is not owner nor approved" ); _changeConsumer(owner, _consumer, _tokenId); } /***********************************| | Only Admin/DAO | |__________________________________*/ // Andy was here (Andy is everywhere) function setSignerAddress(address signer) external onlyOwner { _signer = signer; emit NewSignerAddress(signer); } // In case we need to "undo" a signature/prevent it from being used, // This is easier than changing the signer // we would also need to remake all unused signatures function setNonces(uint256 nonceClaim, uint256 nonceWL) external onlyOwner { _nonceClaim = nonceClaim; _nonceWL = nonceWL; } function setAssetToken(address assetToken) external onlyOwner { _assetToken = assetToken; // Need to Approve Charged Particles to transfer Assets from Particlon IERC20(assetToken).approve( address(_chargedParticles), type(uint256).max ); emit AssetTokenSet(assetToken); } function setMintPrice(uint256 price) external onlyOwner { _mintPrice = price; emit NewMintPrice(price); } /// @notice This is needed for the reveal function setURI(string memory uri) external onlyOwner { _baseUri = uri; emit NewBaseURI(uri); } function setMintPhase(EMintPhase _mintPhase) external onlyOwner { mintPhase = _mintPhase; emit NewMintPhase(_mintPhase); } function setPausedState(bool state) external onlyOwner { state ? _pause() : _unpause(); // these emit events } /** * @dev Setup the ChargedParticles Interface */ function setChargedParticles(address chargedParticles) external onlyOwner { _chargedParticles = IChargedParticles(chargedParticles); emit ChargedParticlesSet(chargedParticles); } /// @dev Setup the Charged-State Controller function setChargedState(address stateController) external onlyOwner { _chargedState = IChargedState(stateController); emit ChargedStateSet(stateController); } /// @dev Setup the Charged-Settings Controller // function setChargedSettings(address settings) external onlyOwner { // _chargedSettings = IChargedSettings(settings); // emit ChargedSettingsSet(settings); // } function setTrustedForwarder(address _trustedForwarder) external onlyOwner { _setTrustedForwarder(_trustedForwarder); // Andy was here, trustedForwarder is already defined in opengsn/contracts/src/BaseRelayRecipient.sol } /***********************************| | Only Admin/DAO | | (blackhole prevention) | |__________________________________*/ function withdrawEther(address payable receiver, uint256 amount) external onlyOwner { _withdrawEther(receiver, amount); } function withdrawERC20( address payable receiver, address tokenAddress, uint256 amount ) external onlyOwner { _withdrawERC20(receiver, tokenAddress, amount); } function withdrawERC721( address payable receiver, address tokenAddress, uint256 tokenId ) external onlyOwner { _withdrawERC721(receiver, tokenAddress, tokenId); } /***********************************| | Private Functions | |__________________________________*/ function _baseURI() internal view override returns (string memory) { return _baseUri; } function _mintAmount(uint256 amount, address creator) internal returns (uint256 actualPrice) { uint256 newTokenId = totalSupply(); // newTokenId is equal to the supply at this stage if (newTokenId + amount > MAX_SUPPLY) { amount = MAX_SUPPLY - newTokenId; } // totalSupply += amount; // _safeMint's second argument now takes in a quantity, not a tokenId. _safeMint(creator, amount); actualPrice = amount * _mintPrice; // Charge people for the ACTUAL amount minted; uint256 assetAmount; newTokenId++; for (uint256 i; i < amount; i++) { // Set the first minters as the creators _tokenCreator[newTokenId + i] = creator; assetAmount += _getAssetAmount(newTokenId + i); // _chargeParticlon(newTokenId, "generic", assetAmount); } // Put all ERC20 tokens into the first Particlon to save a lot of gas _chargeParticlon(newTokenId, "generic", assetAmount); } /** * @dev Changes the consumer * Requirement: `tokenId` must exist */ function _changeConsumer( address _owner, address _consumer, uint256 _tokenId ) internal { _tokenConsumers[_tokenId] = _consumer; emit ConsumerChanged(_owner, _consumer, _tokenId); } function _beforeTokenTransfers( address _from, address _to, uint256 _startTokenId, uint256 _quantity ) internal virtual override(ERC721A) { if (_from == address(0)) { return; } super._beforeTokenTransfers(_from, _to, _startTokenId, _quantity); require(!paused(), "ERC721Pausable: token transfer while paused"); if (_revokeConsumerOnTransfer) { /// @notice quantity is always one in this case _changeConsumer(_from, address(0), _startTokenId); } } function _setSalePrice(uint256 tokenId, uint256 salePrice) internal { _tokenSalePrice[tokenId] = salePrice; // Temp-Lock/Unlock NFT // prevents front-running the sale and draining the value of the NFT just before sale _chargedState.setTemporaryLock(address(this), tokenId, (salePrice > 0)); emit SalePriceSet(tokenId, salePrice); } function _setRoyaltiesPct(uint256 tokenId, uint256 royaltiesPct) internal { require(royaltiesPct <= MAX_ROYALTIES, "PRT:E-421"); // Andy was here _tokenCreatorRoyaltiesPct[tokenId] = royaltiesPct; emit CreatorRoyaltiesSet(tokenId, royaltiesPct); } function _creatorRoyaltiesReceiver(uint256 tokenId) internal view returns (address) { address receiver = _tokenCreatorRoyaltiesRedirect[tokenId]; if (receiver == address(0x0)) { receiver = _tokenCreator[tokenId]; } return receiver; } /// @notice The tokens from a batch are being nested into the first NFT minted in that batch function _getAssetAmount(uint256 tokenId) internal pure returns (uint256) { if (tokenId == MAX_SUPPLY) { return 1596 * 10**18; } else if (tokenId > 9000) { return 1403 * 10**18; } else if (tokenId > 6000) { return 1000 * 10**18; } else if (tokenId > 3000) { return 1500 * 10**18; } else if (tokenId > 1000) { return 1750 * 10**18; } return 2500 * 10**18; } function _chargeParticlon( uint256 tokenId, string memory walletManagerId, uint256 assetAmount ) internal { address _self = address(this); _chargedParticles.energizeParticle( _self, tokenId, walletManagerId, _assetToken, assetAmount, _self ); } function _buyParticlon(uint256 _tokenId, uint256 _gasLimit) internal returns ( address contractAddress, uint256 tokenId, address oldOwner, address newOwner, uint256 salePrice, address royaltiesReceiver, uint256 creatorAmount ) { contractAddress = address(this); tokenId = _tokenId; salePrice = _tokenSalePrice[_tokenId]; require(salePrice > 0, "PRT:E-416"); require(msg.value >= salePrice, "PRT:E-414"); uint256 ownerAmount = salePrice; // creatorAmount; oldOwner = ownerOf(_tokenId); newOwner = _msgSender(); // Creator Royalties royaltiesReceiver = _creatorRoyaltiesReceiver(_tokenId); uint256 royaltiesPct = _tokenCreatorRoyaltiesPct[_tokenId]; uint256 lastSellPrice = _tokenLastSellPrice[_tokenId]; if ( royaltiesPct > 0 && lastSellPrice > 0 && salePrice > lastSellPrice ) { creatorAmount = ((salePrice - lastSellPrice) * royaltiesPct) / PERCENTAGE_SCALE; ownerAmount -= creatorAmount; } _tokenLastSellPrice[_tokenId] = salePrice; // Reserve Royalties for Creator if (creatorAmount > 0) { _tokenCreatorClaimableRoyalties[royaltiesReceiver] += creatorAmount; } // Transfer Token _transfer(oldOwner, newOwner, _tokenId); emit ParticlonSold( _tokenId, oldOwner, newOwner, salePrice, royaltiesReceiver, creatorAmount ); // Transfer Payment if (ownerAmount > 0) { payable(oldOwner).sendValue(ownerAmount, _gasLimit); } _refundOverpayment(salePrice, _gasLimit); } /** * @dev Pays out the Creator Royalties of the calling account * @param receiver The receiver of the claimable royalties * @return The amount of Creator Royalties claimed */ function _claimCreatorRoyalties(address receiver) internal returns (uint256) { uint256 claimableAmount = _tokenCreatorClaimableRoyalties[receiver]; require(claimableAmount > 0, "PRT:E-411"); delete _tokenCreatorClaimableRoyalties[receiver]; payable(receiver).sendValue(claimableAmount, 0); emit RoyaltiesClaimed(receiver, claimableAmount); // Andy was here return claimableAmount; } function _refundOverpayment(uint256 threshold, uint256 gasLimit) internal { // Andy was here, removed SafeMath uint256 overage = msg.value - threshold; if (overage > 0) { payable(_msgSender()).sendValue(overage, gasLimit); } } function _transfer( address from, address to, uint256 tokenId ) internal override { // Unlock NFT _tokenSalePrice[tokenId] = 0; // Andy was here _chargedState.setTemporaryLock(address(this), tokenId, false); super._transfer(from, to, tokenId); } /***********************************| | GSN/MetaTx Relay | |__________________________________*/ /// @dev See {BaseRelayRecipient-_msgSender}. /// Andy: removed payable function _msgSender() internal view override(BaseRelayRecipient, Context) returns (address) { return BaseRelayRecipient._msgSender(); } /// @dev See {BaseRelayRecipient-_msgData}. function _msgData() internal view override(BaseRelayRecipient, Context) returns (bytes memory) { return BaseRelayRecipient._msgData(); } /// @dev This is missing from ERC721A for some reason. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /***********************************| | Modifiers | |__________________________________*/ // Andy was here modifier notBeforePhase(EMintPhase _mintPhase) { require(mintPhase >= _mintPhase, "MINT PHASE ERR"); _; } modifier whenRemainingSupply() { require(totalSupply() <= MAX_SUPPLY, "SUPPLY LIMIT"); _; } modifier requirePayment(uint256 amount) { uint256 fullPrice = amount * _mintPrice; require(msg.value >= fullPrice, "LOW ETH"); _; } modifier requireWhitelist( uint256 amountMint, uint256 amountAllowed, uint256 nonce, bytes calldata signature ) { require(amountMint <= amountAllowed, "AMOUNT ERR"); require(nonce == _nonceWL, "NONCE ERR"); require( _signatureVerifier.verify( _signer, _msgSender(), amountAllowed, nonce, // prevent WL signatures being used for claiming signature ), "SIGNATURE ERR" ); require( _whitelistedAddressMinted[_msgSender()] + amountMint <= amountAllowed, "CLAIM ERR" ); _whitelistedAddressMinted[_msgSender()] += amountMint; _; } /// @notice A snapshot is taken before the mint (mint pass NFT count is taken into consideration) modifier requirePass( uint256 amountMint, uint256 amountAllowed, uint256 nonce, bytes calldata signature ) { require(amountMint <= amountAllowed, "AMOUNT ERR"); require(nonce == _nonceClaim, "NONCE ERR"); require( _signatureVerifier.verify( _signer, _msgSender(), amountAllowed, nonce, signature ), "SIGNATURE ERR" ); require( _mintPassMinted[_msgSender()] + amountMint <= amountAllowed, "CLAIM ERR" ); _mintPassMinted[_msgSender()] += amountMint; _; } modifier onlyTokenOwnerOrApproved(uint256 tokenId) { require(_isApprovedOrOwner(_msgSender(), tokenId), "PRT:E-105"); _; } modifier onlyTokenCreator(uint256 tokenId) { require(_tokenCreator[tokenId] == _msgSender(), "PRT:E-104"); _; } }
In case we need to "undo" a signature/prevent it from being used, This is easier than changing the signer we would also need to remake all unused signatures
function setNonces(uint256 nonceClaim, uint256 nonceWL) external onlyOwner { _nonceClaim = nonceClaim; _nonceWL = nonceWL; }
14,387,831
[ 1, 4625, 348, 7953, 560, 30, 225, 657, 648, 732, 1608, 358, 315, 31226, 6, 279, 3372, 19, 29150, 518, 628, 3832, 1399, 16, 1220, 353, 15857, 2353, 12770, 326, 10363, 732, 4102, 2546, 1608, 358, 849, 911, 777, 10197, 14862, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3989, 764, 12, 11890, 5034, 7448, 9762, 16, 2254, 5034, 7448, 59, 48, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 12824, 9762, 273, 7448, 9762, 31, 203, 3639, 389, 12824, 59, 48, 273, 7448, 59, 48, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x7F0e93339F45683B122d4d10498ACaa1aCcF7BD5/sources/auction.sol
mapping(uint256 => auction)auctiondetails;mapping(address => mapping(uint256 => uint256))biddersdetails;bidder[] internal bidders;
contract Auction is IERC721Receiver{ using Counters for Counters.Counter; using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; IERC721 public TokenX; mapping(address => uint256)conductedAuction; mapping(address => mapping(uint256 =>uint256))participatedAuction; uint256 public auctionTime = uint256(5 days); Counters.Counter private totalAuctionId; auction[] internal auctions; EnumerableSet.UintSet private TokenIds; mapping(uint256 => bidder)bidHistory; pragma solidity 0.7.6; enum auctionStatus { ACTIVE, OVER } struct auction{ uint256 auctionId; uint256 start; uint256 end; uint256 tokenId; address auctioner; address highestBidder; uint256 highestBid; address[] prevBid; uint256[] prevBidAmounts; auctionStatus status; } struct bidder{ uint256 auctionId; address[] bidders; } constructor(IERC721 _tokenx){ TokenX = _tokenx; } uint256[] public saleauctionarray; function getTotalid() public view returns(uint[] memory) { return saleauctionarray; } function createSaleAuction(uint256 _tokenId,uint256 _price)public returns(uint256){ require(TokenX.ownerOf(_tokenId) == msg.sender,"Auction your NFT"); saleauctionarray.push(_tokenId); auction memory _auction = auction({ auctionId : totalAuctionId.current(), start: block.number, end : block.number.add(auctionTime), tokenId: _tokenId, auctioner: msg.sender, highestBidder: msg.sender, highestBid: _price, prevBid : new address[](0), prevBidAmounts : new uint256[](0), status: auctionStatus.ACTIVE }); totalAuctionId.increment(); auctions.push(_auction); conductedAuction[msg.sender] = totalAuctionId.current(); TokenX.safeTransferFrom(msg.sender,address(this),_tokenId); return uint256(totalAuctionId.current()); } function createSaleAuction(uint256 _tokenId,uint256 _price)public returns(uint256){ require(TokenX.ownerOf(_tokenId) == msg.sender,"Auction your NFT"); saleauctionarray.push(_tokenId); auction memory _auction = auction({ auctionId : totalAuctionId.current(), start: block.number, end : block.number.add(auctionTime), tokenId: _tokenId, auctioner: msg.sender, highestBidder: msg.sender, highestBid: _price, prevBid : new address[](0), prevBidAmounts : new uint256[](0), status: auctionStatus.ACTIVE }); totalAuctionId.increment(); auctions.push(_auction); conductedAuction[msg.sender] = totalAuctionId.current(); TokenX.safeTransferFrom(msg.sender,address(this),_tokenId); return uint256(totalAuctionId.current()); } function placeBid(uint256 _auctionId)public payable returns(bool){ require(auctions[_auctionId].highestBid < msg.value,"Place a higher Bid"); require(auctions[_auctionId].auctioner != msg.sender,"Not allowed"); require(auctions[_auctionId].end > block.number,"Auction Finished"); auction storage auction = auctions[_auctionId]; auction.prevBid.push(auction.highestBidder); auction.prevBidAmounts.push(auction.highestBid); if(participatedAuction[auction.highestBidder][_auctionId] > 0){ participatedAuction[auction.highestBidder][_auctionId] = participatedAuction[auction.highestBidder][_auctionId].add(auction.highestBid); participatedAuction[auction.highestBidder][_auctionId] = auction.highestBid; } auction.highestBidder = msg.sender; auction.highestBid = msg.value; return true; } function placeBid(uint256 _auctionId)public payable returns(bool){ require(auctions[_auctionId].highestBid < msg.value,"Place a higher Bid"); require(auctions[_auctionId].auctioner != msg.sender,"Not allowed"); require(auctions[_auctionId].end > block.number,"Auction Finished"); auction storage auction = auctions[_auctionId]; auction.prevBid.push(auction.highestBidder); auction.prevBidAmounts.push(auction.highestBid); if(participatedAuction[auction.highestBidder][_auctionId] > 0){ participatedAuction[auction.highestBidder][_auctionId] = participatedAuction[auction.highestBidder][_auctionId].add(auction.highestBid); participatedAuction[auction.highestBidder][_auctionId] = auction.highestBid; } auction.highestBidder = msg.sender; auction.highestBid = msg.value; return true; } }else{ function finishAuction(uint256 _auctionId) public{ require(auctions[_auctionId].auctioner == msg.sender,"only auctioner"); auction storage auction = auctions[_auctionId]; auction.end = block.number; auction.status = auctionStatus.OVER; if(auction.prevBid.length > 0){ for(uint256 i = 1; i < auction.prevBid.length; i++){ if(participatedAuction[auctions[_auctionId].prevBid[i]][_auctionId] == auctions[_auctionId].prevBidAmounts[i] ){ address payable give = payable(auctions[_auctionId].prevBid[i]); uint256 repay = auctions[_auctionId].prevBidAmounts[i]; give.transfer(repay); } } msg.sender.transfer(auctions[_auctionId].highestBid); TokenX.safeTransferFrom(address(this),auctions[_auctionId].highestBidder,auctions[_auctionId].tokenId); } } function finishAuction(uint256 _auctionId) public{ require(auctions[_auctionId].auctioner == msg.sender,"only auctioner"); auction storage auction = auctions[_auctionId]; auction.end = block.number; auction.status = auctionStatus.OVER; if(auction.prevBid.length > 0){ for(uint256 i = 1; i < auction.prevBid.length; i++){ if(participatedAuction[auctions[_auctionId].prevBid[i]][_auctionId] == auctions[_auctionId].prevBidAmounts[i] ){ address payable give = payable(auctions[_auctionId].prevBid[i]); uint256 repay = auctions[_auctionId].prevBidAmounts[i]; give.transfer(repay); } } msg.sender.transfer(auctions[_auctionId].highestBid); TokenX.safeTransferFrom(address(this),auctions[_auctionId].highestBidder,auctions[_auctionId].tokenId); } } function finishAuction(uint256 _auctionId) public{ require(auctions[_auctionId].auctioner == msg.sender,"only auctioner"); auction storage auction = auctions[_auctionId]; auction.end = block.number; auction.status = auctionStatus.OVER; if(auction.prevBid.length > 0){ for(uint256 i = 1; i < auction.prevBid.length; i++){ if(participatedAuction[auctions[_auctionId].prevBid[i]][_auctionId] == auctions[_auctionId].prevBidAmounts[i] ){ address payable give = payable(auctions[_auctionId].prevBid[i]); uint256 repay = auctions[_auctionId].prevBidAmounts[i]; give.transfer(repay); } } msg.sender.transfer(auctions[_auctionId].highestBid); TokenX.safeTransferFrom(address(this),auctions[_auctionId].highestBidder,auctions[_auctionId].tokenId); } } function finishAuction(uint256 _auctionId) public{ require(auctions[_auctionId].auctioner == msg.sender,"only auctioner"); auction storage auction = auctions[_auctionId]; auction.end = block.number; auction.status = auctionStatus.OVER; if(auction.prevBid.length > 0){ for(uint256 i = 1; i < auction.prevBid.length; i++){ if(participatedAuction[auctions[_auctionId].prevBid[i]][_auctionId] == auctions[_auctionId].prevBidAmounts[i] ){ address payable give = payable(auctions[_auctionId].prevBid[i]); uint256 repay = auctions[_auctionId].prevBidAmounts[i]; give.transfer(repay); } } msg.sender.transfer(auctions[_auctionId].highestBid); TokenX.safeTransferFrom(address(this),auctions[_auctionId].highestBidder,auctions[_auctionId].tokenId); } } function auctionStatusCheck(uint256 _auctionId)public view returns(bool){ if(auctions[_auctionId].end > block.number){ return true; return false; } } function auctionStatusCheck(uint256 _auctionId)public view returns(bool){ if(auctions[_auctionId].end > block.number){ return true; return false; } } }else{ function auctionInfo(uint256 _auctionId)public view returns( uint256 auctionId, uint256 start, uint256 end, uint256 tokenId, address auctioner, address highestBidder, uint256 highestBid, uint256 status){ auction storage auction = auctions[_auctionId]; auctionId = _auctionId; start = auction.start; end =auction.end; tokenId = auction.tokenId; auctioner = auction.auctioner; highestBidder = auction.highestBidder; highestBid = auction.highestBid; status = uint256(auction.status); } function bidHistory1(uint256 _auctionId) public view returns(address[]memory,uint256[]memory){ return (auctions[_auctionId].prevBid,auctions[_auctionId].prevBidAmounts); } function activeAuctionList()public view returns(auction[] memory){ auction[] memory list = new auction[](0); for(uint256 i = 0; i < auctions.length;i++){ if(auctionStatusCheck(i) == true){ list[i] = auctions[i]; } } return list; } function activeAuctionList()public view returns(auction[] memory){ auction[] memory list = new auction[](0); for(uint256 i = 0; i < auctions.length;i++){ if(auctionStatusCheck(i) == true){ list[i] = auctions[i]; } } return list; } function activeAuctionList()public view returns(auction[] memory){ auction[] memory list = new auction[](0); for(uint256 i = 0; i < auctions.length;i++){ if(auctionStatusCheck(i) == true){ list[i] = auctions[i]; } } return list; } function participatedAuctions(address _user) public view returns(uint256[]memory){ uint256[] memory participated = new uint256[](0); for(uint256 i = 0;i< auctions.length;i++){ if(participatedAuction[_user][i] > 0){ participated[i] = participatedAuction[_user][i]; } } return participated; } function participatedAuctions(address _user) public view returns(uint256[]memory){ uint256[] memory participated = new uint256[](0); for(uint256 i = 0;i< auctions.length;i++){ if(participatedAuction[_user][i] > 0){ participated[i] = participatedAuction[_user][i]; } } return participated; } function participatedAuctions(address _user) public view returns(uint256[]memory){ uint256[] memory participated = new uint256[](0); for(uint256 i = 0;i< auctions.length;i++){ if(participatedAuction[_user][i] > 0){ participated[i] = participatedAuction[_user][i]; } } return participated; } function onERC721Received(address _operator,address _from,uint256 _tokenId,bytes calldata _data) external override returns(bytes4) { require(msg.sender == address(TokenX), "received from unauthenticated contract" ); TokenIds.add(_tokenId); return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } }
8,189,052
[ 1, 4625, 348, 7953, 560, 30, 2874, 12, 11890, 5034, 516, 279, 4062, 13, 69, 4062, 6395, 31, 6770, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 70, 1873, 414, 6395, 31, 19773, 765, 8526, 2713, 324, 1873, 414, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 432, 4062, 353, 467, 654, 39, 27, 5340, 12952, 95, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 203, 377, 203, 565, 467, 654, 39, 27, 5340, 1071, 3155, 60, 31, 203, 377, 203, 377, 2874, 12, 2867, 516, 2254, 5034, 13, 591, 1828, 329, 37, 4062, 31, 203, 1377, 203, 377, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 11890, 5034, 3719, 2680, 24629, 690, 37, 4062, 31, 203, 377, 203, 377, 203, 377, 203, 377, 203, 565, 2254, 5034, 1071, 279, 4062, 950, 273, 2254, 5034, 12, 25, 4681, 1769, 27699, 377, 203, 565, 9354, 87, 18, 4789, 3238, 2078, 37, 4062, 548, 31, 203, 377, 203, 377, 203, 565, 279, 4062, 8526, 2713, 279, 4062, 87, 31, 203, 377, 203, 565, 6057, 25121, 694, 18, 5487, 694, 3238, 3155, 2673, 31, 203, 377, 203, 377, 203, 565, 2874, 12, 11890, 5034, 516, 9949, 765, 13, 19773, 5623, 31, 203, 377, 203, 377, 203, 377, 203, 683, 9454, 18035, 560, 374, 18, 27, 18, 26, 31, 203, 565, 2792, 279, 4062, 1482, 288, 21135, 16, 22577, 289, 203, 565, 1958, 279, 4062, 95, 203, 3639, 2254, 5034, 279, 4062, 548, 31, 203, 3639, 2254, 5034, 787, 31, 203, 3639, 2254, 5034, 679, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 3639, 1758, 279, 4062, 264, 31, 203, 3639, 1758, 9742, 17763, 765, 31, 203, 3639, 2254, 5034, 9742, 17763, 31, 203, 3639, 1758, 8526, 2807, 17763, 31, 203, 3639, 2254, 5034, 8526, 2807, 17763, 6275, 87, 31, 203, 3639, 279, 4062, 1482, 1267, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 9949, 765, 95, 203, 3639, 2254, 5034, 279, 4062, 548, 31, 203, 3639, 1758, 8526, 324, 1873, 414, 31, 203, 565, 289, 203, 377, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 2316, 92, 15329, 203, 3639, 3155, 60, 273, 389, 2316, 92, 31, 203, 565, 289, 203, 377, 203, 565, 2254, 5034, 8526, 1071, 272, 5349, 69, 4062, 1126, 31, 203, 377, 203, 565, 445, 3181, 352, 567, 1435, 1071, 1476, 1135, 12, 11890, 8526, 3778, 13, 288, 203, 3639, 327, 272, 5349, 69, 4062, 1126, 31, 203, 565, 289, 203, 203, 377, 203, 565, 445, 752, 30746, 37, 4062, 12, 11890, 5034, 389, 2316, 548, 16, 11890, 5034, 389, 8694, 13, 482, 1135, 12, 11890, 5034, 15329, 203, 202, 565, 2583, 12, 1345, 60, 18, 8443, 951, 24899, 2316, 548, 13, 422, 1234, 18, 15330, 10837, 37, 4062, 3433, 423, 4464, 8863, 203, 202, 377, 203, 202, 565, 272, 5349, 69, 4062, 1126, 18, 6206, 24899, 2316, 548, 1769, 203, 202, 7010, 202, 377, 203, 202, 377, 203, 202, 565, 279, 4062, 3778, 389, 69, 4062, 273, 279, 4062, 12590, 203, 202, 565, 279, 4062, 548, 294, 2078, 37, 4062, 548, 18, 2972, 9334, 203, 3639, 787, 30, 1203, 18, 2696, 16, 203, 3639, 679, 294, 1203, 18, 2696, 18, 1289, 12, 69, 4062, 950, 3631, 203, 3639, 1147, 548, 30, 389, 2316, 548, 16, 203, 3639, 279, 4062, 264, 30, 1234, 18, 15330, 16, 203, 3639, 9742, 17763, 765, 30, 1234, 18, 15330, 16, 203, 3639, 9742, 17763, 30, 389, 8694, 16, 203, 3639, 2807, 17763, 294, 394, 1758, 8526, 12, 20, 3631, 203, 3639, 2807, 17763, 6275, 87, 294, 394, 2254, 5034, 8526, 12, 20, 3631, 203, 3639, 1267, 30, 279, 4062, 1482, 18, 13301, 203, 202, 540, 203, 202, 565, 15549, 203, 202, 565, 2078, 37, 4062, 548, 18, 15016, 5621, 203, 202, 565, 279, 4062, 87, 18, 6206, 24899, 69, 4062, 1769, 203, 202, 377, 203, 202, 377, 356, 1828, 329, 37, 4062, 63, 3576, 18, 15330, 65, 273, 2078, 37, 4062, 548, 18, 2972, 5621, 203, 202, 377, 3155, 60, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 2867, 12, 2211, 3631, 67, 2316, 548, 1769, 203, 202, 377, 327, 2254, 5034, 12, 4963, 37, 4062, 548, 18, 2972, 10663, 203, 565, 289, 203, 377, 203, 565, 445, 752, 30746, 37, 4062, 12, 11890, 5034, 389, 2316, 548, 16, 11890, 5034, 389, 8694, 13, 482, 1135, 12, 11890, 5034, 15329, 203, 202, 565, 2583, 12, 1345, 60, 18, 8443, 951, 24899, 2316, 548, 13, 422, 1234, 18, 15330, 10837, 37, 4062, 3433, 423, 4464, 8863, 203, 202, 377, 203, 202, 565, 272, 5349, 69, 4062, 1126, 18, 6206, 24899, 2316, 548, 1769, 203, 202, 7010, 202, 377, 203, 202, 377, 203, 202, 565, 279, 4062, 3778, 389, 69, 4062, 273, 279, 4062, 12590, 203, 202, 565, 279, 4062, 548, 294, 2078, 37, 4062, 548, 18, 2972, 9334, 203, 3639, 787, 30, 1203, 18, 2696, 16, 203, 3639, 679, 294, 1203, 18, 2696, 18, 1289, 12, 69, 4062, 950, 3631, 203, 3639, 1147, 548, 30, 389, 2316, 548, 16, 203, 3639, 279, 4062, 264, 30, 1234, 18, 15330, 16, 203, 3639, 9742, 17763, 765, 30, 1234, 18, 15330, 16, 203, 3639, 9742, 17763, 30, 389, 8694, 16, 203, 3639, 2807, 17763, 294, 394, 1758, 8526, 12, 20, 3631, 203, 3639, 2807, 17763, 6275, 87, 294, 394, 2254, 5034, 8526, 12, 20, 3631, 203, 3639, 1267, 30, 279, 4062, 1482, 18, 13301, 203, 202, 540, 203, 202, 565, 15549, 203, 202, 565, 2078, 37, 4062, 548, 18, 15016, 5621, 203, 202, 565, 279, 4062, 87, 18, 6206, 24899, 69, 4062, 1769, 203, 202, 377, 203, 202, 377, 356, 1828, 329, 37, 4062, 63, 3576, 18, 15330, 65, 273, 2078, 37, 4062, 548, 18, 2972, 5621, 203, 202, 377, 3155, 60, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 2867, 12, 2211, 3631, 67, 2316, 548, 1769, 203, 202, 377, 327, 2254, 5034, 12, 4963, 37, 4062, 548, 18, 2972, 10663, 203, 565, 289, 203, 377, 203, 202, 1377, 203, 202, 1377, 203, 565, 445, 3166, 17763, 12, 11890, 5034, 389, 69, 4062, 548, 13, 482, 8843, 429, 1135, 12, 6430, 15329, 203, 3639, 2583, 12, 69, 4062, 87, 63, 67, 69, 4062, 548, 8009, 8766, 395, 17763, 411, 1234, 18, 1132, 10837, 6029, 279, 10478, 605, 350, 8863, 203, 3639, 2 ]
/** Source code of Opium Protocol Web https://opium.network Telegram https://t.me/opium_network Twitter https://twitter.com/opium_network */ // File: LICENSE /** The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2020 Blockeys BV. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // File: contracts/Lib/LibDerivative.sol pragma solidity 0.5.16; pragma experimental ABIEncoderV2; /// @title Opium.Lib.LibDerivative contract should be inherited by contracts that use Derivative structure and calculate derivativeHash contract LibDerivative { // Opium derivative structure (ticker) definition struct Derivative { // Margin parameter for syntheticId uint256 margin; // Maturity of derivative uint256 endTime; // Additional parameters for syntheticId uint256[] params; // oracleId of derivative address oracleId; // Margin token address of derivative address token; // syntheticId of derivative address syntheticId; } /// @notice Calculates hash of provided Derivative /// @param _derivative Derivative Instance of derivative to hash /// @return derivativeHash bytes32 Derivative hash function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) { derivativeHash = keccak256(abi.encodePacked( _derivative.margin, _derivative.endTime, _derivative.params, _derivative.oracleId, _derivative.token, _derivative.syntheticId )); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol 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. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: erc721o/contracts/Libs/LibPosition.sol pragma solidity ^0.5.4; library LibPosition { function getLongTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "LONG"))); } function getShortTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "SHORT"))); } } // File: contracts/Interface/IDerivativeLogic.sol pragma solidity 0.5.16; /// @title Opium.Interface.IDerivativeLogic contract is an interface that every syntheticId should implement contract IDerivativeLogic is LibDerivative { /// @notice Validates ticker /// @param _derivative Derivative Instance of derivative to validate /// @return Returns boolean whether ticker is valid function validateInput(Derivative memory _derivative) public view returns (bool); /// @notice Calculates margin required for derivative creation /// @param _derivative Derivative Instance of derivative /// @return buyerMargin uint256 Margin needed from buyer (LONG position) /// @return sellerMargin uint256 Margin needed from seller (SHORT position) function getMargin(Derivative memory _derivative) public view returns (uint256 buyerMargin, uint256 sellerMargin); /// @notice Calculates payout for derivative execution /// @param _derivative Derivative Instance of derivative /// @param _result uint256 Data retrieved from oracleId on the maturity /// @return buyerPayout uint256 Payout in ratio for buyer (LONG position holder) /// @return sellerPayout uint256 Payout in ratio for seller (SHORT position holder) function getExecutionPayout(Derivative memory _derivative, uint256 _result) public view returns (uint256 buyerPayout, uint256 sellerPayout); /// @notice Returns syntheticId author address for Opium commissions /// @return authorAddress address The address of syntheticId address function getAuthorAddress() public view returns (address authorAddress); /// @notice Returns syntheticId author commission in base of COMMISSION_BASE /// @return commission uint256 Author commission function getAuthorCommission() public view returns (uint256 commission); /// @notice Returns whether thirdparty could execute on derivative's owner's behalf /// @param _derivativeOwner address Derivative owner address /// @return Returns boolean whether _derivativeOwner allowed third party execution function thirdpartyExecutionAllowed(address _derivativeOwner) public view returns (bool); /// @notice Returns whether syntheticId implements pool logic /// @return Returns whether syntheticId implements pool logic function isPool() public view returns (bool); /// @notice Sets whether thirds parties are allowed or not to execute derivative's on msg.sender's behalf /// @param _allow bool Flag for execution allowance function allowThirdpartyExecution(bool _allow) public; // Event with syntheticId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/Errors/CoreErrors.sol pragma solidity 0.5.16; contract CoreErrors { string constant internal ERROR_CORE_NOT_POOL = "CORE:NOT_POOL"; string constant internal ERROR_CORE_CANT_BE_POOL = "CORE:CANT_BE_POOL"; string constant internal ERROR_CORE_TICKER_WAS_CANCELLED = "CORE:TICKER_WAS_CANCELLED"; string constant internal ERROR_CORE_SYNTHETIC_VALIDATION_ERROR = "CORE:SYNTHETIC_VALIDATION_ERROR"; string constant internal ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE = "CORE:NOT_ENOUGH_TOKEN_ALLOWANCE"; string constant internal ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED = "CORE:EXECUTION_BEFORE_MATURITY_NOT_ALLOWED"; string constant internal ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED = "CORE:SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED"; string constant internal ERROR_CORE_INSUFFICIENT_POOL_BALANCE = "CORE:INSUFFICIENT_POOL_BALANCE"; string constant internal ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID = "CORE:CANT_CANCEL_DUMMY_ORACLE_ID"; string constant internal ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED = "CORE:CANCELLATION_IS_NOT_ALLOWED"; string constant internal ERROR_CORE_UNKNOWN_POSITION_TYPE = "CORE:UNKNOWN_POSITION_TYPE"; } // File: contracts/Errors/RegistryErrors.sol pragma solidity 0.5.16; contract RegistryErrors { string constant internal ERROR_REGISTRY_ONLY_INITIALIZER = "REGISTRY:ONLY_INITIALIZER"; string constant internal ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED = "REGISTRY:ONLY_OPIUM_ADDRESS_ALLOWED"; string constant internal ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS = "REGISTRY:CANT_BE_ZERO_ADDRESS"; string constant internal ERROR_REGISTRY_ALREADY_SET = "REGISTRY:ALREADY_SET"; } // File: contracts/Registry.sol pragma solidity 0.5.16; /// @title Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other contract Registry is RegistryErrors { // Address of Opium.TokenMinter contract address private minter; // Address of Opium.Core contract address private core; // Address of Opium.OracleAggregator contract address private oracleAggregator; // Address of Opium.SyntheticAggregator contract address private syntheticAggregator; // Address of Opium.TokenSpender contract address private tokenSpender; // Address of Opium commission receiver address private opiumAddress; // Address of Opium contract set deployer address public initializer; /// @notice This modifier restricts access to functions, which could be called only by initializer modifier onlyInitializer() { require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER); _; } /// @notice Sets initializer constructor() public { initializer = msg.sender; } // SETTERS /// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once /// @param _minter address Address of Opium.TokenMinter /// @param _core address Address of Opium.Core /// @param _oracleAggregator address Address of Opium.OracleAggregator /// @param _syntheticAggregator address Address of Opium.SyntheticAggregator /// @param _tokenSpender address Address of Opium.TokenSpender /// @param _opiumAddress address Address of Opium commission receiver function init( address _minter, address _core, address _oracleAggregator, address _syntheticAggregator, address _tokenSpender, address _opiumAddress ) external onlyInitializer { require( minter == address(0) && core == address(0) && oracleAggregator == address(0) && syntheticAggregator == address(0) && tokenSpender == address(0) && opiumAddress == address(0), ERROR_REGISTRY_ALREADY_SET ); require( _minter != address(0) && _core != address(0) && _oracleAggregator != address(0) && _syntheticAggregator != address(0) && _tokenSpender != address(0) && _opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS ); minter = _minter; core = _core; oracleAggregator = _oracleAggregator; syntheticAggregator = _syntheticAggregator; tokenSpender = _tokenSpender; opiumAddress = _opiumAddress; } /// @notice Allows opium commission receiver address to change itself /// @param _opiumAddress address New opium commission receiver address function changeOpiumAddress(address _opiumAddress) external { require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED); require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS); opiumAddress = _opiumAddress; } // GETTERS /// @notice Returns address of Opium.TokenMinter /// @param result address Address of Opium.TokenMinter function getMinter() external view returns (address result) { return minter; } /// @notice Returns address of Opium.Core /// @param result address Address of Opium.Core function getCore() external view returns (address result) { return core; } /// @notice Returns address of Opium.OracleAggregator /// @param result address Address of Opium.OracleAggregator function getOracleAggregator() external view returns (address result) { return oracleAggregator; } /// @notice Returns address of Opium.SyntheticAggregator /// @param result address Address of Opium.SyntheticAggregator function getSyntheticAggregator() external view returns (address result) { return syntheticAggregator; } /// @notice Returns address of Opium.TokenSpender /// @param result address Address of Opium.TokenSpender function getTokenSpender() external view returns (address result) { return tokenSpender; } /// @notice Returns address of Opium commission receiver /// @param result address Address of Opium commission receiver function getOpiumAddress() external view returns (address result) { return opiumAddress; } } // File: contracts/Errors/UsingRegistryErrors.sol pragma solidity 0.5.16; contract UsingRegistryErrors { string constant internal ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED = "USING_REGISTRY:ONLY_CORE_ALLOWED"; } // File: contracts/Lib/UsingRegistry.sol pragma solidity 0.5.16; /// @title Opium.Lib.UsingRegistry contract should be inherited by contracts, that are going to use Opium.Registry contract UsingRegistry is UsingRegistryErrors { // Emitted when registry instance is set event RegistrySet(address registry); // Instance of Opium.Registry contract Registry internal registry; /// @notice This modifier restricts access to functions, which could be called only by Opium.Core modifier onlyCore() { require(msg.sender == registry.getCore(), ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED); _; } /// @notice Defines registry instance and emits appropriate event constructor(address _registry) public { registry = Registry(_registry); emit RegistrySet(_registry); } /// @notice Getter for registry variable /// @return address Address of registry set in current contract function getRegistry() external view returns (address) { return address(registry); } } // File: contracts/Lib/LibCommission.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibCommission contract defines constants for Opium commissions contract LibCommission { // Represents 100% base for commissions calculation uint256 constant public COMMISSION_BASE = 10000; // Represents 100% base for Opium commission uint256 constant public OPIUM_COMMISSION_BASE = 10; // Represents which part of `syntheticId` author commissions goes to opium uint256 constant public OPIUM_COMMISSION_PART = 1; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: erc721o/contracts/Libs/UintArray.sol pragma solidity ^0.5.4; library UintArray { function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } function difference(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { uint256 e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } uint256[] memory newUints = new uint256[](count); uint256[] memory newUintsIdxs = new uint256[](count); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsIdxs[j] = i; j++; } } return (newUints, newUintsIdxs); } function intersect(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } uint256[] memory newUints = new uint256[](newLength); uint256[] memory newUintsAIdxs = new uint256[](newLength); uint256[] memory newUintsBIdxs = new uint256[](newLength); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsAIdxs[j] = i; (newUintsBIdxs[j], ) = indexOf(B, A[i]); j++; } } return (newUints, newUintsAIdxs, newUintsBIdxs); } function isUnique(uint256[] memory A) internal pure returns (bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { (uint256 idx, bool isIn) = indexOf(A, A[i]); if (isIn && idx < i) { return false; } } return true; } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.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/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: erc721o/contracts/Interfaces/IERC721O.sol pragma solidity ^0.5.4; contract IERC721O { // Token description function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() public view returns (uint256); function exists(uint256 _tokenId) public view returns (bool); function implementsERC721() public pure returns (bool); function tokenByIndex(uint256 _index) public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri); function getApproved(uint256 _tokenId) public view returns (address); function implementsERC721O() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address _owner); function balanceOf(address owner) public view returns (uint256); function balanceOf(address _owner, uint256 _tokenId) public view returns (uint256); function tokensOwned(address _owner) public view returns (uint256[] memory, uint256[] memory); // Non-Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public; // Non-Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId) public; // Fungible Unsafe Transfer function transfer(address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public; // Fungible Safe Batch Transfer From function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data) public; // Fungible Unsafe Batch Transfer From function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; // Approvals function setApprovalForAll(address _operator, bool _approved) public; function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator); function isApprovedOrOwner(address _spender, address _owner, uint256 _tokenId) public view returns (bool); function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external; // Composable function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function recompose(uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity) public; // Required Events event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts); event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio); } // File: erc721o/contracts/Interfaces/IERC721OReceiver.sol pragma solidity ^0.5.4; /** * @title ERC721O token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721O contracts. */ contract IERC721OReceiver { /** * @dev Magic value to be returned upon successful reception of an amount of ERC721O tokens * ERC721O_RECEIVED = `bytes4(keccak256("onERC721OReceived(address,address,uint256,uint256,bytes)"))` = 0xf891ffe0 * ERC721O_BATCH_RECEIVED = `bytes4(keccak256("onERC721OBatchReceived(address,address,uint256[],uint256[],bytes)"))` = 0xd0e17c0b */ bytes4 constant internal ERC721O_RECEIVED = 0xf891ffe0; bytes4 constant internal ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function onERC721OReceived( address _operator, address _from, uint256 tokenId, uint256 amount, bytes memory data ) public returns(bytes4); function onERC721OBatchReceived( address _operator, address _from, uint256[] memory _types, uint256[] memory _amounts, bytes memory _data ) public returns (bytes4); } // File: erc721o/contracts/Libs/ObjectsLib.sol pragma solidity ^0.5.4; library ObjectLib { // Libraries using SafeMath for uint256; enum Operations { ADD, SUB, REPLACE } // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param _tokenId Object type * @return (Bin number, ID's index within that bin) */ function getTokenBinIndex(uint256 _tokenId) internal pure returns (uint256 bin, uint256 index) { bin = _tokenId * TYPES_BITS_SIZE / 256; index = _tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in _binBalances * @param _binBalances Uint256 containing the balances of objects * @param _index Index of the object in the provided bin * @param _amount Value to update the type balance * @param _operation Which operation to conduct : * Operations.REPLACE : Replace type balance with _amount * Operations.ADD : ADD _amount to type balance * Operations.SUB : Substract _amount from type balance */ function updateTokenBalance( uint256 _binBalances, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinBalance) { uint256 objectBalance; if (_operation == Operations.ADD) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount)); } else if (_operation == Operations.SUB) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount)); } else if (_operation == Operations.REPLACE) { newBinBalance = writeValueInBin(_binBalances, _index, _amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in _binValue at position _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index index at which to retrieve value * @return Value at given _index in _bin */ function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue >> rightShift) & mask; } /** * @dev return the updated _binValue after writing _amount at _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index Index at which to retrieve value * @param _amount Value to store at _index in _bin * @return Value at given _index in _bin */ function writeValueInBin(uint256 _binValue, uint256 _index, uint256 _amount) internal pure returns (uint256) { require(_amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large"); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue & ~(mask << leftShift) ) | (_amount << leftShift); } } // File: erc721o/contracts/ERC721OBase.sol pragma solidity ^0.5.4; contract ERC721OBase is IERC721O, ERC165, IERC721 { // Libraries using ObjectLib for ObjectLib.Operations; using ObjectLib for uint256; // Array with all tokenIds uint256[] internal allTokens; // Packed balances mapping(address => mapping(uint256 => uint256)) internal packedTokenBalance; // Operators mapping(address => mapping(address => bool)) internal operators; // Keeps aprovals for tokens from owner to approved address // tokenApprovals[tokenId][owner] = approved mapping (uint256 => mapping (address => address)) internal tokenApprovals; // Token Id state mapping(uint256 => uint256) internal tokenTypes; uint256 constant internal INVALID = 0; uint256 constant internal POSITION = 1; uint256 constant internal PORTFOLIO = 2; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721O = 0x12345678; // EIP712 constants bytes32 public DOMAIN_SEPARATOR; bytes32 public PERMIT_TYPEHASH; // mapping holds nonces for approval permissions // nonces[holder] => nonce mapping (address => uint) public nonces; modifier isOperatorOrOwner(address _from) { require((msg.sender == _from) || operators[_from][msg.sender], "msg.sender is neither _from nor operator"); _; } constructor() public { _registerInterface(INTERFACE_ID_ERC721O); // Calculate EIP712 constants DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,address verifyingContract)"), keccak256(bytes("ERC721o")), keccak256(bytes("1")), address(this) )); PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); } function implementsERC721O() public pure returns (bool) { return true; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { return tokenTypes[_tokenId] != INVALID; } /** * @dev return the _tokenId type' balance of _address * @param _address Address to query balance of * @param _tokenId type to query balance of * @return Amount of objects of a given type ID */ function balanceOf(address _address, uint256 _tokenId) public view returns (uint256) { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); return packedTokenBalance[_address][bin].getValueInBin(index); } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets Iterate through the list of existing tokens and return the indexes * and balances of the tokens owner by the user * @param _owner The adddress we are checking * @return indexes The tokenIds * @return balances The balances of each token */ function tokensOwned(address _owner) public view returns (uint256[] memory indexes, uint256[] memory balances) { uint256 numTokens = totalSupply(); uint256[] memory tokenIndexes = new uint256[](numTokens); uint256[] memory tempTokens = new uint256[](numTokens); uint256 count; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = allTokens[i]; if (balanceOf(_owner, tokenId) > 0) { tempTokens[count] = balanceOf(_owner, tokenId); tokenIndexes[count] = tokenId; count++; } } // copy over the data to a correct size array uint256[] memory _ownedTokens = new uint256[](count); uint256[] memory _ownedTokensIndexes = new uint256[](count); for (uint256 i = 0; i < count; i++) { _ownedTokens[i] = tempTokens[i]; _ownedTokensIndexes[i] = tokenIndexes[i]; } return (_ownedTokensIndexes, _ownedTokens); } /** * @dev Will set _operator operator status to true or false * @param _operator Address to changes operator status. * @param _approved _operator's new operator status (true or false) */ function setApprovalForAll(address _operator, bool _approved) public { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Approve for all by signature function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external { // Calculate hash bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed )) )); // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly bytes32 r; bytes32 s; uint8 v; bytes memory signature = _signature; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } address recoveredAddress; // If the version is correct return the signer address if (v != 27 && v != 28) { recoveredAddress = address(0); } else { // solium-disable-next-line arg-overflow recoveredAddress = ecrecover(digest, v, r, s); } require(_holder != address(0), "Holder can't be zero address"); require(_holder == recoveredAddress, "Signer address is invalid"); require(_expiry == 0 || now <= _expiry, "Permission expired"); require(_nonce == nonces[_holder]++, "Nonce is invalid"); // Update operator status operators[_holder][_spender] = _allowed; emit ApprovalForAll(_holder, _spender, _allowed); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { require(_to != msg.sender, "Can't approve to yourself"); tokenApprovals[_tokenId][msg.sender] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address) { return tokenApprovals[_tokenId][_tokenOwner]; } /** * @dev Function that verifies whether _operator is an authorized operator of _tokenHolder. * @param _operator The address of the operator to query status of * @param _owner Address of the tokenHolder * @return A uint256 specifying the amount of tokens still available for the spender. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) ); } function _updateTokenBalance( address _from, uint256 _tokenId, uint256 _amount, ObjectLib.Operations op ) internal { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); packedTokenBalance[_from][bin] = packedTokenBalance[_from][bin].updateTokenBalance( index, _amount, op ); } } // File: erc721o/contracts/ERC721OTransferable.sol pragma solidity ^0.5.4; contract ERC721OTransferable is ERC721OBase, ReentrancyGuard { // Libraries using Address for address; // safeTransfer constants bytes4 internal constant ERC721O_RECEIVED = 0xf891ffe0; bytes4 internal constant ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * @param _data Data to pass to onERC721OReceived() function if recipient is contract * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data ) public nonReentrant { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC721OReceiver(_to).onERC721OBatchReceived( msg.sender, _from, _tokenIds, _amounts, _data ); require(retval == ERC721O_BATCH_RECEIVED); } } function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) public { safeBatchTransferFrom(_from, _to, _tokenIds, _amounts, ""); } function transfer(address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(msg.sender, _to, _tokenId, _amount); } function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(_from, _to, _tokenId, _amount); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { safeTransferFrom(_from, _to, _tokenId, _amount, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, _amount); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _amount, _data), "Sent to a contract which is not an ERC721O receiver" ); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function _batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) internal isOperatorOrOwner(_from) { // Requirements require(_tokenIds.length == _amounts.length, "Inconsistent array length between args"); require(_to != address(0), "Invalid to address"); // Number of transfers to execute uint256 nTransfer = _tokenIds.length; // Don't do useless calculations if (_from == _to) { for (uint256 i = 0; i < nTransfer; i++) { emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } return; } for (uint256 i = 0; i < nTransfer; i++) { require(_amounts[i] <= balanceOf(_from, _tokenIds[i]), "Quantity greater than from balance"); _updateTokenBalance(_from, _tokenIds[i], _amounts[i], ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenIds[i], _amounts[i], ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } // Emit batchTransfer event emit BatchTransfer(_from, _to, _tokenIds, _amounts); } function _transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) internal { require(isApprovedOrOwner(msg.sender, _from, _tokenId), "Not approved"); require(_amount <= balanceOf(_from, _tokenId), "Quantity greater than from balance"); require(_to != address(0), "Invalid to address"); _updateTokenBalance(_from, _tokenId, _amount, ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenId, _amount, ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenId); emit TransferWithQuantity(_from, _to, _tokenId, _amount); } function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721OReceiver(_to).onERC721OReceived(msg.sender, _from, _tokenId, _amount, _data); return(retval == ERC721O_RECEIVED); } } // File: erc721o/contracts/ERC721OMintable.sol pragma solidity ^0.5.4; contract ERC721OMintable is ERC721OTransferable { // Libraries using LibPosition for bytes32; // Internal functions function _mint(uint256 _tokenId, address _to, uint256 _supply) internal { // If the token doesn't exist, add it to the tokens array if (!exists(_tokenId)) { tokenTypes[_tokenId] = POSITION; allTokens.push(_tokenId); } _updateTokenBalance(_to, _tokenId, _supply, ObjectLib.Operations.ADD); emit Transfer(address(0), _to, _tokenId); emit TransferWithQuantity(address(0), _to, _tokenId, _supply); } function _burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) internal { uint256 ownerBalance = balanceOf(_tokenOwner, _tokenId); require(ownerBalance >= _quantity, "TOKEN_MINTER:NOT_ENOUGH_POSITIONS"); _updateTokenBalance(_tokenOwner, _tokenId, _quantity, ObjectLib.Operations.SUB); emit Transfer(_tokenOwner, address(0), _tokenId); emit TransferWithQuantity(_tokenOwner, address(0), _tokenId, _quantity); } function _mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { _mintLong(_buyer, _derivativeHash, _quantity); _mintShort(_seller, _derivativeHash, _quantity); } function _mintLong(address _buyer, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 longTokenId = _derivativeHash.getLongTokenId(); _mint(longTokenId, _buyer, _quantity); } function _mintShort(address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 shortTokenId = _derivativeHash.getShortTokenId(); _mint(shortTokenId, _seller, _quantity); } function _registerPortfolio(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio) internal { if (!exists(_portfolioId)) { tokenTypes[_portfolioId] = PORTFOLIO; emit Composition(_portfolioId, _tokenIds, _tokenRatio); } } } // File: erc721o/contracts/ERC721OComposable.sol pragma solidity ^0.5.4; contract ERC721OComposable is ERC721OMintable { // Libraries using UintArray for uint256[]; using SafeMath for uint256; function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); for (uint256 i = 0; i < _tokenIds.length; i++) { _burn(msg.sender, _tokenIds[i], _tokenRatio[i].mul(_quantity)); } uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); _registerPortfolio(portfolioId, _tokenIds, _tokenRatio); _mint(portfolioId, msg.sender, _quantity); } function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); require(portfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); for (uint256 i = 0; i < _tokenIds.length; i++) { _mint(_tokenIds[i], msg.sender, _tokenRatio[i].mul(_quantity)); } } function recompose( uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) public { require(_initialTokenIds.length == _initialTokenRatio.length, "TOKEN_MINTER:INITIAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_finalTokenIds.length == _finalTokenRatio.length, "TOKEN_MINTER:FINAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_finalTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); require(_finalTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 oldPortfolioId = uint256(keccak256(abi.encodePacked( _initialTokenIds, _initialTokenRatio ))); require(oldPortfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); _removedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _addedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _keptIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); uint256 newPortfolioId = uint256(keccak256(abi.encodePacked( _finalTokenIds, _finalTokenRatio ))); _registerPortfolio(newPortfolioId, _finalTokenIds, _finalTokenRatio); _mint(newPortfolioId, msg.sender, _quantity); } function _removedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory removedIds, uint256[] memory removedIdsIdxs) = _initialTokenIds.difference(_finalTokenIds); for (uint256 i = 0; i < removedIds.length; i++) { uint256 index = removedIdsIdxs[i]; _mint(_initialTokenIds[index], msg.sender, _initialTokenRatio[index].mul(_quantity)); } _finalTokenRatio; } function _addedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory addedIds, uint256[] memory addedIdsIdxs) = _finalTokenIds.difference(_initialTokenIds); for (uint256 i = 0; i < addedIds.length; i++) { uint256 index = addedIdsIdxs[i]; _burn(msg.sender, _finalTokenIds[index], _finalTokenRatio[index].mul(_quantity)); } _initialTokenRatio; } function _keptIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory keptIds, uint256[] memory keptInitialIdxs, uint256[] memory keptFinalIdxs) = _initialTokenIds.intersect(_finalTokenIds); for (uint256 i = 0; i < keptIds.length; i++) { uint256 initialIndex = keptInitialIdxs[i]; uint256 finalIndex = keptFinalIdxs[i]; if (_initialTokenRatio[initialIndex] > _finalTokenRatio[finalIndex]) { uint256 diff = _initialTokenRatio[initialIndex] - _finalTokenRatio[finalIndex]; _mint(_initialTokenIds[initialIndex], msg.sender, diff.mul(_quantity)); } else if (_initialTokenRatio[initialIndex] < _finalTokenRatio[finalIndex]) { uint256 diff = _finalTokenRatio[finalIndex] - _initialTokenRatio[initialIndex]; _burn(msg.sender, _initialTokenIds[initialIndex], diff.mul(_quantity)); } } } } // File: erc721o/contracts/Libs/UintsLib.sol pragma solidity ^0.5.4; library UintsLib { function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: erc721o/contracts/ERC721OBackwardCompatible.sol pragma solidity ^0.5.4; contract ERC721OBackwardCompatible is ERC721OComposable { using UintsLib for uint256; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; // Reciever constants bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; // Metadata URI string internal baseTokenURI; constructor(string memory _baseTokenURI) public ERC721OBase() { baseTokenURI = _baseTokenURI; _registerInterface(INTERFACE_ID_ERC721); _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); _registerInterface(INTERFACE_ID_ERC721_METADATA); } // ERC721 compatibility function implementsERC721() public pure returns (bool) { return true; } /** * @dev Gets the owner of a given NFT * @param _tokenId uint256 representing the unique token identifier * @return address the owner of the token */ function ownerOf(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } /** * @dev Gets the number of tokens owned by the address we are checking * @param _owner The adddress we are checking * @return balance The unique amount of tokens owned */ function balanceOf(address _owner) public view returns (uint256 balance) { (, uint256[] memory tokens) = tokensOwned(_owner); return tokens.length; } // ERC721 - Enumerable compatibility /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { (, uint256[] memory tokens) = tokensOwned(_owner); require(_index < tokens.length); return tokens[_index]; } // ERC721 - Metadata compatibility function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri) { require(exists(_tokenId), "Token doesn't exist"); return string(abi.encodePacked( baseTokenURI, _tokenId.uint2str(), ".json" )); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, 1); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Sent to a contract which is not an ERC721 receiver" ); } function transferFrom(address _from, address _to, uint256 _tokenId) public { _transferFrom(_from, _to, _tokenId, 1); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); return (retval == ERC721_RECEIVED); } } // File: contracts/TokenMinter.sol pragma solidity 0.5.16; /// @title Opium.TokenMinter contract implements ERC721O token standard for minting, burning and transferring position tokens contract TokenMinter is ERC721OBackwardCompatible, UsingRegistry { /// @notice Calls constructors of super-contracts /// @param _baseTokenURI string URI for token explorers /// @param _registry address Address of Opium.registry constructor(string memory _baseTokenURI, address _registry) public ERC721OBackwardCompatible(_baseTokenURI) UsingRegistry(_registry) {} /// @notice Mints LONG and SHORT position tokens /// @param _buyer address Address of LONG position receiver /// @param _seller address Address of SHORT position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mint(_buyer, _seller, _derivativeHash, _quantity); } /// @notice Mints only LONG position tokens for "pooled" derivatives /// @param _buyer address Address of LONG position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mintLong(_buyer, _derivativeHash, _quantity); } /// @notice Burns position tokens /// @param _tokenOwner address Address of tokens owner /// @param _tokenId uint256 tokenId of positions to burn /// @param _quantity uint256 Quantity of positions to burn function burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) external onlyCore { _burn(_tokenOwner, _tokenId, _quantity); } /// @notice ERC721 interface compatible function for position token name retrieving /// @return Returns name of token function name() external view returns (string memory) { return "Opium Network Position Token"; } /// @notice ERC721 interface compatible function for position token symbol retrieving /// @return Returns symbol of token function symbol() external view returns (string memory) { return "ONP"; } /// VIEW FUNCTIONS /// @notice Checks whether _spender is approved to spend tokens on _owners behalf or owner itself /// @param _spender address Address of spender /// @param _owner address Address of owner /// @param _tokenId address tokenId of interest /// @return Returns whether _spender is approved to spend tokens function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) || isOpiumSpender(_spender) ); } /// @notice Checks whether _spender is Opium.TokenSpender /// @return Returns whether _spender is Opium.TokenSpender function isOpiumSpender(address _spender) public view returns (bool) { return _spender == registry.getTokenSpender(); } } // File: contracts/Errors/OracleAggregatorErrors.sol pragma solidity 0.5.16; contract OracleAggregatorErrors { string constant internal ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER = "ORACLE_AGGREGATOR:NOT_ENOUGH_ETHER"; string constant internal ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE = "ORACLE_AGGREGATOR:QUERY_WAS_ALREADY_MADE"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST = "ORACLE_AGGREGATOR:DATA_DOESNT_EXIST"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST = "ORACLE_AGGREGATOR:DATA_ALREADY_EXIST"; } // File: contracts/Interface/IOracleId.sol pragma solidity 0.5.16; /// @title Opium.Interface.IOracleId contract is an interface that every oracleId should implement interface IOracleId { /// @notice Requests data from `oracleId` one time /// @param timestamp uint256 Timestamp at which data are needed function fetchData(uint256 timestamp) external payable; /// @notice Requests data from `oracleId` multiple times /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(uint256 timestamp, uint256 period, uint256 times) external payable; /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice() external returns (uint256 fetchPrice); // Event with oracleId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/OracleAggregator.sol pragma solidity 0.5.16; /// @title Opium.OracleAggregator contract requests and caches the data from `oracleId`s and provides them to the Core for positions execution contract OracleAggregator is OracleAggregatorErrors, ReentrancyGuard { using SafeMath for uint256; // Storage for the `oracleId` results // dataCache[oracleId][timestamp] => data mapping (address => mapping(uint256 => uint256)) public dataCache; // Flags whether data were provided // dataExist[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataExist; // Flags whether data were requested // dataRequested[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataRequested; // MODIFIERS /// @notice Checks whether enough ETH were provided withing data request to proceed /// @param oracleId address Address of the `oracleId` smart contract /// @param times uint256 How many times the `oracleId` is being requested modifier enoughEtherProvided(address oracleId, uint256 times) { // Calling Opium.IOracleId function to get the data fetch price per one request uint256 oneTimePrice = calculateFetchPrice(oracleId); // Checking if enough ether was provided for `times` amount of requests require(msg.value >= oneTimePrice.mul(times), ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER); _; } // PUBLIC FUNCTIONS /// @notice Requests data from `oracleId` one time /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed function fetchData(address oracleId, uint256 timestamp) public payable nonReentrant enoughEtherProvided(oracleId, 1) { // Check if was not requested before and mark as requested _registerQuery(oracleId, timestamp); // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).fetchData.value(msg.value)(timestamp); } /// @notice Requests data from `oracleId` multiple times /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(address oracleId, uint256 timestamp, uint256 period, uint256 times) public payable nonReentrant enoughEtherProvided(oracleId, times) { // Check if was not requested before and mark as requested in loop for each timestamp for (uint256 i = 0; i < times; i++) { _registerQuery(oracleId, timestamp + period * i); } // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).recursivelyFetchData.value(msg.value)(timestamp, period, times); } /// @notice Receives and caches data from `msg.sender` /// @param timestamp uint256 Timestamp of data /// @param data uint256 Data itself function __callback(uint256 timestamp, uint256 data) public { // Don't allow to push data twice require(!dataExist[msg.sender][timestamp], ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST); // Saving data dataCache[msg.sender][timestamp] = data; // Flagging that data were received dataExist[msg.sender][timestamp] = true; } /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @param oracleId address Address of the `oracleId` smart contract /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice(address oracleId) public returns(uint256 fetchPrice) { fetchPrice = IOracleId(oracleId).calculateFetchPrice(); } // PRIVATE FUNCTIONS /// @notice Checks if data was not requested and provided before and marks as requested /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are requested function _registerQuery(address oracleId, uint256 timestamp) private { // Check if data was not requested and provided yet require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE); // Mark as requested dataRequested[oracleId][timestamp] = true; } // VIEW FUNCTIONS /// @notice Returns cached data if they exist, or reverts with an error /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @return dataResult uint256 Cached data provided by `oracleId` function getData(address oracleId, uint256 timestamp) public view returns(uint256 dataResult) { // Check if Opium.OracleAggregator has data require(hasData(oracleId, timestamp), ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST); // Return cached data dataResult = dataCache[oracleId][timestamp]; } /// @notice Getter for dataExist mapping /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @param result bool Returns whether data were provided already function hasData(address oracleId, uint256 timestamp) public view returns(bool result) { return dataExist[oracleId][timestamp]; } } // File: contracts/Errors/SyntheticAggregatorErrors.sol pragma solidity 0.5.16; contract SyntheticAggregatorErrors { string constant internal ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH = "SYNTHETIC_AGGREGATOR:DERIVATIVE_HASH_NOT_MATCH"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN = "SYNTHETIC_AGGREGATOR:WRONG_MARGIN"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG = "SYNTHETIC_AGGREGATOR:COMMISSION_TOO_BIG"; } // File: contracts/SyntheticAggregator.sol pragma solidity 0.5.16; /// @notice Opium.SyntheticAggregator contract initialized, identifies and caches syntheticId sensitive data contract SyntheticAggregator is SyntheticAggregatorErrors, LibDerivative, LibCommission, ReentrancyGuard { // Emitted when new ticker is initialized event Create(Derivative derivative, bytes32 derivativeHash); // Enum for types of syntheticId // Invalid - syntheticId is not initialized yet // NotPool - syntheticId with p2p logic // Pool - syntheticId with pooled logic enum SyntheticTypes { Invalid, NotPool, Pool } // Cache of buyer margin by ticker // buyerMarginByHash[derivativeHash] = buyerMargin mapping (bytes32 => uint256) public buyerMarginByHash; // Cache of seller margin by ticker // sellerMarginByHash[derivativeHash] = sellerMargin mapping (bytes32 => uint256) public sellerMarginByHash; // Cache of type by ticker // typeByHash[derivativeHash] = type mapping (bytes32 => SyntheticTypes) public typeByHash; // Cache of commission by ticker // commissionByHash[derivativeHash] = commission mapping (bytes32 => uint256) public commissionByHash; // Cache of author addresses by ticker // authorAddressByHash[derivativeHash] = authorAddress mapping (bytes32 => address) public authorAddressByHash; // PUBLIC FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return commission uint256 Synthetic author commission function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); commission = commissionByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author address from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return authorAddress address Synthetic author address function getAuthorAddress(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (address authorAddress) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); authorAddress = authorAddressByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns buyer and seller margin from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return buyerMargin uint256 Margin of buyer /// @return sellerMargin uint256 Margin of seller function getMargin(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 buyerMargin, uint256 sellerMargin) { // If it's a pool, just return margin from syntheticId contract if (_isPool(_derivativeHash, _derivative)) { return IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); } // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); // Check if margins for _derivativeHash were already cached buyerMargin = buyerMarginByHash[_derivativeHash]; sellerMargin = sellerMarginByHash[_derivativeHash]; } /// @notice Checks whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function isPool(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (bool result) { result = _isPool(_derivativeHash, _derivative); } // PRIVATE FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function _isPool(bytes32 _derivativeHash, Derivative memory _derivative) private returns (bool result) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); result = typeByHash[_derivativeHash] == SyntheticTypes.Pool; } /// @notice Initializes ticker: caches syntheticId type, margin, author address and commission /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself function _initDerivative(bytes32 _derivativeHash, Derivative memory _derivative) private { // Check if type for _derivativeHash was already cached SyntheticTypes syntheticType = typeByHash[_derivativeHash]; // Type could not be Invalid, thus this condition says us that type was not cached before if (syntheticType != SyntheticTypes.Invalid) { return; } // For security reasons we calculate hash of provided _derivative bytes32 derivativeHash = getDerivativeHash(_derivative); require(derivativeHash == _derivativeHash, ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH); // POOL // Get isPool from SyntheticId bool result = IDerivativeLogic(_derivative.syntheticId).isPool(); // Cache type returned from synthetic typeByHash[derivativeHash] = result ? SyntheticTypes.Pool : SyntheticTypes.NotPool; // MARGIN // Get margin from SyntheticId (uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); // We are not allowing both margins to be equal to 0 require(buyerMargin != 0 || sellerMargin != 0, ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN); // Cache margins returned from synthetic buyerMarginByHash[derivativeHash] = buyerMargin; sellerMarginByHash[derivativeHash] = sellerMargin; // AUTHOR ADDRESS // Cache author address returned from synthetic authorAddressByHash[derivativeHash] = IDerivativeLogic(_derivative.syntheticId).getAuthorAddress(); // AUTHOR COMMISSION // Get commission from syntheticId uint256 commission = IDerivativeLogic(_derivative.syntheticId).getAuthorCommission(); // Check if commission is not set > 100% require(commission <= COMMISSION_BASE, ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG); // Cache commission commissionByHash[derivativeHash] = commission; // If we are here, this basically means this ticker was not used before, so we emit an event for Dapps developers about new ticker (derivative) and it's hash emit Create(_derivative, derivativeHash); } } // File: contracts/Lib/Whitelisted.sol pragma solidity 0.5.16; /// @title Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses contract Whitelisted { // Whitelist array address[] internal whitelist; /// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses modifier onlyWhitelisted() { // Allowance flag bool allowed = false; // Going through whitelisted addresses array uint256 whitelistLength = whitelist.length; for (uint256 i = 0; i < whitelistLength; i++) { // If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop if (whitelist[i] == msg.sender) { allowed = true; break; } } // Check if flag was raised require(allowed, "Only whitelisted allowed"); _; } /// @notice Getter for whitelisted addresses array /// @return Array of whitelisted addresses function getWhitelist() public view returns (address[] memory) { return whitelist; } } // File: contracts/Lib/WhitelistedWithGovernance.sol pragma solidity 0.5.16; /// @title Opium.Lib.WhitelistedWithGovernance contract implements Opium.Lib.Whitelisted and adds governance for whitelist controlling contract WhitelistedWithGovernance is Whitelisted { // Emitted when new governor is set event GovernorSet(address governor); // Emitted when new whitelist is proposed event Proposed(address[] whitelist); // Emitted when proposed whitelist is committed (set) event Committed(address[] whitelist); // Proposal life timelock interval uint256 public timeLockInterval; // Governor address address public governor; // Timestamp of last proposal uint256 public proposalTime; // Proposed whitelist address[] public proposedWhitelist; /// @notice This modifier restricts access to functions, which could be called only by governor modifier onlyGovernor() { require(msg.sender == governor, "Only governor allowed"); _; } /// @notice Contract constructor /// @param _timeLockInterval uint256 Initial value for timelock interval /// @param _governor address Initial value for governor constructor(uint256 _timeLockInterval, address _governor) public { timeLockInterval = _timeLockInterval; governor = _governor; emit GovernorSet(governor); } /// @notice Calling this function governor could propose new whitelist addresses array. Also it allows to initialize first whitelist if it was not initialized yet. function proposeWhitelist(address[] memory _whitelist) public onlyGovernor { // Restrict empty proposals require(_whitelist.length != 0, "Can't be empty"); // Consider empty whitelist as not initialized, as proposing of empty whitelists is not allowed // If whitelist has never been initialized, we set whitelist right away without proposal if (whitelist.length == 0) { whitelist = _whitelist; emit Committed(_whitelist); // Otherwise save current time as timestamp of proposal, save proposed whitelist and emit event } else { proposalTime = now; proposedWhitelist = _whitelist; emit Proposed(_whitelist); } } /// @notice Calling this function governor commits proposed whitelist if timelock interval of proposal was passed function commitWhitelist() public onlyGovernor { // Check if proposal was made require(proposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((proposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new whitelist and emit event whitelist = proposedWhitelist; emit Committed(whitelist); // Reset proposal time lock proposalTime = 0; } /// @notice This function allows governor to transfer governance to a new governor and emits event /// @param _governor address Address of new governor function setGovernor(address _governor) public onlyGovernor { require(_governor != address(0), "Can't set zero address"); governor = _governor; emit GovernorSet(governor); } } // File: contracts/Lib/WhitelistedWithGovernanceAndChangableTimelock.sol pragma solidity 0.5.16; /// @notice Opium.Lib.WhitelistedWithGovernanceAndChangableTimelock contract implements Opium.Lib.WhitelistedWithGovernance and adds possibility for governor to change timelock interval within timelock interval contract WhitelistedWithGovernanceAndChangableTimelock is WhitelistedWithGovernance { // Emitted when new timelock is proposed event Proposed(uint256 timelock); // Emitted when new timelock is committed (set) event Committed(uint256 timelock); // Timestamp of last timelock proposal uint256 public timeLockProposalTime; // Proposed timelock uint256 public proposedTimeLock; /// @notice Calling this function governor could propose new timelock /// @param _timelock uint256 New timelock value function proposeTimelock(uint256 _timelock) public onlyGovernor { timeLockProposalTime = now; proposedTimeLock = _timelock; emit Proposed(_timelock); } /// @notice Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed function commitTimelock() public onlyGovernor { // Check if proposal was made require(timeLockProposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new timelock and emit event timeLockInterval = proposedTimeLock; emit Committed(proposedTimeLock); // Reset timelock time lock timeLockProposalTime = 0; } } // File: contracts/TokenSpender.sol pragma solidity 0.5.16; /// @title Opium.TokenSpender contract holds users ERC20 approvals and allows whitelisted contracts to use tokens contract TokenSpender is WhitelistedWithGovernanceAndChangableTimelock { using SafeERC20 for IERC20; // Initial timelock period uint256 public constant WHITELIST_TIMELOCK = 1 hours; /// @notice Calls constructors of super-contracts /// @param _governor address Address of governor, who is allowed to adjust whitelist constructor(address _governor) public WhitelistedWithGovernance(WHITELIST_TIMELOCK, _governor) {} /// @notice Using this function whitelisted contracts could call ERC20 transfers /// @param token IERC20 Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param amount uint256 Amount of tokens to be transferred function claimTokens(IERC20 token, address from, address to, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, amount); } /// @notice Using this function whitelisted contracts could call ERC721O transfers /// @param token IERC721O Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param tokenId uint256 Token ID to be transferred /// @param amount uint256 Amount of tokens to be transferred function claimPositions(IERC721O token, address from, address to, uint256 tokenId, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, tokenId, amount); } } // File: contracts/Core.sol pragma solidity 0.5.16; /// @title Opium.Core contract creates positions, holds and distributes margin at the maturity contract Core is LibDerivative, LibCommission, UsingRegistry, CoreErrors, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emitted when Core creates new position event Created(address buyer, address seller, bytes32 derivativeHash, uint256 quantity); // Emitted when Core executes positions event Executed(address tokenOwner, uint256 tokenId, uint256 quantity); // Emitted when Core cancels ticker for the first time event Canceled(bytes32 derivativeHash); // Period of time after which ticker could be canceled if no data was provided to the `oracleId` uint256 public constant NO_DATA_CANCELLATION_PERIOD = 2 weeks; // Vaults for pools // This mapping holds balances of pooled positions // poolVaults[syntheticAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public poolVaults; // Vaults for fees // This mapping holds balances of fee recipients // feesVaults[feeRecipientAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public feesVaults; // Hashes of cancelled tickers mapping (bytes32 => bool) public cancelled; /// @notice Calls Core.Lib.UsingRegistry constructor constructor(address _registry) public UsingRegistry(_registry) {} // PUBLIC FUNCTIONS /// @notice This function allows fee recipients to withdraw their fees /// @param _tokenAddress address Address of an ERC20 token to withdraw function withdrawFee(address _tokenAddress) public nonReentrant { uint256 balance = feesVaults[msg.sender][_tokenAddress]; feesVaults[msg.sender][_tokenAddress] = 0; IERC20(_tokenAddress).safeTransfer(msg.sender, balance); } /// @notice Creates derivative contracts (positions) /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of derivatives to be created /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address - if seller is set to `address(0)`, consider as pooled position function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant { if (_addresses[1] == address(0)) { _createPooled(_derivative, _quantity, _addresses[0]); } else { _create(_derivative, _quantity, _addresses); } } /// @notice Executes several positions of `msg.sender` with same `tokenId` /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(msg.sender, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `_tokenOwner` with same `tokenId` /// @param _tokenOwner address Address of the owner of positions /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(address _tokenOwner, uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(_tokenOwner, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `msg.sender` with different `tokenId`s /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(msg.sender, _tokenIds, _quantities, _derivatives); } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(_tokenOwner, _tokenIds, _quantities, _derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenId uint256 `tokenId` of positions that needs to be canceled /// @param _quantity uint256 Quantity of positions to cancel /// @param _derivative Derivative Derivative definition function cancel(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _cancel(tokenIds, quantities, derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _cancel(_tokenIds, _quantities, _derivatives); } // PRIVATE FUNCTIONS struct CreatePooledLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates pooled positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _address address Address of position receiver function _createPooled(Derivative memory _derivative, uint256 _quantity, address _address) private { // Local variables CreatePooledLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is a pool require(vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_NOT_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); // Get cached margin required according to logic from Opium.SyntheticAggregator (uint256 margin, ) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: margin * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margin.mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margin.mul(_quantity)); // Since it's a pooled position, we add transferred margin to pool balance poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].add(margin.mul(_quantity)); // Mint LONG position tokens vars.tokenMinter.mint(_address, derivativeHash, _quantity); emit Created(_address, address(0), derivativeHash, _quantity); } struct CreateLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates p2p positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address function _create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) private { // Local variables CreateLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is not a pool require(!vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_CANT_BE_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: (margins[0] + margins[1]) * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margins[0].add(margins[1]).mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margins[0].add(margins[1]).mul(_quantity)); // Mint LONG and SHORT positions tokens vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity); emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity); } struct ExecuteAndCancelLocalVars { TokenMinter tokenMinter; OracleAggregator oracleAggregator; SyntheticAggregator syntheticAggregator; } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Check if execution is performed after endTime require(now > _derivatives[i].endTime, ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED); // Checking whether execution is performed by `_tokenOwner` or `_tokenOwner` allowed third party executions on it's behalf require( _tokenOwner == msg.sender || IDerivativeLogic(_derivatives[i].syntheticId).thirdpartyExecutionAllowed(_tokenOwner), ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED ); // Returns payout for all positions uint256 payout = _getPayout(_derivatives[i], _tokenIds[i], _quantities[i], vars); // Transfer payout if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(_tokenOwner, payout); } // Burn executed position tokens vars.tokenMinter.burn(_tokenOwner, _tokenIds[i], _quantities[i]); emit Executed(_tokenOwner, _tokenIds[i], _quantities[i]); } } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Don't allow to cancel tickers with "dummy" oracleIds require(_derivatives[i].oracleId != address(0), ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID); // Check if cancellation is called after `NO_DATA_CANCELLATION_PERIOD` and `oracleId` didn't provided data require( _derivatives[i].endTime + NO_DATA_CANCELLATION_PERIOD <= now && !vars.oracleAggregator.hasData(_derivatives[i].oracleId, _derivatives[i].endTime), ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED ); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivatives[i]); // Emit `Canceled` event only once and mark ticker as canceled if (!cancelled[derivativeHash]) { cancelled[derivativeHash] = true; emit Canceled(derivativeHash); } uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivatives[i]); uint256 payout; // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenIds[i]) { // Set payout to buyerPayout payout = margins[0]; // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenIds[i]) { // Set payout to sellerPayout payout = margins[1]; } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } // Transfer payout * _quantities[i] if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(msg.sender, payout.mul(_quantities[i])); } // Burn canceled position tokens vars.tokenMinter.burn(msg.sender, _tokenIds[i], _quantities[i]); } } /// @notice Calculates payout for position and gets fees /// @param _derivative Derivative Derivative definition /// @param _tokenId uint256 `tokenId` of positions /// @param _quantity uint256 Quantity of positions /// @param _vars ExecuteAndCancelLocalVars Helping local variables /// @return payout uint256 Payout for all tokens function _getPayout(Derivative memory _derivative, uint256 _tokenId, uint256 _quantity, ExecuteAndCancelLocalVars memory _vars) private returns (uint256 payout) { // Trying to getData from Opium.OracleAggregator, could be reverted // Opium allows to use "dummy" oracleIds, in this case data is set to `0` uint256 data; if (_derivative.oracleId != address(0)) { data = _vars.oracleAggregator.getData(_derivative.oracleId, _derivative.endTime); } else { data = 0; } uint256[2] memory payoutRatio; // Get payout ratio from Derivative logic // payoutRatio[0] - buyerPayout // payoutRatio[1] - sellerPayout (payoutRatio[0], payoutRatio[1]) = IDerivativeLogic(_derivative.syntheticId).getExecutionPayout(_derivative, data); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); uint256[2] memory margins; // Get cached total margin required from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = _vars.syntheticAggregator.getMargin(derivativeHash, _derivative); uint256[2] memory payouts; // Calculate payouts from ratio // payouts[0] -> buyerPayout = (buyerMargin + sellerMargin) * buyerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) // payouts[1] -> sellerPayout = (buyerMargin + sellerMargin) * sellerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) payouts[0] = margins[0].add(margins[1]).mul(payoutRatio[0]).div(payoutRatio[0].add(payoutRatio[1])); payouts[1] = margins[0].add(margins[1]).mul(payoutRatio[1]).div(payoutRatio[0].add(payoutRatio[1])); // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenId) { // Check if it's a pooled position if (_vars.syntheticAggregator.isPool(derivativeHash, _derivative)) { // Pooled position payoutRatio is considered as full payout, not as payoutRatio payout = payoutRatio[0]; // Multiply payout by quantity payout = payout.mul(_quantity); // Check sufficiency of syntheticId balance in poolVaults require( poolVaults[_derivative.syntheticId][_derivative.token] >= payout , ERROR_CORE_INSUFFICIENT_POOL_BALANCE ); // Subtract paid out margin from poolVault poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].sub(payout); } else { // Set payout to buyerPayout payout = payouts[0]; // Multiply payout by quantity payout = payout.mul(_quantity); } // Take fees only from profit makers // Check: payout > buyerMargin * quantity if (payout > margins[0].mul(_quantity)) { // Get Opium and `syntheticId` author fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[0].mul(_quantity))); } // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenId) { // Set payout to sellerPayout payout = payouts[1]; // Multiply payout by quantity payout = payout.mul(_quantity); // Take fees only from profit makers // Check: payout > sellerMargin * quantity if (payout > margins[1].mul(_quantity)) { // Get Opium fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[1].mul(_quantity))); } } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } } /// @notice Calculates `syntheticId` author and opium fees from profit makers /// @param _syntheticAggregator SyntheticAggregator Instance of Opium.SyntheticAggregator /// @param _derivativeHash bytes32 Derivative hash /// @param _derivative Derivative Derivative definition /// @param _profit uint256 payout of one position /// @return fee uint256 Opium and `syntheticId` author fee function _getFees(SyntheticAggregator _syntheticAggregator, bytes32 _derivativeHash, Derivative memory _derivative, uint256 _profit) private returns (uint256 fee) { // Get cached `syntheticId` author address from Opium.SyntheticAggregator address authorAddress = _syntheticAggregator.getAuthorAddress(_derivativeHash, _derivative); // Get cached `syntheticId` fee percentage from Opium.SyntheticAggregator uint256 commission = _syntheticAggregator.getAuthorCommission(_derivativeHash, _derivative); // Calculate fee // fee = profit * commission / COMMISSION_BASE fee = _profit.mul(commission).div(COMMISSION_BASE); // If commission is zero, finish if (fee == 0) { return 0; } // Calculate opium fee // opiumFee = fee * OPIUM_COMMISSION_PART / OPIUM_COMMISSION_BASE uint256 opiumFee = fee.mul(OPIUM_COMMISSION_PART).div(OPIUM_COMMISSION_BASE); // Calculate author fee // authorFee = fee - opiumFee uint256 authorFee = fee.sub(opiumFee); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Update feeVault for Opium team // feesVault[opium][token] += opiumFee feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee); // Update feeVault for `syntheticId` author // feeVault[author][token] += authorFee feesVaults[authorAddress][_derivative.token] = feesVaults[authorAddress][_derivative.token].add(authorFee); } } // File: contracts/Errors/MatchingErrors.sol pragma solidity 0.5.16; contract MatchingErrors { string constant internal ERROR_MATCH_CANCELLATION_NOT_ALLOWED = "MATCH:CANCELLATION_NOT_ALLOWED"; string constant internal ERROR_MATCH_ALREADY_CANCELED = "MATCH:ALREADY_CANCELED"; string constant internal ERROR_MATCH_ORDER_WAS_CANCELED = "MATCH:ORDER_WAS_CANCELED"; string constant internal ERROR_MATCH_TAKER_ADDRESS_WRONG = "MATCH:TAKER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_ORDER_IS_EXPIRED = "MATCH:ORDER_IS_EXPIRED"; string constant internal ERROR_MATCH_SENDER_ADDRESS_WRONG = "MATCH:SENDER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_SIGNATURE_NOT_VERIFIED = "MATCH:SIGNATURE_NOT_VERIFIED"; string constant internal ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES = "MATCH:NOT_ENOUGH_ALLOWED_FEES"; } // File: contracts/Lib/LibEIP712.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibEIP712 contract implements the domain of EIP712 for meta transactions contract LibEIP712 { // EIP712Domain structure // name - protocol name // version - protocol version // verifyingContract - signed message verifying contract struct EIP712Domain { string name; string version; address verifyingContract; } // Calculate typehash of ERC712Domain bytes32 constant internal EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // solhint-disable-next-line var-name-mixedcase bytes32 internal DOMAIN_SEPARATOR; // Calculate domain separator at creation constructor () public { DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256("Opium Network"), keccak256("1"), address(this) )); } /// @notice Hashes EIP712Message /// @param hashStruct bytes32 Hash of structured message /// @return result bytes32 Hash of EIP712Message function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 domainSeparator = DOMAIN_SEPARATOR; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // File: contracts/Matching/SwaprateMatch/LibSwaprateOrder.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch contract LibSwaprateOrder is LibEIP712 { /** Structure of order Description should be considered from the order signer (maker) perspective syntheticId - address of derivative syntheticId oracleId - address of derivative oracleId token - address of derivative margin token makerMarginAddress - address of token that maker is willing to pay with takerMarginAddress - address of token that maker is willing to receive makerAddress - address of maker takerAddress - address of counterparty (taker). If zero address, then taker could be anyone senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle relayerAddress - address of the relayer fee recipient affiliateAddress - address of the affiliate fee recipient feeTokenAddress - address of token which is used for fees endTime - timestamp of derivative maturity quantity - quantity of positions maker wants to receive partialFill - whether maker allows partial fill of it's order param0...param9 - additional params to pass it to syntheticId relayerFee - amount of fee in feeToken that should be paid to relayer affiliateFee - amount of fee in feeToken that should be paid to affiliate nonce - unique order ID signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes */ struct SwaprateOrder { address syntheticId; address oracleId; address token; address makerAddress; address takerAddress; address senderAddress; address relayerAddress; address affiliateAddress; address feeTokenAddress; uint256 endTime; uint256 quantity; uint256 partialFill; uint256 param0; uint256 param1; uint256 param2; uint256 param3; uint256 param4; uint256 param5; uint256 param6; uint256 param7; uint256 param8; uint256 param9; uint256 relayerFee; uint256 affiliateFee; uint256 nonce; // Not used in hash bytes signature; } // Calculate typehash of Order bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "address syntheticId,", "address oracleId,", "address token,", "address makerAddress,", "address takerAddress,", "address senderAddress,", "address relayerAddress,", "address affiliateAddress,", "address feeTokenAddress,", "uint256 endTime,", "uint256 quantity,", "uint256 partialFill,", "uint256 param0,", "uint256 param1,", "uint256 param2,", "uint256 param3,", "uint256 param4,", "uint256 param5,", "uint256 param6,", "uint256 param7,", "uint256 param8,", "uint256 param9,", "uint256 relayerFee,", "uint256 affiliateFee,", "uint256 nonce", ")" )); /// @notice Hashes the order /// @param _order SwaprateOrder Order to hash /// @return hash bytes32 Order hash function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) { hash = keccak256( abi.encodePacked( abi.encodePacked( EIP712_ORDER_TYPEHASH, uint256(_order.syntheticId), uint256(_order.oracleId), uint256(_order.token), uint256(_order.makerAddress), uint256(_order.takerAddress), uint256(_order.senderAddress), uint256(_order.relayerAddress), uint256(_order.affiliateAddress), uint256(_order.feeTokenAddress) ), abi.encodePacked( _order.endTime, _order.quantity, _order.partialFill ), abi.encodePacked( _order.param0, _order.param1, _order.param2, _order.param3, _order.param4 ), abi.encodePacked( _order.param5, _order.param6, _order.param7, _order.param8, _order.param9 ), abi.encodePacked( _order.relayerFee, _order.affiliateFee, _order.nonce ) ) ); } /// @notice Verifies order signature /// @param _hash bytes32 Hash of the order /// @param _signature bytes Signature of the order /// @param _address address Address of the order signer /// @return bool Returns whether `_signature` is valid and was created by `_address` function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) { require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH"); bytes32 digest = hashEIP712Message(_hash); address recovered = retrieveAddress(digest, _signature); return _address == recovered; } /// @notice Helping function to recover signer address /// @param _hash bytes32 Hash for signature /// @param _signature bytes Signature /// @return address Returns address of signature creator function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } } // File: contracts/Matching/SwaprateMatch/SwaprateMatchBase.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatchBase contract implements logic for order validation and cancelation contract SwaprateMatchBase is MatchingErrors, LibSwaprateOrder, UsingRegistry, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emmitted when order was canceled event Canceled(bytes32 orderHash); // Canceled orders // This mapping holds hashes of canceled orders // canceled[orderHash] => canceled mapping (bytes32 => bool) public canceled; // Verified orders // This mapping holds hashes of verified orders to verify only once // verified[orderHash] => verified mapping (bytes32 => bool) public verified; // Vaults for fees // This mapping holds balances of relayers and affiliates fees to withdraw // balances[feeRecipientAddress][tokenAddress] => balances mapping (address => mapping (address => uint256)) public balances; // Keeps whether fee was already taken mapping (bytes32 => bool) public feeTaken; /// @notice Calling this function maker of the order could cancel it on-chain /// @param _order SwaprateOrder function cancel(SwaprateOrder memory _order) public { require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED); bytes32 orderHash = hashOrder(_order); require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED); canceled[orderHash] = true; emit Canceled(orderHash); } /// @notice Function to withdraw fees from orders for relayer and affiliates /// @param _token IERC20 Instance of token to withdraw function withdraw(IERC20 _token) public nonReentrant { uint256 balance = balances[msg.sender][address(_token)]; balances[msg.sender][address(_token)] = 0; _token.safeTransfer(msg.sender, balance); } /// @notice This function checks whether order was canceled /// @param _hash bytes32 Hash of the order function validateNotCanceled(bytes32 _hash) internal view { require(!canceled[_hash], ERROR_MATCH_ORDER_WAS_CANCELED); } /// @notice This function validates takerAddress of _leftOrder. It should match either with _rightOrder.makerAddress or be set to zero address /// @param _leftOrder SwaprateOrder Left order /// @param _rightOrder SwaprateOrder Right order function validateTakerAddress(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder) pure internal { require( _leftOrder.takerAddress == address(0) || _leftOrder.takerAddress == _rightOrder.makerAddress, ERROR_MATCH_TAKER_ADDRESS_WRONG ); } /// @notice This function validates whether sender address equals to `msg.sender` or set to zero address /// @param _order SwaprateOrder function validateSenderAddress(SwaprateOrder memory _order) internal view { require( _order.senderAddress == address(0) || _order.senderAddress == msg.sender, ERROR_MATCH_SENDER_ADDRESS_WRONG ); } /// @notice This function validates order signature if not validated before /// @param orderHash bytes32 Hash of the order /// @param _order SwaprateOrder function validateSignature(bytes32 orderHash, SwaprateOrder memory _order) internal { if (verified[orderHash]) { return; } bool result = verifySignature(orderHash, _order.signature, _order.makerAddress); require(result, ERROR_MATCH_SIGNATURE_NOT_VERIFIED); verified[orderHash] = true; } /// @notice This function is responsible for taking relayer and affiliate fees, if they were not taken already /// @param _orderHash bytes32 Hash of the order /// @param _order Order Order itself function takeFees(bytes32 _orderHash, SwaprateOrder memory _order) internal { // Check if fee was already taken if (feeTaken[_orderHash]) { return; } // Check if feeTokenAddress is not set to zero address if (_order.feeTokenAddress == address(0)) { return; } // Calculate total amount of fees needs to be transfered uint256 fees = _order.relayerFee.add(_order.affiliateFee); // If total amount of fees is non-zero if (fees == 0) { return; } // Create instance of fee token IERC20 feeToken = IERC20(_order.feeTokenAddress); // Create instance of TokenSpender TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Check if user has enough token approval to pay the fees require(feeToken.allowance(_order.makerAddress, address(tokenSpender)) >= fees, ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES); // Transfer fee tokenSpender.claimTokens(feeToken, _order.makerAddress, address(this), fees); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Add commission to relayer balance, or to opium balance if relayer is not set if (_order.relayerAddress != address(0)) { balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee); } // Add commission to affiliate balance, or to opium balance if affiliate is not set if (_order.affiliateAddress != address(0)) { balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee); } // Mark the fee of token as taken feeTaken[_orderHash] = true; } /// @notice Helper to get minimal of two integers /// @param _a uint256 First integer /// @param _b uint256 Second integer /// @return uint256 Minimal integer function min(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: contracts/Matching/SwaprateMatch/SwaprateMatch.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch contract implements create() function to settle a pair of orders and create derivatives for order makers contract SwaprateMatch is SwaprateMatchBase, LibDerivative { // Orders filled quantity // This mapping holds orders filled quantity // filled[orderHash] => filled mapping (bytes32 => uint256) public filled; /// @notice Calls constructors of super-contracts /// @param _registry address Address of Opium.registry constructor (address _registry) public UsingRegistry(_registry) {} /// @notice This function receives left and right orders, derivative related to it /// @param _leftOrder Order /// @param _rightOrder Order /// @param _derivative Derivative Data of derivative for validation and calculation purposes function create(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) public nonReentrant { // New deals must not offer tokenIds require( _leftOrder.syntheticId == _rightOrder.syntheticId, "MATCH:NOT_CREATION" ); // Check if it's not pool require(!IDerivativeLogic(_derivative.syntheticId).isPool(), "MATCH:CANT_BE_POOL"); // Validate taker if set validateTakerAddress(_leftOrder, _rightOrder); validateTakerAddress(_rightOrder, _leftOrder); // Validate sender if set validateSenderAddress(_leftOrder); validateSenderAddress(_rightOrder); // Validate if was canceled // orderHashes[0] - leftOrderHash // orderHashes[1] - rightOrderHash bytes32[2] memory orderHashes; orderHashes[0] = hashOrder(_leftOrder); validateNotCanceled(orderHashes[0]); validateSignature(orderHashes[0], _leftOrder); orderHashes[1] = hashOrder(_rightOrder); validateNotCanceled(orderHashes[1]); validateSignature(orderHashes[1], _rightOrder); // Calculate derivative hash and get margin // margins[0] - leftMargin // margins[1] - rightMargin (uint256[2] memory margins, ) = _calculateDerivativeAndGetMargin(_derivative); // Calculate and validate availabilities of orders and fill them uint256 fillable = _checkFillability(orderHashes[0], _leftOrder, orderHashes[1], _rightOrder); // Validate derivative parameters with orders _verifyDerivative(_leftOrder, _rightOrder, _derivative); // Take fees takeFees(orderHashes[0], _leftOrder); takeFees(orderHashes[1], _rightOrder); // Send margin to Core _distributeFunds(_leftOrder, _rightOrder, _derivative, margins, fillable); // Settle contracts Core(registry.getCore()).create(_derivative, fillable, [_leftOrder.makerAddress, _rightOrder.makerAddress]); } // PRIVATE FUNCTIONS /// @notice Calculates derivative hash and gets margin /// @param _derivative Derivative /// @return margins uint256[2] left and right margin /// @return derivativeHash bytes32 Hash of the derivative function _calculateDerivativeAndGetMargin(Derivative memory _derivative) private returns (uint256[2] memory margins, bytes32 derivativeHash) { // Calculate derivative related data for validation derivativeHash = getDerivativeHash(_derivative); // Get cached total margin required according to logic // margins[0] - leftMargin // margins[1] - rightMargin (margins[0], margins[1]) = SyntheticAggregator(registry.getSyntheticAggregator()).getMargin(derivativeHash, _derivative); } /// @notice Calculate and validate availabilities of orders and fill them /// @param _leftOrderHash bytes32 /// @param _leftOrder SwaprateOrder /// @param _rightOrderHash bytes32 /// @param _rightOrder SwaprateOrder /// @return fillable uint256 function _checkFillability(bytes32 _leftOrderHash, SwaprateOrder memory _leftOrder, bytes32 _rightOrderHash, SwaprateOrder memory _rightOrder) private returns (uint256 fillable) { // Calculate availabilities of orders uint256 leftAvailable = _leftOrder.quantity.sub(filled[_leftOrderHash]); uint256 rightAvailable = _rightOrder.quantity.sub(filled[_rightOrderHash]); require(leftAvailable != 0 && rightAvailable !=0, "MATCH:NO_AVAILABLE"); // We could only fill minimum available of both counterparties fillable = min(leftAvailable, rightAvailable); // Check fillable with order conditions about partial fill requirements if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 0) { require(_leftOrder.quantity == _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 1) { require(_leftOrder.quantity <= rightAvailable, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 1 && _rightOrder.partialFill == 0) { require(leftAvailable >= _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } // Update filled filled[_leftOrderHash] = filled[_leftOrderHash].add(fillable); filled[_rightOrderHash] = filled[_rightOrderHash].add(fillable); } /// @notice Validate derivative parameters with orders /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative function _verifyDerivative(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) private pure { string memory orderError = "MATCH:DERIVATIVE_PARAM_IS_WRONG"; // Validate derivative endTime require( _derivative.endTime == _leftOrder.endTime && _derivative.endTime == _rightOrder.endTime, orderError ); // Validate derivative syntheticId require( _derivative.syntheticId == _leftOrder.syntheticId && _derivative.syntheticId == _rightOrder.syntheticId, orderError ); // Validate derivative oracleId require( _derivative.oracleId == _leftOrder.oracleId && _derivative.oracleId == _rightOrder.oracleId, orderError ); // Validate derivative token require( _derivative.token == _leftOrder.token && _derivative.token == _rightOrder.token, orderError ); // Validate derivative params require(_derivative.params.length >= 20, "MATCH:DERIVATIVE_PARAMS_LENGTH_IS_WRONG"); // Validate left order params require(_leftOrder.param0 == _derivative.params[0], orderError); require(_leftOrder.param1 == _derivative.params[1], orderError); require(_leftOrder.param2 == _derivative.params[2], orderError); require(_leftOrder.param3 == _derivative.params[3], orderError); require(_leftOrder.param4 == _derivative.params[4], orderError); require(_leftOrder.param5 == _derivative.params[5], orderError); require(_leftOrder.param6 == _derivative.params[6], orderError); require(_leftOrder.param7 == _derivative.params[7], orderError); require(_leftOrder.param8 == _derivative.params[8], orderError); require(_leftOrder.param9 == _derivative.params[9], orderError); // Validate right order params require(_rightOrder.param0 == _derivative.params[10], orderError); require(_rightOrder.param1 == _derivative.params[11], orderError); require(_rightOrder.param2 == _derivative.params[12], orderError); require(_rightOrder.param3 == _derivative.params[13], orderError); require(_rightOrder.param4 == _derivative.params[14], orderError); require(_rightOrder.param5 == _derivative.params[15], orderError); require(_rightOrder.param6 == _derivative.params[16], orderError); require(_rightOrder.param7 == _derivative.params[17], orderError); require(_rightOrder.param8 == _derivative.params[18], orderError); require(_rightOrder.param9 == _derivative.params[19], orderError); } /// @notice Distributes funds to core /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative /// @param margins uint256[2] left and right margin /// @param _fillable uint256 How many positions are fillable function _distributeFunds(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative, uint256[2] memory margins, uint256 _fillable) private { IERC20 marginToken = IERC20(_derivative.token); TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Transfer margin from left to Match and send to Core if (margins[0] != 0) { // Check allowance for margins require(marginToken.allowance(_leftOrder.makerAddress, address(tokenSpender)) >= margins[0].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from buyer to Match tokenSpender.claimTokens(marginToken, _leftOrder.makerAddress, address(this), margins[0].mul(_fillable)); } // Transfer margin from right to Match and send to Core if (margins[1] != 0) { // Check allowance for premiums + margin require(marginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= margins[1].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from seller to Match tokenSpender.claimTokens(marginToken, _rightOrder.makerAddress, address(this), margins[1].mul(_fillable)); } if (margins[0].add(margins[1]) != 0) { // Approve margin to Core for derivative creation require(marginToken.approve(address(tokenSpender), margins[0].add(margins[1]).mul(_fillable)), "MATCH:COULDNT_APPROVE_MARGIN_FOR_CORE"); } } }
* @dev Gets the approved address for a token ID, or zero if no address set @param _tokenId uint256 ID of the token to query the approval of @return address currently approved for the given token ID/
function getApproved(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); }
1,368,058
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 11881, 326, 20412, 1758, 364, 279, 1147, 1599, 16, 578, 3634, 309, 1158, 1758, 444, 632, 891, 389, 2316, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 843, 326, 23556, 434, 632, 2463, 1758, 4551, 20412, 364, 326, 864, 1147, 1599, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 31639, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 565, 309, 261, 1808, 24899, 2316, 548, 3719, 288, 203, 1377, 327, 1758, 12, 2211, 1769, 203, 565, 289, 203, 203, 565, 327, 1758, 12, 20, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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\token\ERC20\IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\@openzeppelin\contracts\math\SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: node_modules\@openzeppelin\contracts\utils\Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.6.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 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"); } } } // File: contracts\strategies\Interfaces\Compound\CTokenI.sol pragma solidity >=0.5.0; interface CTokenI{ /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function accrualBlockNumber() external view returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); function totalBorrows() external view returns (uint); function totalSupply() external view returns (uint); } // File: contracts\strategies\Interfaces\Compound\CEtherI.sol pragma solidity >=0.5.16; interface CEtherI is CTokenI{ function redeemUnderlying(uint redeemAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function liquidateBorrow(address borrower, CTokenI cTokenCollateral) external payable; function mint() external payable; } // File: contracts\strategies\Interfaces\UniswapInterfaces\IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; function balanceOf(address) external view returns (uint); } // File: contracts\strategies\Interfaces\Yearn\IController.sol pragma solidity >=0.6.9; interface IController { function withdraw(address, uint256) external; function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); function approveStrategy(address, address) external; function setStrategy(address, address) external; function strategies(address) external view returns (address); } // File: contracts\strategies\BaseStrategy.sol pragma solidity >=0.6.0 <0.7.0; struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtLimit; uint256 rateLimit; uint256 lastSync; uint256 totalDebt; uint256 totalReturns; } interface VaultAPI { function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /* * View how much the Vault would increase this strategy's borrow limit, * based on it's present performance (since its last report). Can be used to * determine expectedReturn in your strategy. */ function creditAvailable() external view returns (uint256); /* * View how much the Vault would like to pull back from the Strategy, * based on it's present performance (since its last report). Can be used to * determine expectedReturn in your strategy. */ function debtOutstanding() external view returns (uint256); /* * View how much the Vault expect this strategy to return at the current block, * based on it's present performance (since its last report). Can be used to * determine expectedReturn in your strategy. */ function expectedReturn() external view returns (uint256); /* * This is the main contact point where the strategy interacts with the Vault. * It is critical that this call is handled as intended by the Strategy. * Therefore, this function will be called by BaseStrategy to make sure the * integration is correct. */ function report(uint256 _harvest) external returns (uint256); /* * This function is used in the scenario where there is a newer strategy that * would hold the same positions as this one, and those positions are easily * transferrable to the newer strategy. These positions must be able to be * transferred at the moment this call is made, if any prep is required to * execute a full transfer in one transaction, that must be accounted for * separately from this call. */ function migrateStrategy(address _newStrategy) external; /* * This function should only be used in the scenario where the strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits it's position as fast as possible, such as a sudden change in market * conditions leading to losses, or an imminent failure in an external * dependency. */ function revokeStrategy() external; /* * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. * */ function governance() external view returns (address); } /* * This interface is here for the keeper bot to use */ interface StrategyAPI { function vault() external view returns (address); function keeper() external view returns (address); function tendTrigger(uint256 gasCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 gasCost) external view returns (bool); function harvest() external; event Harvested(uint256 wantEarned, uint256 lifetimeEarned); } /* * BaseStrategy implements all of the required functionality to interoperate closely * with the core protocol. This contract should be inherited and the abstract methods * implemented to adapt the strategy to the particular needs it has to create a return. */ abstract contract BaseStrategy { using SafeMath for uint256; // Version of this contract function version() external pure returns (string memory) { return "0.1.1"; } VaultAPI public vault; address public strategist; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 wantEarned, uint256 lifetimeEarned); // Adjust this to keep some of the position in reserve in the strategy, // to accomodate larger variations needed to sustain the strategy's core positon(s) uint256 public reserve = 0; // This gets adjusted every time the Strategy reports to the Vault, // and should be used during adjustment of the strategy's positions to "deleverage" // in order to pay back the amount the next time it reports. // // NOTE: Do not edit this variable, for safe usage (only read from it) // NOTE: Strategy should not expect to increase it's working capital until this value // is zero. uint256 public outstanding = 0; bool public emergencyExit; constructor(address _vault) public { vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = msg.sender; keeper = msg.sender; } function setStrategist(address _strategist) external { require(msg.sender == strategist || msg.sender == governance(), "!governance"); strategist = _strategist; } function setKeeper(address _keeper) external { require(msg.sender == strategist || msg.sender == governance(), "!governance"); keeper = _keeper; } /* * Resolve governance address from Vault contract, used to make * assertions on protected functions in the Strategy */ function governance() internal view returns (address) { return vault.governance(); } /* * Provide an accurate expected value for the return this strategy * would provide to the Vault the next time `report()` is called * (since the last time it was called) */ function expectedReturn() public virtual view returns (uint256); /* * Provide an accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of `want` tokens. * This total should be "realizable" e.g. the total value that could *actually* be * obtained from this strategy if it were to divest it's entire position based on * current on-chain conditions. * * NOTE: care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through flashloan * attacks, oracle manipulations, or other DeFi attack mechanisms). * * NOTE: It is up to governance to use this function in order to correctly order * this strategy relative to its peers in order to minimize losses for the * Vault based on sudden withdrawals. This value should be higher than the * total debt of the strategy and higher than it's expected value to be "safe". */ function estimatedTotalAssets() public virtual view returns (uint256); /* * Perform any strategy unwinding or other calls necessary to capture * the "free return" this strategy has generated since the last time it's * core position(s) were adusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and should * be optimized to minimize losses as much as possible. It is okay to report * "no returns", however this will affect the credit limit extended to the * strategy and reduce it's overall position if lower than expected returns * are sustained for long periods of time. */ function prepareReturn() internal virtual; /* * Perform any adjustments to the core position(s) of this strategy given * what change the Vault made in the "investable capital" available to the * strategy. Note that all "free capital" in the strategy after the report * was made is available for reinvestment. Also note that this number could * be 0, and you should handle that scenario accordingly. */ function adjustPosition() internal virtual; /* * Make as much capital as possible "free" for the Vault to take. Some slippage * is allowed, since when this method is called the strategist is no longer receiving * their performance fee. The goal is for the strategy to divest as quickly as possible * while not suffering exorbitant losses. This function is used during emergency exit * instead of `prepareReturn()` */ function exitPosition() internal virtual; /* * Provide a signal to the keeper that `tend()` should be called. The keeper will provide * the estimated gas cost that they would pay to call `tend()`, and this function should * use that estimate to make a determination if calling it is "worth it" for the keeper. * This is not the only consideration into issuing this trigger, for example if the position * would be negatively affected if `tend()` is not called shortly, then this can return `true` * even if the keeper might be "at a loss" (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * NOTE: if `tend()` is never intended to be called, it should always return `false` */ function tendTrigger(uint256 gasCost) public virtual view returns (bool); function tend() external { if (keeper != address(0)) require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance()); // NOTE: Don't take profits with this call, but adjust for better gains adjustPosition(); } /* * Provide a signal to the keeper that `harvest()` should be called. The keeper will provide * the estimated gas cost that they would pay to call `harvest()`, and this function should * use that estimate to make a determination if calling it is "worth it" for the keeper. * This is not the only consideration into issuing this trigger, for example if the position * would be negatively affected if `harvest()` is not called shortly, then this can return `true` * even if the keeper might be "at a loss" (keepers are always reimbursed by yEarn) * * NOTE: this call and `tendTrigger` should never return `true` at the same time. */ function harvestTrigger(uint256 gasCost) public virtual view returns (bool); function harvest() external { if (keeper != address(0)) require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance()); if (emergencyExit) { exitPosition(); // Free up as much capital as possible // NOTE: Don't take performance fee in this scenario } else { prepareReturn(); // Free up returns for Vault to pull } if (reserve > want.balanceOf(address(this))) reserve = want.balanceOf(address(this)); // Allow Vault to take up to the "harvested" balance of this contract, which is // the amount it has earned since the last time it reported to the Vault uint256 wantEarned = want.balanceOf(address(this)).sub(reserve); outstanding = vault.report(wantEarned); adjustPosition(); // Check if free returns are left, and re-invest them emit Harvested(wantEarned, vault.strategies(address(this)).totalReturns); } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amount) internal virtual; function withdraw(uint256 _amount) external { require(msg.sender == address(vault), "!vault"); liquidatePosition(_amount); // Liquidates as much as possible to `want`, up to `_amount` want.transfer(msg.sender, want.balanceOf(address(this)).sub(reserve)); } /* * Do anything necesseary to prepare this strategy for migration, such * as transfering any reserve or LP tokens, CDPs, or other tokens or stores of value. */ function prepareMigration(address _newStrategy) internal virtual; function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); } function setEmergencyExit() external { require(msg.sender == strategist || msg.sender == governance()); emergencyExit = true; exitPosition(); vault.revokeStrategy(); if (reserve > want.balanceOf(address(this))) reserve = want.balanceOf(address(this)); outstanding = vault.report(want.balanceOf(address(this)).sub(reserve)); } // Override this to add all tokens this contract manages on a *persistant* basis // (e.g. not just for swapping back to want ephemerally) // NOTE: Must inclide `want` token function protectedTokens() internal virtual view returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(want); return protected; } function sweep(address _token) external { address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: contracts\strategies\YearnWethCreamStratV2.sol pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT //cream is fork of compound and has same interface /******************** * An ETH Cream strategy with a liquidity buffer to ensure we don't end up in crisis. * Made by SamPriestley.com * https://github.com/Grandthrax/yearnv2/blob/master/contracts/YearnWethCreamStratV2.sol * ********************* */ contract YearnWethCreamStratV2 is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; string public constant name = "YearnWethCreamStratV2"; //Only three tokens we use CEtherI public constant crETH = CEtherI(address(0xD06527D5e56A3495252A528C4987003b712860eE)); IWETH public constant weth = IWETH(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)); uint256 public maxReportDelay = 50; //6300 is once a day. lower vaule used for testing //Operating variables uint256 public liquidityCushion = 3000 ether; // 3000 ether ~ 1m usd uint256 public profitFactor = 50; // multiple before triggering harvest uint256 public dustThreshold = 0.01 ether; // multiple before triggering harvest constructor(address _vault) public BaseStrategy(_vault) { //only accept ETH vault require(vault.token() == address(weth), "!WETH"); } //to receive eth from weth receive() external payable {} /* * Control Functions */ function setProfitFactor(uint256 _profitFactor) external { require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist profitFactor = _profitFactor; } function setLiquidityCushion(uint256 _liquidityCushion) external { require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist liquidityCushion = _liquidityCushion; } /* * Base External Facing Functions */ /* * Expected return this strategy would provide to the Vault the next time `report()` is called * * The total assets currently in strategy minus what vault believes we have */ function expectedReturn() public override view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets - debt; } } /* * Our balance in CrETH plus balance of want */ function estimatedTotalAssets() public override view returns (uint256) { uint256 underlying = underlyingBalanceStored(); return want.balanceOf(address(this)).add(underlying); } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * If we are in liquidation cushion we move */ function tendTrigger(uint256 gasCost) public override view returns (bool) { gasCost; // silence UI warning if (harvestTrigger(gasCost)) { //harvest takes priority return false; } //we want to tend if there is a liquidity crisis uint256 cashAvailable = crETH.getCash(); if(cashAvailable == 0){ return false; } uint wethBalance = weth.balanceOf(address(this)); uint256 toKeep = 0; //to keep is the amount we need to hold to make the liqudity cushion full if(cashAvailable.add(wethBalance.mul(2)) < liquidityCushion){ toKeep = liquidityCushion.sub(cashAvailable.add(wethBalance)); } if (toKeep > wethBalance.add(dustThreshold) && cashAvailable <= liquidityCushion && cashAvailable > dustThreshold && underlyingBalanceStored() > dustThreshold) { return true; } // if liquidity crisis is over if(wethBalance > 0 && liquidityCushion < cashAvailable){ if(cashAvailable - liquidityCushion > gasCost.mul(profitFactor) && wethBalance > gasCost.mul(profitFactor)){ return true; } } return false; } function underlyingBalanceStored() public view returns (uint256 balance){ uint256 currentCrETH = crETH.balanceOf(address(this)); if(currentCrETH == 0){ balance = 0; }else{ balance = currentCrETH.mul(crETH.exchangeRateStored()).div(1e18); } } /* * Provide a signal to the keeper that `harvest()` should be called. * gasCost is expected_gas_use * gas_price * (keepers are always reimbursed by yEarn) * * NOTE: this call and `tendTrigger` should never return `true` at the same time. */ function harvestTrigger(uint256 gasCost) public override view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if strategy is not activated if (params.activation == 0) return false; // Should trigger if hadn't been called in a while if (block.number.sub(params.lastSync) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is adjusted in step-wise fashion, it is appropiate to always trigger here, // because the resulting change should be large (might not always be the case) uint256 outstanding = vault.debtOutstanding(); if (outstanding > dustThreshold && crETH.getCash().add(want.balanceOf(address(this))) > 0) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); if (total.add(dustThreshold) < params.totalDebt) return true; // We have a loss to report! uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor * gasCost < credit.add(profit)); } /*********** * internal core logic *********** */ /* * A core method. */ function prepareReturn() internal override { if (crETH.balanceOf(address(this)) == 0) { //no position to harvest reserve = weth.balanceOf(address(this)); return; } if (reserve != 0) { //reset reserve so it doesnt interfere anywhere else reserve = 0; } uint256 balanceInCr = crETH.balanceOfUnderlying(address(this)); uint256 balanceInWeth = weth.balanceOf(address(this)); uint256 total = balanceInCr.add(balanceInWeth); uint256 debt = vault.strategies(address(this)).totalDebt; if(total > debt){ uint profit = total-debt; uint amountToFree = profit.add(outstanding); //we need to add outstanding to our profit if(balanceInWeth >= amountToFree){ reserve = weth.balanceOf(address(this)) - amountToFree; }else{ //change profit to what we can withdraw _withdrawSome(amountToFree.sub(balanceInWeth)); balanceInWeth = weth.balanceOf(address(this)); if(balanceInWeth > amountToFree){ reserve = balanceInWeth - amountToFree; }else{ reserve = 0; } } }else{ uint256 bal = weth.balanceOf(address(this)); if(bal <= outstanding){ reserve = 0; }else{ reserve = bal - outstanding; } } } /* * Second core function. Happens after report call. * */ function adjustPosition() internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we did state changing call in prepare return so this will be accurate uint liquidity = crETH.getCash(); if(liquidity == 0){ return; } uint wethBalance = weth.balanceOf(address(this)); uint256 toKeep = 0; //to keep is the amount we need to hold to make the liqudity cushion full if(liquidity < liquidityCushion){ toKeep = liquidityCushion.sub(liquidity); } toKeep = toKeep.add(outstanding); //if we have more than enough weth then invest the extra if(wethBalance > toKeep){ uint toInvest = wethBalance.sub(toKeep); //turn weth into eth first weth.withdraw(toInvest); //mint crETH.mint{value: toInvest}(); }else if(wethBalance < toKeep){ //free up the difference if we can uint toWithdraw = toKeep.sub(wethBalance); _withdrawSome(toWithdraw); } } /************* * Withdraw Up to the amount asked for * returns amount we really withdrew ******************** */ function _withdrawSome(uint256 _amount) internal returns(uint256 amountWithdrawn) { //state changing uint balance = crETH.balanceOfUnderlying(address(this)); if(_amount > balance){ //cant withdraw more than we own _amount = balance; } //not state changing but OK because of previous call uint liquidity = crETH.getCash(); amountWithdrawn = 0; if(liquidity == 0){ return amountWithdrawn; } if(_amount <= liquidity){ amountWithdrawn = _amount; //we can take all crETH.redeemUnderlying(amountWithdrawn); }else{ //take all we can amountWithdrawn = liquidity-1; crETH.redeemUnderlying(amountWithdrawn); //safe as we return if liquidity == 0 } //remember to turn eth to weth weth.deposit{value: address(this).balance}(); } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amount) internal override { uint256 _balance = want.balanceOf(address(this)); if(_balance >= _amount){ //if we don't set reserve here withdrawer will be sent our full balance reserve = _balance.sub(_amount); return; }else{ _withdrawSome(_amount - _balance); } } /* * Make as much capital as possible "free" for the Vault to take. Some slippage * is allowed. */ function exitPosition() internal override { uint balance = crETH.balanceOfUnderlying(address(this)); if(balance > 0){ _withdrawSome(balance); } reserve = 0; } //lets leave function prepareMigration(address _newStrategy) internal override { crETH.transfer(_newStrategy, crETH.balanceOf(address(this))); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } function protectedTokens() internal override view returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = address(want); protected[1] = address(crETH); return protected; } }
safe as we return if liquidity == 0
crETH.redeemUnderlying(amountWithdrawn);
14,005,302
[ 1, 4625, 348, 7953, 560, 30, 4183, 487, 732, 327, 309, 4501, 372, 24237, 422, 374, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 4422, 1584, 44, 18, 266, 24903, 14655, 6291, 12, 8949, 1190, 9446, 82, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_404(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,117
[ 1, 4625, 348, 7953, 560, 30, 225, 2660, 30, 1410, 10929, 3560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6617, 537, 67, 11746, 12, 2867, 17571, 264, 16, 2254, 460, 13, 1071, 1135, 261, 6430, 1529, 13, 288, 203, 565, 389, 12908, 4524, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 460, 31, 203, 565, 3626, 1716, 685, 1125, 12, 1234, 18, 15330, 16, 17571, 264, 16, 460, 11272, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x11b2164DDf1C3c0a420cEaD050d422B26530d11C/sources/contracts/facets/ERC721A/ERC721AUpgradeableFacet.sol
* @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}. Requirements: - The caller must own the token or be an approved operator./
function approve(address to, uint256 tokenId) public payable onlyAllowedOperatorApproval(to) virtual { _approve(to, tokenId, true); }
9,188,652
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 611, 3606, 4132, 358, 1375, 869, 68, 358, 7412, 1375, 2316, 548, 68, 1147, 358, 4042, 2236, 18, 2164, 288, 654, 39, 27, 5340, 37, 17, 67, 12908, 537, 5496, 29076, 30, 300, 1021, 4894, 1297, 4953, 326, 1147, 578, 506, 392, 20412, 3726, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 8843, 429, 225, 1338, 5042, 5592, 23461, 12, 869, 13, 225, 5024, 288, 203, 3639, 389, 12908, 537, 12, 869, 16, 1147, 548, 16, 638, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.5.16; pragma experimental ABIEncoderV2; contract Health { //mappings mapping(address => uint) authCaller; mapping(address => string) userType; mapping(address => patient) PData; mapping(address=> address[]) patToDoctor; mapping(address => doctor) DData; mapping(address => insaurance) IData; mapping(address => chemist) CData; mapping(uint => treatment) treatmentDetails; mapping(address => medicine[]) PatToMed; mapping(address => bill[]) patToChemistBill; mapping(address => address[]) insToPat; //constructor constructor() public{ authCaller[msg.sender] = 1; } //events event DoctorAdded(address doctorAdd); event ChemistAdded(address ChemistAdd); event insAdded(address insAdd); event treated(address indexed Did,address indexed Pid,uint tid); //structs struct bill{ address chemid; string date; uint amt; } struct patient{ string Phash; uint [] treatmentId; string precautions; } struct doctor{ string Dhash; } struct chemist{ string Chash; } struct insaurance{ string Ihash; } struct treatment { string Thash; } struct medicine{ address pid; string medicines; string date; } //struct variable //patient functions //make function to show all chemist bills function addPat(string memory _Phash) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked(""))); patient memory pat; pat.Phash = _Phash; userType[msg.sender] = 'patient'; PData[msg.sender] = pat; return true; } function getbills() public returns(bill[] memory){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("patient"))); return patToChemistBill[msg.sender]; } //return patient treatmentId and precautions as well function getPatient(address _Padd) public returns(string memory,uint[] memory,string memory){ require(msg.sender == _Padd); require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("patient"))); return (PData[msg.sender].Phash,PData[msg.sender].treatmentId,PData[msg.sender].precautions); } function getDoctor(address _Dadd) public returns(string memory){ //need to complete return DData[_Dadd].Dhash; } function getIns(address _Iadd) public returns(string memory){ //need to complete return IData[_Iadd].Ihash; } function grantAccess(address _Dadd) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("patient"))); patToDoctor[msg.sender].push(_Dadd); return true; } //check give address is insaurance company is or not function applyIns(address _Iadd) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("patient"))); require(keccak256(abi.encodePacked(userType[_Iadd])) == keccak256(abi.encodePacked("Insaurance"))); insToPat[_Iadd].push(msg.sender); return true; } function isValid(address pat,address doctor) public returns(bool){ address[] memory temp = patToDoctor[pat]; uint len = temp.length; for(uint i = 0;i<len;i++){ if(temp[i] == doctor) return true; } return false; } //getUser function getUser(address _Uaddress) public returns(string memory){ return userType[_Uaddress]; } //Doctor function addDoc(string memory _Dhash) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked(""))); userType[msg.sender] = 'doctor'; DData[msg.sender].Dhash = _Dhash; emit DoctorAdded(msg.sender); return true; } function updatePrecautions(address _Padd,string memory _precautions) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("doctor"))); require(isValid(_Padd,msg.sender) == true); PData[_Padd].precautions = _precautions; return true; } function random() private view returns (uint) { return uint(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251); } function treatPatient(address _Padd, string memory _Thash) public returns(uint){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("doctor"))); require(isValid(_Padd,msg.sender) == true); uint _tid = random(); treatment memory trt; trt.Thash = _Thash; PData[_Padd].treatmentId.push(_tid); treatmentDetails[_tid] = trt; emit treated(msg.sender,_Padd,_tid); return _tid; } //check if chemist is present function giveMedicines(address _pid,string memory _medicines,string memory _date) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("doctor"))); require(isValid(_pid,msg.sender) == true); PatToMed[_pid].push(medicine(_pid,_medicines,_date)); return true; } function getTrtDetails(uint _tid) public returns(string memory){ require(keccak256(abi.encodePacked(userType[msg.sender])) != keccak256(abi.encodePacked("doctor"))); require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("patient"))); return treatmentDetails[_tid].Thash; } //chemist function addChemist(string memory Chash) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked(""))); userType[msg.sender] = 'Chemist'; CData[msg.sender].Chash = Chash; emit ChemistAdded(msg.sender); return true; } function getMedicineDetails(address _pid) public returns(medicine[] memory){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("Chemist"))); return PatToMed[_pid]; } function sellMedicines(address _pid,string memory _date,uint _amt) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("Chemist"))); patToChemistBill[_pid].push(bill(msg.sender,_date,_amt)); return true; } //insaurance function addInsCompany(string memory Ihash) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked(""))); userType[msg.sender] = 'Insaurance'; IData[msg.sender].Ihash = Ihash; emit insAdded(msg.sender); return true; } function getAppliedForIns() public returns(address[] memory){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("Insaurance"))); return(insToPat[msg.sender]); } function approveInsurance(address patId) public returns(bool){ require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("Insaurance"))); address[] memory arr = insToPat[msg.sender]; uint len = arr.length; int j = -122; for(uint i = 0 ; i < len ; i++ ){ if(arr[i] == patId){ j=int (i); } } if(j != -122){ uint i = uint (j); delete insToPat[msg.sender][i]; } return true; } }
return patient treatmentId and precautions as well
function getPatient(address _Padd) public returns(string memory,uint[] memory,string memory){ require(msg.sender == _Padd); require(keccak256(abi.encodePacked(userType[msg.sender])) == keccak256(abi.encodePacked("patient"))); return (PData[msg.sender].Phash,PData[msg.sender].treatmentId,PData[msg.sender].precautions); }
956,158
[ 1, 4625, 348, 7953, 560, 30, 327, 18608, 24266, 548, 471, 675, 5353, 6170, 487, 5492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1689, 270, 1979, 12, 2867, 389, 52, 1289, 13, 1071, 1135, 12, 1080, 3778, 16, 11890, 8526, 3778, 16, 1080, 3778, 15329, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 52, 1289, 1769, 203, 3639, 2583, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1355, 559, 63, 3576, 18, 15330, 22643, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 16330, 1979, 6, 3719, 1769, 203, 540, 203, 3639, 327, 261, 52, 751, 63, 3576, 18, 15330, 8009, 52, 2816, 16, 52, 751, 63, 3576, 18, 15330, 8009, 25707, 548, 16, 52, 751, 63, 3576, 18, 15330, 8009, 4036, 5854, 1115, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x3056Ae2701fB1c97c57a1A5a9521E6E62D173499/sources/BEP20Polkadot.sol
* @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; }
11,124,795
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2860, 326, 10022, 434, 3739, 10415, 2795, 9088, 12321, 18, 261, 22297, 3571, 26109, 3631, 868, 31537, 598, 1679, 883, 1347, 3739, 10415, 635, 3634, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 12430, 68, 3726, 18, 1220, 445, 4692, 279, 1375, 266, 1097, 68, 11396, 261, 12784, 15559, 4463, 16189, 640, 869, 19370, 13, 1323, 348, 7953, 560, 4692, 392, 2057, 11396, 358, 15226, 261, 17664, 310, 777, 4463, 16189, 2934, 29076, 30, 300, 1021, 15013, 2780, 506, 3634, 18, 19, 2, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 681, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 6528, 12, 70, 480, 374, 16, 9324, 1769, 203, 2463, 279, 738, 324, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x23599275e58005cBf1c348fe9a19a0076FBB1635/sources/ERC20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } ) internal virtual {} ) internal virtual {} }
9,752,027
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 25379, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 30131, 9875, 14567, 30, 4186, 15226, 3560, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 9484, 2537, 635, 13895, 358, 7864, 350, 2641, 18, 4673, 16164, 434, 326, 512, 2579, 2026, 486, 3626, 4259, 2641, 16, 487, 518, 5177, 1404, 1931, 635, 326, 7490, 18, 15768, 16, 326, 1661, 17, 10005, 288, 323, 11908, 7009, 1359, 97, 471, 288, 267, 11908, 7009, 1359, 97, 4186, 1240, 2118, 3096, 358, 20310, 360, 340, 326, 5492, 17, 2994, 8296, 6740, 3637, 1699, 6872, 18, 2164, 288, 45, 654, 39, 3462, 17, 12908, 537, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 24899, 3576, 12021, 9334, 8027, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 389, 5965, 6872, 63, 15330, 6362, 67, 3576, 12021, 1435, 15533, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 1699, 1359, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 15330, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 300, 3844, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 389, 5965, 6872, 63, 15330, 6362, 67, 3576, 12021, 1435, 15533, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 1699, 1359, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 15330, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 300, 3844, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 10929, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 3096, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 389, 5965, 6872, 63, 67, 3576, 12021, 1435, 6362, 87, 1302, 264, 65, 397, 3096, 620, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 389, 5965, 6872, 63, 67, 3576, 12021, 1435, 6362, 87, 1302, 264, 15533, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 10418, 329, 620, 16, 315, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 783, 7009, 1359, 300, 10418, 329, 620, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 389, 5965, 6872, 63, 67, 3576, 12021, 1435, 6362, 87, 1302, 264, 15533, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 10418, 329, 620, 16, 315, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 783, 7009, 1359, 300, 10418, 329, 620, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 2254, 5034, 5793, 13937, 273, 389, 70, 26488, 63, 15330, 15533, 203, 3639, 2583, 12, 15330, 13937, 1545, 3844, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 11013, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 70, 26488, 63, 15330, 65, 273, 5793, 13937, 300, 3844, 31, 203, 3639, 289, 203, 3639, 389, 70, 26488, 63, 20367, 65, 1011, 3844, 31, 203, 203, 3639, 3626, 12279, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 389, 5205, 1345, 5912, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 2 ]
./full_match/80001/0xd3cFB1CE690B52006c90d8425D4EbAa9c86aBC77/sources/contracts/module/NTS-Single.sol
Update the user's total rewards earned and store the reward payment information.
users[msg.sender].rewardsEarned += _myReward;
5,581,709
[ 1, 4625, 348, 7953, 560, 30, 225, 2315, 326, 729, 1807, 2078, 283, 6397, 425, 1303, 329, 471, 1707, 326, 19890, 5184, 1779, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3677, 63, 3576, 18, 15330, 8009, 266, 6397, 41, 1303, 329, 1011, 389, 4811, 17631, 1060, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.19; // File: contracts\MultiOwnable.sol /** * FEATURE 2): MultiOwnable implementation * Transactions approved by _multiRequires of _multiOwners' addresses will be executed. * All functions needing unit-tests cannot be INTERNAL */ contract MultiOwnable { address[8] m_owners; uint m_numOwners; uint m_multiRequires; mapping (bytes32 => uint) internal m_pendings; event AcceptConfirm(bytes32 operation, address indexed who, uint confirmTotal); // constructor is given number of sigs required to do protected "multiOwner" transactions function MultiOwnable (address[] _multiOwners, uint _multiRequires) public { require(0 < _multiRequires && _multiRequires <= _multiOwners.length); m_numOwners = _multiOwners.length; require(m_numOwners <= 8); // Bigger then 8 co-owners, not support ! for (uint i = 0; i < _multiOwners.length; ++i) { m_owners[i] = _multiOwners[i]; require(m_owners[i] != address(0)); } m_multiRequires = _multiRequires; } // Any one of the owners, will approve the action modifier anyOwner { if (isOwner(msg.sender)) { _; } } // Requiring num > m_multiRequires owners, to approve the action modifier mostOwner(bytes32 operation) { if (checkAndConfirm(msg.sender, operation)) { _; } } function isOwner(address currentUser) public view returns (bool) { for (uint i = 0; i < m_numOwners; ++i) { if (m_owners[i] == currentUser) { return true; } } return false; } function checkAndConfirm(address currentUser, bytes32 operation) public returns (bool) { uint ownerIndex = m_numOwners; uint i; for (i = 0; i < m_numOwners; ++i) { if (m_owners[i] == currentUser) { ownerIndex = i; } } if (ownerIndex == m_numOwners) { return false; // Not Owner } uint newBitFinger = (m_pendings[operation] | (2 ** ownerIndex)); uint confirmTotal = 0; for (i = 0; i < m_numOwners; ++i) { if ((newBitFinger & (2 ** i)) > 0) { confirmTotal ++; } } AcceptConfirm(operation, currentUser, confirmTotal); if (confirmTotal >= m_multiRequires) { delete m_pendings[operation]; return true; } else { m_pendings[operation] = newBitFinger; return false; } } } // File: contracts\Pausable.sol /** * FEATURE 3): Pausable implementation */ contract Pausable is MultiOwnable { event Pause(); event Unpause(); bool paused = false; // Modifier to make a function callable only when the contract is not paused. modifier whenNotPaused() { require(!paused); _; } // Modifier to make a function callable only when the contract is paused. modifier whenPaused() { require(paused); _; } // called by the owner to pause, triggers stopped state function pause() mostOwner(keccak256(msg.data)) whenNotPaused public { paused = true; Pause(); } // called by the owner to unpause, returns to normal state function unpause() mostOwner(keccak256(msg.data)) whenPaused public { paused = false; Unpause(); } function isPause() view public returns(bool) { return paused; } } // File: contracts\SafeMath.sol /** * Standard SafeMath Library: zeppelin-solidity/contracts/math/SafeMath.sol */ 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; } } // File: contracts\RoutineGPX.sol /** * The updated body of smart contract. * %6 fund will be transferred to ParcelX advisors automatically. */ contract RoutineGPX is MultiOwnable, Pausable { using SafeMath for uint256; function RoutineGPX(address[] _multiOwners, uint _multiRequires) MultiOwnable(_multiOwners, _multiRequires) public { } event Deposit(address indexed who, uint256 value); event Withdraw(address indexed who, uint256 value, address indexed lastApprover, string extra); function getTime() public view returns (uint256) { return now; } function getBalance() public view returns (uint256) { return this.balance; } /** * FEATURE : Buyable * minimum of 0.001 ether for purchase in the public, pre-ico, and private sale * Code caculates the endtime via python: * d1 = datetime.datetime.strptime("2018-10-31 23:59:59", '%Y-%m-%d %H:%M:%S') * t = time.mktime(d1.timetuple()) * d2 = datetime.datetime.fromtimestamp(t) * assert (d1 == d2) # print d2.strftime('%Y-%m-%d %H:%M:%S') * print t # = 1541001599 */ function buy() payable whenNotPaused public returns (bool) { Deposit(msg.sender, msg.value); require(msg.value >= 0.001 ether); return true; } // gets called when no other function matches function () payable public { if (msg.value > 0) { buy(); } } function execute(address _to, uint256 _value, string _extra) mostOwner(keccak256(msg.data)) external returns (bool){ require(_to != address(0)); _to.transfer(_value); // Prevent using call() or send() Withdraw(_to, _value, msg.sender, _extra); return true; } }
* FEATURE : Buyable minimum of 0.001 ether for purchase in the public, pre-ico, and private sale Code caculates the endtime via python: d1 = datetime.datetime.strptime("2018-10-31 23:59:59", '%Y-%m-%d %H:%M:%S') t = time.mktime(d1.timetuple()) d2 = datetime.datetime.fromtimestamp(t) assert (d1 == d2) # print d2.strftime('%Y-%m-%d %H:%M:%S') print t # = 1541001599/
function buy() payable whenNotPaused public returns (bool) { Deposit(msg.sender, msg.value); require(msg.value >= 0.001 ether); return true; }
12,791,489
[ 1, 4625, 348, 7953, 560, 30, 380, 25201, 294, 605, 9835, 429, 5224, 434, 374, 18, 11664, 225, 2437, 364, 23701, 316, 326, 1071, 16, 675, 17, 10764, 16, 471, 3238, 272, 5349, 3356, 276, 1077, 17099, 326, 31361, 3970, 5790, 30, 282, 302, 21, 273, 3314, 18, 6585, 18, 701, 10650, 2932, 21849, 17, 2163, 17, 6938, 10213, 30, 6162, 30, 6162, 3113, 1995, 61, 6456, 81, 6456, 72, 738, 44, 5319, 49, 5319, 55, 6134, 282, 268, 273, 813, 18, 24816, 957, 12, 72, 21, 18, 8584, 278, 2268, 10756, 282, 302, 22, 273, 3314, 18, 6585, 18, 2080, 5508, 12, 88, 13, 282, 1815, 261, 72, 21, 422, 302, 22, 13, 225, 468, 1172, 302, 22, 18, 701, 9982, 29909, 61, 6456, 81, 6456, 72, 738, 44, 5319, 49, 5319, 55, 6134, 282, 1172, 268, 468, 273, 4711, 24, 6625, 3600, 2733, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 1435, 8843, 429, 1347, 1248, 28590, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 4019, 538, 305, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 374, 18, 11664, 225, 2437, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Admin is Ownable { using SafeMath for uint256; struct Tier { uint256 amountInCenter; uint256 amountInOuter; uint256 priceInCenter; uint256 priceInOuter; uint256 soldInCenter; uint256 soldInOuter; bool filledInCenter; bool filledInOuter; } Tier[] public tiers; bool public halted; uint256 public logoPrice = 0; uint256 public logoId; address public platformWallet; uint256 public feeForFirstArtWorkChangeRequest = 0 ether; uint256 public feeForArtWorkChangeRequest = 0.2 ether; uint256 public minResalePercentage = 15; mapping(address => bool) public globalAdmins; mapping(address => bool) public admins; mapping(address => bool) public signers; event Halted(bool _halted); modifier onlyAdmin() { require(true == admins[msg.sender] || true == globalAdmins[msg.sender]); _; } modifier onlyGlobalAdmin() { require(true == globalAdmins[msg.sender]); _; } modifier notHalted() { require(halted == false); _; } function addGlobalAdmin(address _address) public onlyOwner() { globalAdmins[_address] = true; } function removeGlobalAdmin(address _address) public onlyOwner() { globalAdmins[_address] = false; } function addAdmin(address _address) public onlyGlobalAdmin() { admins[_address] = true; } function removeAdmin(address _address) public onlyGlobalAdmin() { admins[_address] = true; } function setSigner(address _address, bool status) public onlyGlobalAdmin() { signers[_address] = status; } function setLogoPrice(uint256 _price) public onlyGlobalAdmin() { logoPrice = _price; } function setFeeForFirstArtWorkChangeRequest(uint256 _fee) public onlyGlobalAdmin() { feeForFirstArtWorkChangeRequest = _fee; } function setFeeForArtWorkChangeRequest(uint256 _fee) public onlyGlobalAdmin() { feeForArtWorkChangeRequest = _fee; } /// @notice global Admin update tier data function setTierData( uint256 _index, uint256 _priceInCenter, uint256 _priceInOuter) public onlyGlobalAdmin() { Tier memory tier = tiers[_index]; tier.priceInCenter = _priceInCenter; tier.priceInOuter = _priceInOuter; tiers[_index] = tier; } function setMinResalePercentage(uint256 _minResalePercentage) public onlyGlobalAdmin() { minResalePercentage = _minResalePercentage; } function isAdmin(address _address) public view returns (bool isAdmin_) { return (true == admins[_address] || true == globalAdmins[_address]); } function setHalted(bool _halted) public onlyGlobalAdmin { halted = _halted; emit Halted(_halted); } function verify(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(abi.encodePacked(prefix, _hash)), _v, _r, _s); } function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } function setPlatformWallet(address _addresss) public onlyGlobalAdmin() { platformWallet = _addresss; } } contract BigIoAdSpace is Ownable { using SafeMath for uint256; /// @notice Token struct Token { uint256 id; uint256 x; // position X on map uint256 y; // position Y on map uint256 sizeA; uint256 sizeB; uint256 soldPrice; // price that user paid to buy token uint256 actualPrice; uint256 timesSold; // how many times token was sold uint256 timesUpdated; // how many times artwork has been changed by current owner uint256 soldAt; // when token was sold uint256 inner; uint256 outer; uint256 soldNearby; } struct MetaData { string meta; } struct InnerScope { uint256 x1; // left top uint256 y1; uint256 x2; // right top uint256 y2; uint256 x3; // left bottom uint256 y3; uint256 x4; // right bottom uint256 y4; } InnerScope public innerScope; /// @notice mapping for token URIs mapping(uint256 => MetaData) public metadata; /// @notice Mapping from token ID to owner mapping(uint256 => address) public tokenOwner; mapping(uint256 => mapping(uint256 => bool)) public neighbours; mapping(uint256 => uint256[]) public neighboursArea; /// @notice Here different from base class we store the token not an id /// Array with all token, used for enumeration Token[] public allMinedTokens; /// @notice Mapping from token id to position in the allMinedTokens array mapping(uint256 => uint256) public allTokensIndex; // store sold units and not-sold but generated units // mapping(uint256 => mapping(uint256 => bool)) public soldUnits; mapping(uint256 => mapping(uint256 => uint256)) public soldUnits; address public platform; event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event TokenPriceIncreased(uint256 _tokenId, uint256 _newPrice, uint256 _boughtTokenId, uint256 time); constructor () public { innerScope = InnerScope( 12, 11, // left top 67, 11, // right top 12, 34, // left bottom 67, 34 ); } modifier onlyPlatform() { require(msg.sender == platform); _; } modifier exists(uint256 _tokenId) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); _; } function setPlatform(address _platform) public onlyOwner() { platform = _platform; } function totalSupply() public view returns (uint256) { return allMinedTokens.length; } /// @notice Check whether token is minted function tokenExists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /// @notice Check whether exist Unit with same x any y coordinates /// and it was sold already /// in order to prevent over writing function unitExists(uint x, uint y) public view returns (bool) { return (soldUnits[x][y] != 0); } function getOwner(uint256 _tokenId) public view returns (address) { return tokenOwner[_tokenId]; } /// @return token metadata function getMetadata(uint256 _tokenId) public exists(_tokenId) view returns (string) { return metadata[_tokenId].meta; } /// @notice update metadata for token function setTokenMetadata(uint256 _tokenId, string meta) public onlyPlatform exists(_tokenId) { metadata[_tokenId] = MetaData(meta); } function increaseUpdateMetadataCounter(uint256 _tokenId) public onlyPlatform { allMinedTokens[allTokensIndex[_tokenId]].timesUpdated = allMinedTokens[allTokensIndex[_tokenId]].timesUpdated.add(1); } /// @notice remove metadata for token function removeTokenMetadata(uint256 _tokenId) public onlyPlatform exists(_tokenId) { delete metadata[_tokenId]; } // @return return the current price function getCurrentPriceForToken(uint256 _tokenId) public exists(_tokenId) view returns (uint256) { return allMinedTokens[allTokensIndex[_tokenId]].actualPrice; } /// @return tokenId, x, y, sizeA, sizeB, price, inner, outer function getTokenData(uint256 _tokenId) public exists(_tokenId) view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (_tokenId, token.x, token.y, token.sizeA, token.sizeB, token.actualPrice, token.soldPrice, token.inner, token.outer); } function getTokenSoldPrice(uint256 _tokenId) public exists(_tokenId) view returns (uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return token.soldPrice; } function getTokenUpdatedCounter(uint256 _tokenId) public exists(_tokenId) view returns (uint256) { return allMinedTokens[allTokensIndex[_tokenId]].timesUpdated; } // @return return token sizes function getTokenSizes(uint256 _tokenId) public exists(_tokenId) view returns (uint256, uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (token.sizeA, token.sizeB); } // @return return token scopes function getTokenScope(uint256 _tokenId) public exists(_tokenId) view returns (bool, bool) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (token.inner > 0, token.outer > 0); } // @return return token scope counters function getTokenCounters(uint256 _tokenId) public exists(_tokenId) view returns (uint256, uint256, uint256, uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (token.inner, token.outer, token.timesSold, token.soldNearby); } /// @notice Mint new token, not sell new token /// BE sends: owner, x coordinate, y coordinate, price /// @param to new owner /// @param x coordinate /// @param y coordinate /// @param totalPrice calculated price for all units + % for siblings function mint( address to, uint x, uint y, uint sizeA, uint sizeB, uint256 totalPrice, uint256 actualPrice ) public onlyPlatform() returns (uint256) { // 1. require(to != address(0)); require(sizeA.mul(sizeB) <= 100); // 2. check area uint256 inner; uint256 total; (total, inner) = calculateCounters(x, y, sizeA, sizeB); // we avoid zero because we later compare against zero uint256 tokenId = (allMinedTokens.length).add(1); // @TODO: ACHTUNG - soldAt equals 0 during minting Token memory minted = Token(tokenId, x, y, sizeA, sizeB, totalPrice, actualPrice, 0, 0, 0, inner, total.sub(inner), 0); // 3. copy units and create siblings copyToAllUnits(x, y, sizeA, sizeB, tokenId); // 4. update state updateInternalState(minted, to); return tokenId; } function updateTokensState(uint256 _tokenId, uint256 newPrice) public onlyPlatform exists(_tokenId) { uint256 index = allTokensIndex[_tokenId]; allMinedTokens[index].timesSold += 1; allMinedTokens[index].timesUpdated = 0; allMinedTokens[index].soldNearby = 0; allMinedTokens[index].soldPrice = newPrice; allMinedTokens[index].actualPrice = newPrice; allMinedTokens[index].soldAt = now; } function updateOwner(uint256 _tokenId, address newOwner, address prevOwner) public onlyPlatform exists(_tokenId) { require(newOwner != address(0)); require(prevOwner != address(0)); require(prevOwner == tokenOwner[_tokenId]); // update data for new owner tokenOwner[_tokenId] = newOwner; } function inInnerScope(uint256 x, uint256 y) public view returns (bool) { // x should be between left top and right top corner // y should be between left top and left bottom corner if ((x >= innerScope.x1) && (x <= innerScope.x2) && (y >= innerScope.y1) && (y <= innerScope.y3)) { return true; } return false; } function calculateCounters(uint256 x, uint256 y, uint256 sizeA, uint256 sizeB) public view returns (uint256 total, uint256 inner) { uint256 upX = x.add(sizeA); uint256 upY = y.add(sizeB); // check for boundaries require(x >= 1); require(y >= 1); require(upX <= 79); require(upY <= 45); require(sizeA > 0); require(sizeB > 0); uint256 i; uint256 j; for (i = x; i < upX; i++) { for (j = y; j < upY; j++) { require(soldUnits[i][j] == 0); if (inInnerScope(i, j)) { inner = inner.add(1); } total = total.add(1); } } } function increasePriceForNeighbours(uint256 tokenId) public onlyPlatform { Token memory token = allMinedTokens[allTokensIndex[tokenId]]; uint256 upX = token.x.add(token.sizeA); uint256 upY = token.y.add(token.sizeB); uint256 i; uint256 j; uint256 k; uint256 _tokenId; if (neighboursArea[tokenId].length == 0) { for (i = token.x; i < upX; i++) { // check neighbors on top of area _tokenId = soldUnits[i][token.y - 1]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } // check neighbors on bottom of area _tokenId = soldUnits[i][upY]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } } for (j = token.y; j < upY; j++) { // check neighbors on left of area of area _tokenId = soldUnits[token.x - 1][j]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } // check neighbors on right of area of area _tokenId = soldUnits[upX][j]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } } } // increase price for (k = 0; k < neighboursArea[tokenId].length; k++) { Token storage _token = allMinedTokens[allTokensIndex[neighboursArea[tokenId][k]]]; _token.soldNearby = _token.soldNearby.add(1); _token.actualPrice = _token.actualPrice.add((_token.actualPrice.div(100))); emit TokenPriceIncreased(_token.id, _token.actualPrice, _tokenId, now); } } // move generated Units to sold array // generate siblings and put it there function copyToAllUnits(uint256 x, uint256 y, uint256 width, uint256 height, uint256 tokenId) internal { uint256 upX = x + width; // 5 uint256 upY = y + height; // 3 uint256 i; // 1 uint256 j; // 1 for (i = x; i < upX; i++) { for (j = y; j < upY; j++) { soldUnits[i][j] = tokenId; } } } function updateInternalState(Token minted, address _to) internal { uint256 lengthT = allMinedTokens.length; allMinedTokens.push(minted); allTokensIndex[minted.id] = lengthT; tokenOwner[minted.id] = _to; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BigIOERC20token is StandardToken, Ownable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public maxSupply; bool public allowedMinting; mapping(address => bool) public mintingAgents; mapping(address => bool) public stateChangeAgents; event MintERC20(address indexed _holder, uint256 _tokens); event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); modifier onlyMintingAgents () { require(mintingAgents[msg.sender]); _; } constructor (string _name, string _symbol, uint8 _decimals, uint256 _maxSupply) public StandardToken() { name = _name; symbol = _symbol; decimals = _decimals; maxSupply = _maxSupply; allowedMinting = true; mintingAgents[msg.sender] = true; } /// @notice update minting agent function updateMintingAgent(address _agent, bool _status) public onlyOwner { mintingAgents[_agent] = _status; } /// @notice allow to mint tokens function mint(address _holder, uint256 _tokens) public onlyMintingAgents() { require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply); totalSupply_ = totalSupply_.add(_tokens); balances[_holder] = balanceOf(_holder).add(_tokens); if (totalSupply_ == maxSupply) { allowedMinting = false; } emit MintERC20(_holder, _tokens); emit Transfer(0x0, _holder, _tokens); } } contract PricingStrategy { using SafeMath for uint256; function calculateMinPriceForNextRound(uint256 _tokenPrice, uint256 _minResalePercentage) public pure returns (uint256) { return _tokenPrice.add(_tokenPrice.div(100).mul(_minResalePercentage)); } function calculateSharesInTheRevenue(uint256 _prevTokenPrice, uint256 _newTokenPrice) public pure returns (uint256, uint256) { uint256 revenue = _newTokenPrice.sub(_prevTokenPrice); uint256 platformShare = revenue.mul(40).div(100); uint256 forPrevOwner = revenue.sub(platformShare); return (platformShare, forPrevOwner); } } /// @title Platform /// @author Applicature /// @notice It is front contract which is used to sell, re-sell tokens and initiate paying dividends contract Platform is Admin { using SafeMath for uint256; struct Offer { uint256 tokenId; uint256 offerId; address from; uint256 offeredPrice; uint256 tokenPrice; bool accepted; uint256 timestamp; } struct ArtWorkChangeRequest { address fromUser; uint256 tokenId; uint256 changeId; string meta; uint256 timestamp; bool isReviewed; } BigIoAdSpace public token; BigIOERC20token public erc20token; PricingStrategy public pricingStrategy; ArtWorkChangeRequest[] public artWorkChangeRequests; bool public isLogoInitied; uint256 public logoX = 35; uint256 public logoY = 18; Offer[] public offers; mapping(address => uint256) public pendingReturns; event Minted(address indexed _owner, uint256 _tokenId, uint256 _x, uint256 _y, uint256 _sizeA, uint256 _sizeB, uint256 _price, uint256 _platformTransfer, uint256 _timestamp); event Purchased(address indexed _from, address indexed _to, uint256 _tokenId, uint256 _price, uint256 _prevPrice, uint256 _prevOwnerTransfer, uint256 _platformTransfer, uint256 _timestamp); event OfferMade(address indexed _fromUser, uint256 _tokenId, uint256 _offerId, uint256 _offeredPrice, uint256 _timestamp); event OfferApproved(address indexed _owner, uint256 _tokenId, uint256 _offerId, uint256 _offeredPrice, uint256 _timestamp); event OfferDeclined(address indexed _fromUser, uint256 _tokenId, uint256 _offerId, uint256 _offeredPrice, uint256 _timestamp); event ArtWorkChangeRequestMade( address indexed _fromUser, uint256 _tokenId, uint256 _changeId, string _meta, uint256 _platformTransfer, uint256 _timestamp); event ArtWorkChangeRequestApproved( address indexed _fromUser, uint256 _tokenId, uint256 _changeId, string _meta, uint256 _timestamp); event ArtWorkChangeRequestDeclined( address indexed _fromUser, uint256 _tokenId, uint256 _changeId, string _meta, uint256 _timestamp); event RemovedMetaData(uint256 _tokenId, address _admin, string _meta, uint256 _timestamp); event ChangedOwnership(uint256 _tokenId, address _prevOwner, address _newOwner, uint256 _timestamp); constructor( address _platformWallet, // owner collects money address _token, address _erc20token, address _pricingStrategy, address _signer ) public { token = BigIoAdSpace(_token); erc20token = BigIOERC20token(_erc20token); platformWallet = _platformWallet; pricingStrategy = PricingStrategy(_pricingStrategy); signers[_signer] = true; // 30% tiers.push( Tier( 400, // amountInCenter 600, // amountInOuter 1 ether, // priceInCenter 0.4 ether, // priceInOuter 0, // soldInCenter 0, // soldInOuter false, // filledInCenter false // filledInOuter ) ); // 30% tiers.push( Tier( 400, 600, 1.2 ether, 0.6 ether, 0, 0, false, false ) ); // 30% tiers.push( Tier( 400, 600, 1.4 ether, 0.8 ether, 0, 0, false, false ) ); // 10% tiers.push( Tier( 144, 288, 1.6 ether, 1.0 ether, 0, 0, false, false ) ); } /// @notice init logo, call it as soon as possible /// call it after setting platform in the token /// Logo is BigIOToken which has 10*10 size and position in the center of map function initLogo() public onlyOwner { require(isLogoInitied == false); isLogoInitied = true; logoId = token.mint(platformWallet, logoX, logoY, 10, 10, 0 ether, 0 ether); token.setTokenMetadata(logoId, ""); updateTierStatus(100, 0); emit Minted(msg.sender, logoId, logoX, logoY, 10, 10, 0 ether, 0 ether, now); } function getPriceFor(uint256 x, uint256 y, uint256 sizeA, uint256 sizeB) public view returns(uint256 totalPrice, uint256 inner, uint256 outer) { (inner, outer) = preMinting(x, y, sizeA, sizeB); totalPrice = calculateTokenPrice(inner, outer); return (totalPrice, inner, outer); } /// @notice sell new tokens during the round 0 /// all except logo function buy( uint256 x, // top left coordinates uint256 y, // top left coordinates uint256 sizeA, // size/width of a square uint256 sizeB, // size/height of a square, uint8 _v, // component of signature bytes32 _r, // component of signature bytes32 _s // component of signature ) public notHalted() payable { address recoveredSigner = verify(keccak256(msg.sender), _v, _r, _s); require(signers[recoveredSigner] == true); require(msg.value > 0); internalBuy(x, y, sizeA, sizeB); } function internalBuy( uint256 x, // top left coordinates uint256 y, // top left coordinates uint256 sizeA, // size/width of a square uint256 sizeB // size/height of a square, ) internal { // get and validate current tier uint256 inner = 0; uint256 outer = 0; uint256 totalPrice = 0; (inner, outer) = preMinting(x, y, sizeA, sizeB); totalPrice = calculateTokenPrice(inner, outer); require(totalPrice <= msg.value); // try to mint and update current tier updateTierStatus(inner, outer); uint256 actualPrice = inner.mul(tiers[3].priceInCenter).add(outer.mul(tiers[3].priceInOuter)); if (msg.value > actualPrice) { actualPrice = msg.value; } uint256 tokenId = token.mint(msg.sender, x, y, sizeA, sizeB, msg.value, actualPrice); erc20token.mint(msg.sender, inner.add(outer)); transferEthers(platformWallet, msg.value); emit Minted(msg.sender, tokenId, x, y, sizeA, sizeB, msg.value, msg.value, now); } /// @notice allow user to make an offer after initial phase(re-sale) /// any offer minResalePercentage is accepted automatically function makeOffer( uint256 _tokenId, uint8 _v, // component of signature bytes32 _r, // component of signature bytes32 _s // component of signature ) public notHalted() payable { address recoveredSigner = verify(keccak256(msg.sender), _v, _r, _s); require(signers[recoveredSigner] == true); require(msg.sender != address(0)); require(msg.value > 0); uint256 currentPrice = getTokenPrice(_tokenId); require(currentPrice > 0); // special case for first sell of logo if (_tokenId == logoId && token.getCurrentPriceForToken(_tokenId) == 0) { require(msg.value >= logoPrice); //update token's state token.updateTokensState(logoId, msg.value); // mint erc20 tokens erc20token.mint(msg.sender, 100); transferEthers(platformWallet, msg.value); emit Purchased(0, msg.sender, _tokenId, msg.value, 0, 0, msg.value, now); return; } uint256 minPrice = pricingStrategy.calculateMinPriceForNextRound(currentPrice, minResalePercentage); require(msg.value >= minPrice); uint256 offerCounter = offers.length; offers.push(Offer(_tokenId, offerCounter, msg.sender, msg.value, currentPrice, false, now)); emit OfferMade(msg.sender, _tokenId, offerCounter, msg.value, now); // 2. check condition for approve and do it approve(offerCounter, _tokenId); } function getTokenPrice(uint256 _tokenId) public view returns (uint256 price) { uint256 actualPrice = token.getCurrentPriceForToken(_tokenId); // special case for first sell of logo if (_tokenId == logoId && actualPrice == 0) { require(logoPrice > 0); return logoPrice; } else { uint256 indexInner = 0; uint256 indexOuter = 0; bool hasInner; bool hasOuter; (hasInner, hasOuter) = token.getTokenScope(_tokenId); (indexInner, indexOuter) = getCurrentTierIndex(); if (_tokenId != logoId && hasInner) { require(indexInner == 100000); } if (hasOuter) { require(indexOuter == 100000); } return actualPrice; } } function getArtWorkChangeFee(uint256 _tokenId) public view returns (uint256 fee) { uint256 counter = token.getTokenUpdatedCounter(_tokenId); if (counter > 0) { return feeForArtWorkChangeRequest; } return feeForFirstArtWorkChangeRequest; } /// @notice it allows token owner to create art work change request /// first user upload 2 images /// then do call this function /// admin can reject or approve it function artWorkChangeRequest(uint256 _tokenId, string _meta, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { address recoveredSigner = verify(keccak256(_meta), _v, _r, _s); require(signers[recoveredSigner] == true); require(msg.sender == token.getOwner(_tokenId)); uint256 fee = getArtWorkChangeFee(_tokenId); require(msg.value >= fee); uint256 changeRequestCounter = artWorkChangeRequests.length; artWorkChangeRequests.push( ArtWorkChangeRequest(msg.sender, _tokenId, changeRequestCounter, _meta, now, false) ); token.increaseUpdateMetadataCounter(_tokenId); transferEthers(platformWallet, msg.value); emit ArtWorkChangeRequestMade(msg.sender, _tokenId, changeRequestCounter, _meta, msg.value, now); return changeRequestCounter; } function artWorkChangeApprove(uint256 _index, uint256 _tokenId, bool approve) public onlyAdmin { ArtWorkChangeRequest storage request = artWorkChangeRequests[_index]; require(false == request.isReviewed); require(_tokenId == request.tokenId); request.isReviewed = true; if (approve) { token.setTokenMetadata(_tokenId, request.meta); emit ArtWorkChangeRequestApproved( request.fromUser, request.tokenId, request.changeId, request.meta, now ); } else { emit ArtWorkChangeRequestDeclined( request.fromUser, request.tokenId, request.changeId, request.meta, now ); } } function artWorkChangeByAdmin(uint256 _tokenId, string _meta, uint256 _changeId) public onlyAdmin { token.setTokenMetadata(_tokenId, _meta); emit ArtWorkChangeRequestApproved( msg.sender, _tokenId, _changeId, _meta, now ); } function changeTokenOwnerByAdmin(uint256 _tokenId, address _newOwner) public onlyAdmin { address prevOwner = token.getOwner(_tokenId); token.updateOwner(_tokenId, _newOwner, prevOwner); emit ChangedOwnership(_tokenId, prevOwner, _newOwner, now); string memory meta = token.getMetadata(_tokenId); token.removeTokenMetadata(_tokenId); emit RemovedMetaData(_tokenId, msg.sender, meta, now); } /// @return tokenId, x, y, sizeA, sizeB, price function getTokenData(uint256 _tokenId) public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return token.getTokenData(_tokenId); } function getMetaData(uint256 _tokenId) public view returns(string) { return token.getMetadata(_tokenId); } /// @notice Withdraw a bid that was overbid and platform owner share function claim() public returns (bool) { return claimInternal(msg.sender); } /// @notice Withdraw (for cold storage wallet) a bid that was overbid and platform owner share function claimByAddress(address _address) public returns (bool) { return claimInternal(_address); } function claimInternal(address _address) internal returns (bool) { require(_address != address(0)); uint256 amount = pendingReturns[_address]; if (amount == 0) { return; } pendingReturns[_address] = 0; _address.transfer(amount); return true; } /// @return index of current tiers, if 100000(cannot use -1) then round 0 finished /// and we need to move to re-sale function getCurrentTierIndex() public view returns (uint256, uint256) { // cannot use -1 // so use not possible value for tiers.length uint256 indexInner = 100000; uint256 indexOuter = 100000; for (uint256 i = 0; i < tiers.length; i++) { if (!tiers[i].filledInCenter) { indexInner = i; break; } } for (uint256 k = 0; k < tiers.length; k++) { if (!tiers[k].filledInOuter) { indexOuter = k; break; } } return (indexInner, indexOuter); } /// @return current tier stats /// index of current tiers, if 100000(cannot use -1) then initial sale is finished /// works only during the initial phase function getCurrentTierStats() public view returns (uint256 indexInner, uint256 indexOuter, uint256 availableInner, uint256 availableInOuter, uint256 priceInCenter, uint256 priceInOuter, uint256 nextPriceInCenter, uint256 nextPriceInOuter) { indexInner = 100000; indexOuter = 100000; for (uint256 i = 0; i < tiers.length; i++) { if (!tiers[i].filledInCenter) { indexInner = i; break; } } for (uint256 k = 0; k < tiers.length; k++) { if (!tiers[k].filledInOuter) { indexOuter = k; break; } } Tier storage tier; if (indexInner != 100000) { tier = tiers[indexInner]; availableInner = tier.amountInCenter.sub(tier.soldInCenter); priceInCenter = tier.priceInCenter; if (indexInner < 3) { nextPriceInCenter = tiers[indexInner + 1].priceInCenter; } } if (indexOuter != 100000) { tier = tiers[indexOuter]; availableInOuter = tier.amountInOuter.sub(tier.soldInOuter); priceInOuter = tier.priceInOuter; if (indexOuter < 3) { nextPriceInOuter = tiers[indexOuter + 1].priceInOuter; } } } function calculateAmountOfUnits(uint256 sizeA, uint256 sizeB) public pure returns (uint256) { return sizeA.mul(sizeB); } /// @notice approve the offer function approve(uint256 _index, uint256 _tokenId) internal { Offer memory localOffer = offers[_index]; address newOwner = localOffer.from; address prevOwner = token.getOwner(_tokenId); uint256 platformShare; uint256 forPrevOwner; uint256 soldPrice = token.getTokenSoldPrice(_tokenId); (platformShare, forPrevOwner) = pricingStrategy.calculateSharesInTheRevenue( soldPrice, localOffer.offeredPrice); //update token's state token.updateTokensState(_tokenId, localOffer.offeredPrice); // update owner token.updateOwner(_tokenId, newOwner, prevOwner); localOffer.accepted = true; transferEthers(platformWallet, platformShare); transferEthers(prevOwner, forPrevOwner.add(soldPrice)); emit OfferApproved(newOwner, _tokenId, localOffer.offerId, localOffer.offeredPrice, now); emit Purchased(prevOwner, newOwner, _tokenId, localOffer.offeredPrice, soldPrice, forPrevOwner.add(soldPrice), platformShare, now); afterApproveAction(_tokenId); } function transferEthers(address _address, uint256 _wei) internal { if (isContract(_address)) { pendingReturns[_address] = pendingReturns[_address].add(_wei); } else { _address.transfer(_wei); } } function preMinting(uint256 x, uint256 y, uint256 sizeA, uint256 sizeB) internal view returns (uint256, uint256) { // calculate units for token uint256 total = 0; uint256 inner = 0; uint256 outer = 0; (total, inner) = token.calculateCounters(x, y, sizeA, sizeB); outer = total.sub(inner); require(total <= 100); return (inner, outer); } function updateTierStatus(uint256 inner, uint256 outer) internal { uint256 leftInner = inner; uint256 leftOuter = outer; for (uint256 i = 0; i < 4; i++) { Tier storage tier = tiers[i]; if (leftInner > 0 && tier.filledInCenter == false) { uint256 availableInner = tier.amountInCenter.sub(tier.soldInCenter); if (availableInner > leftInner) { tier.soldInCenter = tier.soldInCenter.add(leftInner); leftInner = 0; } else { tier.filledInCenter = true; tier.soldInCenter = tier.amountInCenter; leftInner = leftInner.sub(availableInner); } } if (leftOuter > 0 && tier.filledInOuter == false) { uint256 availableOuter = tier.amountInOuter.sub(tier.soldInOuter); if (availableOuter > leftOuter) { tier.soldInOuter = tier.soldInOuter.add(leftOuter); leftOuter = 0; } else { tier.filledInOuter = true; tier.soldInOuter = tier.amountInOuter; leftOuter = leftOuter.sub(availableOuter); } } } require(leftInner == 0 && leftOuter == 0); } function calculateTokenPrice(uint256 inner, uint256 outer) public view returns (uint256 price) { uint256 leftInner = inner; uint256 leftOuter = outer; for (uint256 i = 0; i < 4; i++) { Tier storage tier = tiers[i]; if (leftInner > 0 && tier.filledInCenter == false) { uint256 availableInner = tier.amountInCenter.sub(tier.soldInCenter); if (availableInner > leftInner) { price = price.add(leftInner.mul(tier.priceInCenter)); leftInner = 0; } else { price = price.add(availableInner.mul(tier.priceInCenter)); leftInner = leftInner.sub(availableInner); } } if (leftOuter > 0 && tier.filledInOuter == false) { uint256 availableOuter = tier.amountInOuter.sub(tier.soldInOuter); if (availableOuter > leftOuter) { price = price.add(leftOuter.mul(tier.priceInOuter)); leftOuter = 0; } else { price = price.add(availableOuter.mul(tier.priceInOuter)); leftOuter = leftOuter.sub(availableOuter); } } } require(leftInner == 0 && leftOuter == 0); } function minPriceForNextRound(uint256 _tokenId) public view returns (uint256) { if (_tokenId == logoId && token.getCurrentPriceForToken(_tokenId) == 0) { return logoPrice; } else { // @TODO: check if sold-out uint256 currentPrice = getTokenPrice(_tokenId); uint256 minPrice = pricingStrategy.calculateMinPriceForNextRound(currentPrice, minResalePercentage); return minPrice; } } function afterApproveAction(uint256 _tokenId) internal { uint256 indexInner = 100000; uint256 indexOuter = 100000; bool hasInner; bool hasOuter; (hasInner, hasOuter) = token.getTokenScope(_tokenId); (indexInner, indexOuter) = getCurrentTierIndex(); if (hasInner && hasOuter && indexInner == 100000 && indexOuter == 100000) { token.increasePriceForNeighbours(_tokenId); } else if (!hasInner && hasOuter && indexOuter == 100000) { token.increasePriceForNeighbours(_tokenId); } else if (!hasOuter && hasInner && indexInner == 100000) { token.increasePriceForNeighbours(_tokenId); } } function canBuyExistentToken(uint256 _tokenId) public view returns (uint256 _allowed) { uint256 indexInner = 0; uint256 indexOuter = 0; bool hasInner; bool hasOuter; (hasInner, hasOuter) = token.getTokenScope(_tokenId); (indexInner, indexOuter) = getCurrentTierIndex(); if (token.getCurrentPriceForToken(_tokenId) == 0 && logoPrice == 0) { return 4; } if (_tokenId != logoId && hasInner && indexInner != 100000) { return 2; } if (hasOuter && indexOuter != 100000) { return 3; } return 1; } }
price that user paid to buy token
uint256 soldPrice;
461,962
[ 1, 4625, 348, 7953, 560, 30, 225, 6205, 716, 729, 30591, 358, 30143, 1147, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 272, 1673, 5147, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xb10ba7323c130D2865b37468e1daCA74d265312A/sources/contracts/_external/IERC20.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); }
15,931,146
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 6682, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 15105, 1435, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 203, 225, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 445, 7412, 1265, 12, 203, 565, 1758, 5793, 16, 203, 565, 1758, 8027, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 225, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../../../DS/DSMath.sol"; import "../../ActionBase.sol"; import "../../../utils/TokenUtils.sol"; import "./helpers/UniV3Helper.sol"; /// @title Collects tokensOwed from a position represented by tokenId contract UniCollectV3 is ActionBase, DSMath, UniV3Helper { using TokenUtils for address; /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { IUniswapV3NonfungiblePositionManager.CollectParams memory uniData = parseInputs(_callData); uniData.tokenId = _parseParamUint(uniData.tokenId, _paramMapping[0], _subData, _returnValues); (uint256 amount0, ) = _uniCollect(uniData); return bytes32(amount0); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable override { IUniswapV3NonfungiblePositionManager.CollectParams memory uniData = parseInputs(_callData); _uniCollect(uniData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @dev collects from tokensOwed on position, sends to recipient, up to amountMax /// @return amount0 sent to the recipient function _uniCollect(IUniswapV3NonfungiblePositionManager.CollectParams memory _uniData) internal returns ( uint256 amount0, uint256 amount1 ) { (amount0, amount1) = positionManager.collect(_uniData); logger.Log( address(this), msg.sender, "UniCollectV3", abi.encode(_uniData, amount0, amount1) ); } function parseInputs(bytes[] memory _callData) internal pure returns ( IUniswapV3NonfungiblePositionManager.CollectParams memory uniData ) { uniData = abi.decode(_callData[0], (IUniswapV3NonfungiblePositionManager.CollectParams)); } }
@inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable override { IUniswapV3NonfungiblePositionManager.CollectParams memory uniData = parseInputs(_callData); _uniCollect(uniData); }
1,039,764
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 10093, 4382, 2171, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 1803, 5368, 12, 3890, 8526, 3778, 389, 1991, 751, 13, 1071, 8843, 429, 3849, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 23, 3989, 12125, 75, 1523, 2555, 1318, 18, 10808, 1370, 3778, 7738, 751, 273, 1109, 10059, 24899, 1991, 751, 1769, 203, 540, 203, 3639, 389, 318, 77, 10808, 12, 318, 77, 751, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./AMM.sol"; import "../lib/CappedPool.sol"; import "../lib/CombinedActionsGuard.sol"; import "../interfaces/IPriceProvider.sol"; import "../interfaces/IIVProvider.sol"; import "../interfaces/IBlackScholes.sol"; import "../interfaces/IIVGuesser.sol"; import "../interfaces/IPodOption.sol"; import "../interfaces/IOptionAMMPool.sol"; import "../interfaces/IFeePool.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/IEmergencyStop.sol"; import "../interfaces/IFeePoolBuilder.sol"; import "../options/rewards/AaveIncentives.sol"; /** * Represents an Option specific single-sided AMM. * * The tokenA MUST be an PodOption contract implementation. * The tokenB is preferable to be an stable asset such as DAI or USDC. * * There are 4 external contracts used by this contract: * * - priceProvider: responsible for the the spot price of the option's underlying asset. * - priceMethod: responsible for the current price of the option itself. * - impliedVolatility: responsible for one of the priceMethod inputs: * implied Volatility * - feePoolA and feePoolB: responsible for handling Liquidity providers fees. */ contract OptionAMMPool is AMM, IOptionAMMPool, CappedPool, CombinedActionsGuard, ReentrancyGuard, AaveIncentives { using SafeMath for uint256; uint256 public constant PRICING_DECIMALS = 18; uint256 private constant _SECONDS_IN_A_YEAR = 31536000; uint256 private constant _ORACLE_IV_WEIGHT = 3; uint256 private constant _POOL_IV_WEIGHT = 1; // External Contracts /** * @notice store globally accessed configurations */ IConfigurationManager public immutable configurationManager; /** * @notice responsible for handling Liquidity providers fees of the token A */ IFeePool public immutable feePoolA; /** * @notice responsible for handling Liquidity providers fees of the token B */ IFeePool public immutable feePoolB; // Option Info struct PriceProperties { uint256 expiration; uint256 startOfExerciseWindow; uint256 strikePrice; address underlyingAsset; IPodOption.OptionType optionType; uint256 currentIV; int256 riskFree; uint256 initialIVGuess; } /** * @notice priceProperties are all information needed to handle the price discovery method * most of the properties will be used by getABPrice */ PriceProperties public priceProperties; event TradeInfo(uint256 spotPrice, uint256 newIV); constructor( address _optionAddress, address _stableAsset, uint256 _initialIV, IConfigurationManager _configurationManager, IFeePoolBuilder _feePoolBuilder ) public AMM(_optionAddress, _stableAsset) CappedPool(_configurationManager) AaveIncentives(_configurationManager) { require( IPodOption(_optionAddress).exerciseType() == IPodOption.ExerciseType.EUROPEAN, "Pool: invalid exercise type" ); feePoolA = _feePoolBuilder.buildFeePool(_stableAsset, 10, 3, address(this)); feePoolB = _feePoolBuilder.buildFeePool(_stableAsset, 10, 3, address(this)); priceProperties.currentIV = _initialIV; priceProperties.initialIVGuess = _initialIV; priceProperties.underlyingAsset = IPodOption(_optionAddress).underlyingAsset(); priceProperties.expiration = IPodOption(_optionAddress).expiration(); priceProperties.startOfExerciseWindow = IPodOption(_optionAddress).startOfExerciseWindow(); priceProperties.optionType = IPodOption(_optionAddress).optionType(); uint256 strikePrice = IPodOption(_optionAddress).strikePrice(); uint256 strikePriceDecimals = IPodOption(_optionAddress).strikePriceDecimals(); require(strikePriceDecimals <= PRICING_DECIMALS, "Pool: invalid strikePrice unit"); require(tokenBDecimals() <= PRICING_DECIMALS, "Pool: invalid tokenB unit"); uint256 strikePriceWithRightDecimals = strikePrice.mul(10**(PRICING_DECIMALS - strikePriceDecimals)); priceProperties.strikePrice = strikePriceWithRightDecimals; configurationManager = IConfigurationManager(_configurationManager); } /** * @notice addLiquidity in any proportion of tokenA or tokenB * * @dev This function can only be called before option expiration * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add * @param owner address of the account that will have ownership of the liquidity */ function addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) external override capped(tokenB(), amountOfB) { require(msg.sender == configurationManager.getOptionHelper() || msg.sender == owner, "AMM: invalid sender"); _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); _addLiquidity(amountOfA, amountOfB, owner); _emitTradeInfo(); } /** * @notice removeLiquidity in any proportion of tokenA or tokenB * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add */ function removeLiquidity(uint256 amountOfA, uint256 amountOfB) external override nonReentrant { _nonCombinedActions(); _emergencyStopCheck(); _removeLiquidity(amountOfA, amountOfB); _emitTradeInfo(); } /** * @notice withdrawRewards claims reward from Aave and send to admin * @dev should only be called by the admin power * */ function withdrawRewards() external override { require(msg.sender == configurationManager.owner(), "not owner"); address[] memory assets = new address[](1); assets[0] = this.tokenB(); _claimRewards(assets); address rewardAsset = _parseAddressFromUint(configurationManager.getParameter("REWARD_ASSET")); uint256 rewardsToSend = _rewardBalance(); IERC20(rewardAsset).safeTransfer(msg.sender, rewardsToSend); } /** * @notice tradeExactAInput msg.sender is able to trade exact amount of token A in exchange for minimum * amount of token B and send the tokens B to the owner. After that, this function also updates the * priceProperties.* currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result in less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactAInput first. * * @param exactAmountAIn exact amount of A token that will be transfer from msg.sender * @param minAmountBOut minimum acceptable amount of token B to transfer to owner * @param owner the destination address that will receive the token B * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountBOut = _tradeExactAInput(exactAmountAIn, minAmountBOut, owner); _emitTradeInfo(); return amountBOut; } /** * @notice _tradeExactAOutput owner is able to receive exact amount of token A in exchange of a max * acceptable amount of token B transfer from the msg.sender. After that, this function also updates * the priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result in less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactAOutput first. * * @param exactAmountAOut exact amount of token A that will be transfer to owner * @param maxAmountBIn maximum acceptable amount of token B to transfer from msg.sender * @param owner the destination address that will receive the token A * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountBIn = _tradeExactAOutput(exactAmountAOut, maxAmountBIn, owner); _emitTradeInfo(); return amountBIn; } /** * @notice _tradeExactBInput msg.sender is able to trade exact amount of token B in exchange for minimum * amount of token A sent to the owner. After that, this function also updates the priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result ini less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactBInput first. * * @param exactAmountBIn exact amount of token B that will be transfer from msg.sender * @param minAmountAOut minimum acceptable amount of token A to transfer to owner * @param owner the destination address that will receive the token A * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountAOut = _tradeExactBInput(exactAmountBIn, minAmountAOut, owner); _emitTradeInfo(); return amountAOut; } /** * @notice _tradeExactBOutput owner is able to receive exact amount of token B in exchange of a max * acceptable amount of token A transfer from msg.sender. After that, this function also updates the * priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result ini less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactBOutput first. * * @param exactAmountBOut exact amount of token B that will be transfer to owner * @param maxAmountAIn maximum acceptable amount of token A to transfer from msg.sender * @param owner the destination address that will receive the token B * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountAIn = _tradeExactBOutput(exactAmountBOut, maxAmountAIn, owner); _emitTradeInfo(); return amountAIn; } /** * @notice getRemoveLiquidityAmounts external function that returns the available for rescue * amounts of token A, and token B based on the original position * * @param percentA percent of exposition of Token A to be removed * @param percentB percent of exposition of Token B to be removed * @param user Opening Value Factor by the moment of the deposit * * @return withdrawAmountA the total amount of token A that will be rescued * @return withdrawAmountB the total amount of token B that will be rescued plus fees */ function getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) external override view returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { (uint256 poolWithdrawAmountA, uint256 poolWithdrawAmountB) = _getRemoveLiquidityAmounts( percentA, percentB, user ); (uint256 feeSharesA, uint256 feeSharesB) = _getAmountOfFeeShares(percentA, percentB, user); uint256 feesWithdrawAmountA = 0; uint256 feesWithdrawAmountB = 0; if (feeSharesA > 0) { (, feesWithdrawAmountA) = feePoolA.getWithdrawAmount(user, feeSharesA); } if (feeSharesB > 0) { (, feesWithdrawAmountB) = feePoolB.getWithdrawAmount(user, feeSharesB); } withdrawAmountA = poolWithdrawAmountA; withdrawAmountB = poolWithdrawAmountB.add(feesWithdrawAmountA).add(feesWithdrawAmountB); return (withdrawAmountA, withdrawAmountB); } /** * @notice getABPrice This function wll call internal function _getABPrice that will calculate the * calculate the ABPrice based on current market conditions. It calculates only the unit price AB, not taking in * consideration the slippage. * * @return ABPrice ABPrice is the unit price AB. Meaning how many units of B, buys 1 unit of A */ function getABPrice() external override view returns (uint256 ABPrice) { return _getABPrice(); } /** * @notice getAdjustedIV This function will return the adjustedIV, which is an average * between the pool IV and an external oracle IV * * @return adjustedIV The average between pool's IV and external oracle IV */ function getAdjustedIV() external override view returns (uint256 adjustedIV) { return _getAdjustedIV(tokenA(), priceProperties.currentIV); } /** * @notice getOptionTradeDetailsExactAInput view function that simulates a trade, in order the preview * the amountBOut, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountAIn amount of token A that will by transfer from msg.sender to the pool * * @return amountBOut amount of B in exchange of the exactAmountAIn * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) external override view returns ( uint256 amountBOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactAInput(exactAmountAIn); } /** * @notice getOptionTradeDetailsExactAOutput view function that simulates a trade, in order the preview * the amountBIn, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountAOut amount of token A that will by transfer from pool to the msg.sender/owner * * @return amountBIn amount of B that will be transfer from msg.sender to the pool * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) external override view returns ( uint256 amountBIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactAOutput(exactAmountAOut); } /** * @notice getOptionTradeDetailsExactBInput view function that simulates a trade, in order the preview * the amountAOut, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountBIn amount of token B that will by transfer from msg.sender to the pool * * @return amountAOut amount of A that will be transfer from contract to owner * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) external override view returns ( uint256 amountAOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactBInput(exactAmountBIn); } /** * @notice getOptionTradeDetailsExactBOutput view function that simulates a trade, in order the preview * the amountAIn, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountBOut amount of token B that will by transfer from pool to the msg.sender/owner * * @return amountAIn amount of A that will be transfer from msg.sender to the pool * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) external override view returns ( uint256 amountAIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactBOutput(exactAmountBOut); } function _getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 amountBOutPool = _getAmountBOutPool(exactAmountAIn, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, exactAmountAIn, amountBOutPool, TradeDirection.AB); // Prevents the pool to sell an option under the minimum target price, // because it causes an infinite loop when trying to calculate newIV if (!_isValidTargetPrice(newTargetABPrice, spotPrice)) { return (0, 0, 0, 0); } uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); uint256 feesTokenA = feePoolA.getCollectable(amountBOutPool, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(amountBOutPool, poolAmountB); uint256 amountBOutUser = amountBOutPool.sub(feesTokenA).sub(feesTokenB); return (amountBOutUser, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 amountBInPool = _getAmountBInPool(exactAmountAOut, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, exactAmountAOut, amountBInPool, TradeDirection.BA); uint256 feesTokenA = feePoolA.getCollectable(amountBInPool, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(amountBInPool, poolAmountB); uint256 amountBInUser = amountBInPool.add(feesTokenA).add(feesTokenB); uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountBInUser, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 feesTokenA = feePoolA.getCollectable(exactAmountBIn, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(exactAmountBIn, poolAmountB); uint256 totalFees = feesTokenA.add(feesTokenB); uint256 poolBIn = exactAmountBIn.sub(totalFees); uint256 amountAOutPool = _getAmountAOutPool(poolBIn, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, amountAOutPool, poolBIn, TradeDirection.BA); uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountAOutPool, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 feesTokenA = feePoolA.getCollectable(exactAmountBOut, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(exactAmountBOut, poolAmountB); uint256 totalFees = feesTokenA.add(feesTokenB); uint256 poolBOut = exactAmountBOut.add(totalFees); uint256 amountAInPool = _getAmountAInPool(poolBOut, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, amountAInPool, poolBOut, TradeDirection.AB); // Prevents the pool to sell an option under the minimum target price, // because it causes an infinite loop when trying to calculate newIV if (!_isValidTargetPrice(newTargetABPrice, spotPrice)) { return (0, 0, 0, 0); } uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountAInPool, newIV, feesTokenA, feesTokenB); } function _getPriceDetails() internal view returns ( uint256, uint256, uint256 ) { uint256 timeToMaturity = _getTimeToMaturityInYears(); if (timeToMaturity == 0) { return (0, 0, 0); } uint256 spotPrice = _getSpotPrice(priceProperties.underlyingAsset, PRICING_DECIMALS); uint256 adjustedIV = _getAdjustedIV(tokenA(), priceProperties.currentIV); IBlackScholes pricingMethod = IBlackScholes(configurationManager.getPricingMethod()); uint256 newABPrice; if (priceProperties.optionType == IPodOption.OptionType.PUT) { newABPrice = pricingMethod.getPutPrice( spotPrice, priceProperties.strikePrice, adjustedIV, timeToMaturity, priceProperties.riskFree ); } else { newABPrice = pricingMethod.getCallPrice( spotPrice, priceProperties.strikePrice, adjustedIV, timeToMaturity, priceProperties.riskFree ); } if (newABPrice == 0) { return (0, spotPrice, timeToMaturity); } uint256 newABPriceWithDecimals = newABPrice.div(10**(PRICING_DECIMALS.sub(tokenBDecimals()))); return (newABPriceWithDecimals, spotPrice, timeToMaturity); } /** * @dev returns maturity in years with 18 decimals */ function _getTimeToMaturityInYears() internal view returns (uint256) { if (block.timestamp >= priceProperties.expiration) { return 0; } return priceProperties.expiration.sub(block.timestamp).mul(10**PRICING_DECIMALS).div(_SECONDS_IN_A_YEAR); } function _getPoolAmounts(uint256 newABPrice) internal view returns (uint256 poolAmountA, uint256 poolAmountB) { (uint256 totalAmountA, uint256 totalAmountB) = _getPoolBalances(); if (newABPrice != 0) { poolAmountA = _min(totalAmountA, totalAmountB.mul(10**uint256(tokenADecimals())).div(newABPrice)); poolAmountB = _min(totalAmountB, totalAmountA.mul(newABPrice).div(10**uint256(tokenADecimals()))); } return (poolAmountA, poolAmountB); } function _getABPrice() internal override view returns (uint256) { (uint256 newABPrice, , ) = _getPriceDetails(); return newABPrice; } function _getSpotPrice(address asset, uint256 decimalsOutput) internal view returns (uint256) { IPriceProvider priceProvider = IPriceProvider(configurationManager.getPriceProvider()); uint256 spotPrice = priceProvider.getAssetPrice(asset); uint256 spotPriceDecimals = priceProvider.getAssetDecimals(asset); uint256 diffDecimals; uint256 spotPriceWithRightPrecision; if (decimalsOutput <= spotPriceDecimals) { diffDecimals = spotPriceDecimals.sub(decimalsOutput); spotPriceWithRightPrecision = spotPrice.div(10**diffDecimals); } else { diffDecimals = decimalsOutput.sub(spotPriceDecimals); spotPriceWithRightPrecision = spotPrice.mul(10**diffDecimals); } return spotPriceWithRightPrecision; } function _getOracleIV(address optionAddress) internal view returns (uint256 normalizedOracleIV) { IIVProvider ivProvider = IIVProvider(configurationManager.getIVProvider()); (, , uint256 oracleIV, uint256 ivDecimals) = ivProvider.getIV(optionAddress); uint256 diffDecimals; if (ivDecimals <= PRICING_DECIMALS) { diffDecimals = PRICING_DECIMALS.sub(ivDecimals); } else { diffDecimals = ivDecimals.sub(PRICING_DECIMALS); } return oracleIV.div(10**diffDecimals); } function _getAdjustedIV(address optionAddress, uint256 currentIV) internal view returns (uint256 adjustedIV) { uint256 oracleIV = _getOracleIV(optionAddress); adjustedIV = _ORACLE_IV_WEIGHT.mul(oracleIV).add(_POOL_IV_WEIGHT.mul(currentIV)).div( _POOL_IV_WEIGHT + _ORACLE_IV_WEIGHT ); } function _getNewIV( uint256 newTargetABPrice, uint256 spotPrice, uint256 timeToMaturity ) internal view returns (uint256) { uint256 newTargetABPriceWithDecimals = newTargetABPrice.mul(10**(PRICING_DECIMALS.sub(tokenBDecimals()))); uint256 newIV; IIVGuesser ivGuesser = IIVGuesser(configurationManager.getIVGuesser()); if (priceProperties.optionType == IPodOption.OptionType.PUT) { (newIV, ) = ivGuesser.getPutIV( newTargetABPriceWithDecimals, priceProperties.initialIVGuess, spotPrice, priceProperties.strikePrice, timeToMaturity, priceProperties.riskFree ); } else { (newIV, ) = ivGuesser.getCallIV( newTargetABPriceWithDecimals, priceProperties.initialIVGuess, spotPrice, priceProperties.strikePrice, timeToMaturity, priceProperties.riskFree ); } return newIV; } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountBOutPool The exact amount of tokenB will leave the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountAInPool The amount of tokenA(options) will enter the pool */ function _getAmountAInPool( uint256 amountBOutPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountAInPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); require(amountBOutPool < poolAmountB, "AMM: insufficient liquidity"); amountAInPool = productConstant.div(poolAmountB.sub(amountBOutPool)).sub(poolAmountA); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountBInPool The exact amount of tokenB will enter the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountAOutPool The amount of tokenA(options) will leave the pool */ function _getAmountAOutPool( uint256 amountBInPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountAOutPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); amountAOutPool = poolAmountA.sub(productConstant.div(poolAmountB.add(amountBInPool))); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountAOutPool The amount of tokenA(options) will leave the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountBInPool The amount of tokenB will enter the pool */ function _getAmountBInPool( uint256 amountAOutPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountBInPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); require(amountAOutPool < poolAmountA, "AMM: insufficient liquidity"); amountBInPool = productConstant.div(poolAmountA.sub(amountAOutPool)).sub(poolAmountB); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountAInPool The exact amount of tokenA(options) will enter the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountBOutPool The amount of tokenB will leave the pool */ function _getAmountBOutPool( uint256 amountAInPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountBOutPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); amountBOutPool = poolAmountB.sub(productConstant.div(poolAmountA.add(amountAInPool))); } /** * @dev Based on the tokensA and tokensB leaving or entering the pool, it is possible to calculate the new option * target price. That price will be used later to update the currentIV. * @param newABPrice calculated Black Scholes unit price (how many units of tokenB, to buy 1 tokenA(option)) * @param amountA The amount of tokenA that will leave or enter the pool * @param amountB TThe amount of tokenB that will leave or enter the pool * @param tradeDirection The trade direction, if it is AB, means that tokenA will enter, and tokenB will leave. * @return newTargetPrice The new unit target price (how many units of tokenB, to buy 1 tokenA(option)) */ function _getNewTargetPrice( uint256 newABPrice, uint256 amountA, uint256 amountB, TradeDirection tradeDirection ) internal view returns (uint256 newTargetPrice) { (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); if (tradeDirection == TradeDirection.AB) { newTargetPrice = poolAmountB.sub(amountB).mul(10**uint256(tokenADecimals())).div(poolAmountA.add(amountA)); } else { newTargetPrice = poolAmountB.add(amountB).mul(10**uint256(tokenADecimals())).div(poolAmountA.sub(amountA)); } } function _getTradeDetailsExactAInput(uint256 exactAmountAIn) internal override returns (TradeDetails memory) { (uint256 amountBOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactAInput( exactAmountAIn ); TradeDetails memory tradeDetails = TradeDetails(amountBOut, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactAOutput(uint256 exactAmountAOut) internal override returns (TradeDetails memory) { (uint256 amountBIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactAOutput( exactAmountAOut ); TradeDetails memory tradeDetails = TradeDetails(amountBIn, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactBInput(uint256 exactAmountBIn) internal override returns (TradeDetails memory) { (uint256 amountAOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactBInput( exactAmountBIn ); TradeDetails memory tradeDetails = TradeDetails(amountAOut, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactBOutput(uint256 exactAmountBOut) internal override returns (TradeDetails memory) { (uint256 amountAIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactBOutput( exactAmountBOut ); TradeDetails memory tradeDetails = TradeDetails(amountAIn, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } /** * @dev If a option is ITM, either PUTs or CALLs, the minimum price that it would cost is the difference between * the spot price and strike price. If the target price after applying slippage is above this minimum, the function * returns true. * @param newTargetPrice the new ABPrice after slippage (how many units of tokenB, to buy 1 option) * @param spotPrice current underlying asset spot price during this transaction * @return true if is a valid target price (above the minimum) */ function _isValidTargetPrice(uint256 newTargetPrice, uint256 spotPrice) internal view returns (bool) { if (priceProperties.optionType == IPodOption.OptionType.PUT) { if (spotPrice < priceProperties.strikePrice) { return newTargetPrice > priceProperties.strikePrice.sub(spotPrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } } else { if (spotPrice > priceProperties.strikePrice) { return newTargetPrice > spotPrice.sub(priceProperties.strikePrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } } return true; } function _onAddLiquidity(UserDepositSnapshot memory _userDepositSnapshot, address owner) internal override { uint256 currentQuotesA = feePoolA.sharesOf(owner); uint256 currentQuotesB = feePoolB.sharesOf(owner); uint256 amountOfQuotesAToAdd = 0; uint256 amountOfQuotesBToAdd = 0; uint256 totalQuotesA = _userDepositSnapshot.tokenABalance.mul(10**FIMP_DECIMALS).div(_userDepositSnapshot.fImp); if (totalQuotesA > currentQuotesA) { amountOfQuotesAToAdd = totalQuotesA.sub(currentQuotesA); } uint256 totalQuotesB = _userDepositSnapshot.tokenBBalance.mul(10**FIMP_DECIMALS).div(_userDepositSnapshot.fImp); if (totalQuotesB > currentQuotesB) { amountOfQuotesBToAdd = totalQuotesB.sub(currentQuotesB); } feePoolA.mint(owner, amountOfQuotesAToAdd); feePoolB.mint(owner, amountOfQuotesBToAdd); } function _onRemoveLiquidity( uint256 percentA, uint256 percentB, address owner ) internal override { (uint256 amountOfSharesAToRemove, uint256 amountOfSharesBToRemove) = _getAmountOfFeeShares( percentA, percentB, owner ); if (amountOfSharesAToRemove > 0) { feePoolA.withdraw(owner, amountOfSharesAToRemove); } if (amountOfSharesBToRemove > 0) { feePoolB.withdraw(owner, amountOfSharesBToRemove); } } function _getAmountOfFeeShares( uint256 percentA, uint256 percentB, address owner ) internal view returns (uint256, uint256) { uint256 currentSharesA = feePoolA.sharesOf(owner); uint256 currentSharesB = feePoolB.sharesOf(owner); uint256 amountOfSharesAToRemove = currentSharesA.mul(percentA).div(PERCENT_PRECISION); uint256 amountOfSharesBToRemove = currentSharesB.mul(percentB).div(PERCENT_PRECISION); return (amountOfSharesAToRemove, amountOfSharesBToRemove); } function _onTrade(TradeDetails memory tradeDetails) internal override { uint256 newIV = abi.decode(tradeDetails.params, (uint256)); priceProperties.currentIV = newIV; IERC20(tokenB()).safeTransfer(address(feePoolA), tradeDetails.feesTokenA); IERC20(tokenB()).safeTransfer(address(feePoolB), tradeDetails.feesTokenB); } /** * @dev Check for functions which are only allowed to be executed * BEFORE start of exercise window. */ function _beforeStartOfExerciseWindow() internal view { require(block.timestamp < priceProperties.startOfExerciseWindow, "Pool: exercise window has started"); } function _emergencyStopCheck() private view { IEmergencyStop emergencyStop = IEmergencyStop(configurationManager.getEmergencyStop()); require( !emergencyStop.isStopped(address(this)) && !emergencyStop.isStopped(configurationManager.getPriceProvider()) && !emergencyStop.isStopped(configurationManager.getPricingMethod()), "Pool: Pool is stopped" ); } function _emitTradeInfo() private { uint256 spotPrice = _getSpotPrice(priceProperties.underlyingAsset, PRICING_DECIMALS); emit TradeInfo(spotPrice, priceProperties.currentIV); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../lib/RequiredDecimals.sol"; import "../interfaces/IAMM.sol"; /** * Represents a generalized contract for a single-sided AMM pair. * * That means is possible to add and remove liquidity in any proportion * at any time, even 0 in one of the sides. * * The AMM is constituted by 3 core functions: Add Liquidity, Remove liquidity and Trade. * * There are 4 possible trade types between the token pair (tokenA and tokenB): * * - ExactAInput: * tokenA as an exact Input, meaning that the output tokenB is variable. * it is important to have a slippage control of the minimum acceptable amount of tokenB in return * - ExactAOutput: * tokenA as an exact Output, meaning that the input tokenB is variable. * it is important to have a slippage control of the maximum acceptable amount of tokenB sent * - ExactBInput: * tokenB as an exact Input, meaning that the output tokenA is variable. * it is important to have a slippage control of the minimum acceptable amount of tokenA in return * - ExactBOutput: * tokenB as an exact Output, meaning that the input tokenA is variable. * it is important to have a slippage control of the maximum acceptable amount of tokenA sent * * Several functions are provided as virtual and must be overridden by the inheritor. * * - _getABPrice: * function that will return the tokenA:tokenB price relation. * How many units of tokenB in order to traded for 1 unit of tokenA. * This price is represented in the same tokenB number of decimals. * - _onAddLiquidity: * Executed after adding liquidity. Usually used for handling fees * - _onRemoveLiquidity: * Executed after removing liquidity. Usually used for handling fees * * Also, for which TradeType (E.g: ExactAInput) there are more two functions to override: * _getTradeDetails[$TradeType]: * This function is responsible to return the TradeDetails struct, that contains basically the amount * of the other token depending on the trade type. (E.g: ExactAInput => The TradeDetails will return the * amount of B output). * _onTrade[$TradeType]: * function that will be executed after UserDepositSnapshot updates and before * token transfers. Usually used for handling fees and updating state at the inheritor. * */ abstract contract AMM is IAMM, RequiredDecimals { using SafeERC20 for IERC20; using SafeMath for uint256; /** * @dev The initial value for deposit factor (Fimp) */ uint256 public constant INITIAL_FIMP = 10**27; /** * @notice The Fimp's precision (aka number of decimals) */ uint256 public constant FIMP_DECIMALS = 27; /** * @notice The percent's precision */ uint256 public constant PERCENT_PRECISION = 100; /** * @dev Address of the token A */ address private _tokenA; /** * @dev Address of the token B */ address private _tokenB; /** * @dev Token A number of decimals */ uint8 private _tokenADecimals; /** * @dev Token B number of decimals */ uint8 private _tokenBDecimals; /** * @notice The total balance of token A in the pool not counting the amortization */ uint256 public deamortizedTokenABalance; /** * @notice The total balance of token B in the pool not counting the amortization */ uint256 public deamortizedTokenBBalance; /** * @notice It contains the token A original balance, token B original balance, * and the Open Value Factor (Fimp) at the time of the deposit. */ struct UserDepositSnapshot { uint256 tokenABalance; uint256 tokenBBalance; uint256 fImp; } struct Mult { uint256 AA; // How much A Im getting for rescuing one A that i've deposited uint256 AB; // How much B Im getting for rescuing one A that i've deposited uint256 BA; // How much A Im getting for rescuing one B that i've deposited uint256 BB; // How much B Im getting for rescuing one B that i've deposited } struct TradeDetails { uint256 amount; uint256 feesTokenA; uint256 feesTokenB; bytes params; } /** * @dev Tracks the UserDepositSnapshot struct of each user. * It contains the token A original balance, token B original balance, * and the Open Value Factor (Fimp) at the time of the deposit. */ mapping(address => UserDepositSnapshot) private _userSnapshots; /** Events */ event AddLiquidity(address indexed caller, address indexed owner, uint256 amountA, uint256 amountB); event RemoveLiquidity(address indexed caller, uint256 amountA, uint256 amountB); event TradeExactAInput(address indexed caller, address indexed owner, uint256 exactAmountAIn, uint256 amountBOut); event TradeExactBInput(address indexed caller, address indexed owner, uint256 exactAmountBIn, uint256 amountAOut); event TradeExactAOutput(address indexed caller, address indexed owner, uint256 amountBIn, uint256 exactAmountAOut); event TradeExactBOutput(address indexed caller, address indexed owner, uint256 amountAIn, uint256 exactAmountBOut); constructor(address tokenA, address tokenB) public { require(Address.isContract(tokenA), "AMM: token a is not a contract"); require(Address.isContract(tokenB), "AMM: token b is not a contract"); require(tokenA != tokenB, "AMM: tokens must differ"); _tokenA = tokenA; _tokenB = tokenB; _tokenADecimals = tryDecimals(IERC20(tokenA)); _tokenBDecimals = tryDecimals(IERC20(tokenB)); } /** * @dev Returns the address for tokenA */ function tokenA() public override view returns (address) { return _tokenA; } /** * @dev Returns the address for tokenB */ function tokenB() public override view returns (address) { return _tokenB; } /** * @dev Returns the decimals for tokenA */ function tokenADecimals() public override view returns (uint8) { return _tokenADecimals; } /** * @dev Returns the decimals for tokenB */ function tokenBDecimals() public override view returns (uint8) { return _tokenBDecimals; } /** * @notice getPoolBalances external function that returns the current pool balance of token A and token B * * @return totalTokenA balanceOf this contract of token A * @return totalTokenB balanceOf this contract of token B */ function getPoolBalances() external view returns (uint256 totalTokenA, uint256 totalTokenB) { return _getPoolBalances(); } /** * @notice getUserDepositSnapshot external function that User original balance of token A, * token B and the Opening Value * * Factor (Fimp) at the moment of the liquidity added * * @param user address to check the balance info * * @return tokenAOriginalBalance balance of token A by the moment of deposit * @return tokenBOriginalBalance balance of token B by the moment of deposit * @return fImpUser value of the Opening Value Factor by the moment of the deposit */ function getUserDepositSnapshot(address user) external view returns ( uint256 tokenAOriginalBalance, uint256 tokenBOriginalBalance, uint256 fImpUser ) { return _getUserDepositSnapshot(user); } /** * @notice _addLiquidity in any proportion of tokenA or tokenB * * @dev The inheritor contract should implement _getABPrice and _onAddLiquidity functions * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add * @param owner address of the account that will have ownership of the liquidity */ function _addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) internal { _isValidAddress(owner); // Get Pool Balances (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); bool hasNoLiquidity = deamortizedTokenABalance == 0 && deamortizedTokenBBalance == 0; uint256 fImpOpening; uint256 userAmountToStoreTokenA = amountOfA; uint256 userAmountToStoreTokenB = amountOfB; if (hasNoLiquidity) { // In the first liquidity, is necessary add both tokens bool bothTokensHigherThanZero = amountOfA > 0 && amountOfB > 0; require(bothTokensHigherThanZero, "AMM: invalid first liquidity"); fImpOpening = INITIAL_FIMP; deamortizedTokenABalance = amountOfA; deamortizedTokenBBalance = amountOfB; } else { // Get ABPrice uint256 ABPrice = _getABPrice(); require(ABPrice > 0, "AMM: option price zero"); // Calculate the Pool's Value Factor (Fimp) fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); (userAmountToStoreTokenA, userAmountToStoreTokenB) = _getUserBalanceToStore( amountOfA, amountOfB, fImpOpening, _userSnapshots[owner] ); // Update Deamortized Balance of the pool for each token; deamortizedTokenABalance = deamortizedTokenABalance.add(amountOfA.mul(10**FIMP_DECIMALS).div(fImpOpening)); deamortizedTokenBBalance = deamortizedTokenBBalance.add(amountOfB.mul(10**FIMP_DECIMALS).div(fImpOpening)); } // Update the User Balances for each token and with the Pool Factor previously calculated UserDepositSnapshot memory userDepositSnapshot = UserDepositSnapshot( userAmountToStoreTokenA, userAmountToStoreTokenB, fImpOpening ); _userSnapshots[owner] = userDepositSnapshot; _onAddLiquidity(_userSnapshots[owner], owner); // Update Total Balance of the pool for each token if (amountOfA > 0) { IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), amountOfA); } if (amountOfB > 0) { IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), amountOfB); } emit AddLiquidity(msg.sender, owner, amountOfA, amountOfB); } /** * @notice _removeLiquidity in any proportion of tokenA or tokenB * @dev The inheritor contract should implement _getABPrice and _onRemoveLiquidity functions * * @param percentA proportion of the exposition of the original tokenA that want to be removed * @param percentB proportion of the exposition of the original tokenB that want to be removed */ function _removeLiquidity(uint256 percentA, uint256 percentB) internal { (uint256 userTokenABalance, uint256 userTokenBBalance, uint256 userFImp) = _getUserDepositSnapshot(msg.sender); require(percentA <= 100 && percentB <= 100, "AMM: forbidden percent"); uint256 originalBalanceAToReduce = percentA.mul(userTokenABalance).div(PERCENT_PRECISION); uint256 originalBalanceBToReduce = percentB.mul(userTokenBBalance).div(PERCENT_PRECISION); // Get Pool Balances (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); // Get ABPrice uint256 ABPrice = _getABPrice(); // Calculate the Pool's Value Factor (Fimp) uint256 fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); // Calculate Multipliers Mult memory multipliers = _getMultipliers(totalTokenA, totalTokenB, fImpOpening); // Update User balance _userSnapshots[msg.sender].tokenABalance = userTokenABalance.sub(originalBalanceAToReduce); _userSnapshots[msg.sender].tokenBBalance = userTokenBBalance.sub(originalBalanceBToReduce); // Update deamortized balance deamortizedTokenABalance = deamortizedTokenABalance.sub( originalBalanceAToReduce.mul(10**FIMP_DECIMALS).div(userFImp) ); deamortizedTokenBBalance = deamortizedTokenBBalance.sub( originalBalanceBToReduce.mul(10**FIMP_DECIMALS).div(userFImp) ); // Calculate amount to send (uint256 withdrawAmountA, uint256 withdrawAmountB) = _getWithdrawAmounts( originalBalanceAToReduce, originalBalanceBToReduce, userFImp, multipliers ); if (withdrawAmountA > totalTokenA) { withdrawAmountA = totalTokenA; } if (withdrawAmountB > totalTokenB) { withdrawAmountB = totalTokenB; } _onRemoveLiquidity(percentA, percentB, msg.sender); // Transfers / Update if (withdrawAmountA > 0) { IERC20(_tokenA).safeTransfer(msg.sender, withdrawAmountA); } if (withdrawAmountB > 0) { IERC20(_tokenB).safeTransfer(msg.sender, withdrawAmountB); } emit RemoveLiquidity(msg.sender, withdrawAmountA, withdrawAmountB); } /** * @notice _tradeExactAInput msg.sender is able to trade exact amount of token A in exchange for minimum * amount of token B sent by the contract to the owner * @dev The inheritor contract should implement _getTradeDetailsExactAInput and _onTradeExactAInput functions * _getTradeDetailsExactAInput should return tradeDetails struct format * * @param exactAmountAIn exact amount of A token that will be transfer from msg.sender * @param minAmountBOut minimum acceptable amount of token B to transfer to owner * @param owner the destination address that will receive the token B */ function _tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner ) internal returns (uint256) { _isValidInput(exactAmountAIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactAInput(exactAmountAIn); uint256 amountBOut = tradeDetails.amount; require(amountBOut > 0, "AMM: invalid amountBOut"); require(amountBOut >= minAmountBOut, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), exactAmountAIn); IERC20(_tokenB).safeTransfer(owner, amountBOut); emit TradeExactAInput(msg.sender, owner, exactAmountAIn, amountBOut); return amountBOut; } /** * @notice _tradeExactAOutput owner is able to receive exact amount of token A in exchange of a max * acceptable amount of token B sent by the msg.sender to the contract * * @dev The inheritor contract should implement _getTradeDetailsExactAOutput and _onTradeExactAOutput functions * _getTradeDetailsExactAOutput should return tradeDetails struct format * * @param exactAmountAOut exact amount of token A that will be transfer to owner * @param maxAmountBIn maximum acceptable amount of token B to transfer from msg.sender * @param owner the destination address that will receive the token A */ function _tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner ) internal returns (uint256) { _isValidInput(maxAmountBIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactAOutput(exactAmountAOut); uint256 amountBIn = tradeDetails.amount; require(amountBIn > 0, "AMM: invalid amountBIn"); require(amountBIn <= maxAmountBIn, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), amountBIn); IERC20(_tokenA).safeTransfer(owner, exactAmountAOut); emit TradeExactAOutput(msg.sender, owner, amountBIn, exactAmountAOut); return amountBIn; } /** * @notice _tradeExactBInput msg.sender is able to trade exact amount of token B in exchange for minimum * amount of token A sent by the contract to the owner * * @dev The inheritor contract should implement _getTradeDetailsExactBInput and _onTradeExactBInput functions * _getTradeDetailsExactBInput should return tradeDetails struct format * * @param exactAmountBIn exact amount of token B that will be transfer from msg.sender * @param minAmountAOut minimum acceptable amount of token A to transfer to owner * @param owner the destination address that will receive the token A */ function _tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner ) internal returns (uint256) { _isValidInput(exactAmountBIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactBInput(exactAmountBIn); uint256 amountAOut = tradeDetails.amount; require(amountAOut > 0, "AMM: invalid amountAOut"); require(amountAOut >= minAmountAOut, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), exactAmountBIn); IERC20(_tokenA).safeTransfer(owner, amountAOut); emit TradeExactBInput(msg.sender, owner, exactAmountBIn, amountAOut); return amountAOut; } /** * @notice _tradeExactBOutput owner is able to receive exact amount of token B from the contract in exchange of a * max acceptable amount of token A sent by the msg.sender to the contract. * * @dev The inheritor contract should implement _getTradeDetailsExactBOutput and _onTradeExactBOutput functions * _getTradeDetailsExactBOutput should return tradeDetails struct format * * @param exactAmountBOut exact amount of token B that will be transfer to owner * @param maxAmountAIn maximum acceptable amount of token A to transfer from msg.sender * @param owner the destination address that will receive the token B */ function _tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner ) internal returns (uint256) { _isValidInput(maxAmountAIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactBOutput(exactAmountBOut); uint256 amountAIn = tradeDetails.amount; require(amountAIn > 0, "AMM: invalid amountAIn"); require(amountAIn <= maxAmountAIn, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), amountAIn); IERC20(_tokenB).safeTransfer(owner, exactAmountBOut); emit TradeExactBOutput(msg.sender, owner, amountAIn, exactAmountBOut); return amountAIn; } /** * @notice _getFImpOpening Auxiliary function that calculate the Opening Value Factor Fimp * * @param _totalTokenA total contract balance of token A * @param _totalTokenB total contract balance of token B * @param _ABPrice Unit price AB, meaning, how many units of token B could buy 1 unit of token A * @param _deamortizedTokenABalance contract deamortized balance of token A * @param _deamortizedTokenBBalance contract deamortized balance of token B * @return fImpOpening Opening Value Factor Fimp */ function _getFImpOpening( uint256 _totalTokenA, uint256 _totalTokenB, uint256 _ABPrice, uint256 _deamortizedTokenABalance, uint256 _deamortizedTokenBBalance ) internal view returns (uint256) { uint256 numerator; uint256 denominator; { numerator = _totalTokenA.mul(_ABPrice).div(10**uint256(_tokenADecimals)).add(_totalTokenB).mul( 10**FIMP_DECIMALS ); } { denominator = _deamortizedTokenABalance.mul(_ABPrice).div(10**uint256(_tokenADecimals)).add( _deamortizedTokenBBalance ); } return numerator.div(denominator); } /** * @notice _getPoolBalances external function that returns the current pool balance of token A and token B * * @return totalTokenA balanceOf this contract of token A * @return totalTokenB balanceOf this contract of token B */ function _getPoolBalances() internal view returns (uint256 totalTokenA, uint256 totalTokenB) { totalTokenA = IERC20(_tokenA).balanceOf(address(this)); totalTokenB = IERC20(_tokenB).balanceOf(address(this)); } /** * @notice _getUserDepositSnapshot internal function that User original balance of token A, * token B and the Opening Value * * Factor (Fimp) at the moment of the liquidity added * * @param user address of the user that want to check the balance * * @return tokenAOriginalBalance balance of token A by the moment of deposit * @return tokenBOriginalBalance balance of token B by the moment of deposit * @return fImpOriginal value of the Opening Value Factor by the moment of the deposit */ function _getUserDepositSnapshot(address user) internal view returns ( uint256 tokenAOriginalBalance, uint256 tokenBOriginalBalance, uint256 fImpOriginal ) { tokenAOriginalBalance = _userSnapshots[user].tokenABalance; tokenBOriginalBalance = _userSnapshots[user].tokenBBalance; fImpOriginal = _userSnapshots[user].fImp; } /** * @notice _getMultipliers internal function that calculate new multipliers based on the current pool position * * mAA => How much A the users can rescue for each A they deposited * mBA => How much A the users can rescue for each B they deposited * mBB => How much B the users can rescue for each B they deposited * mAB => How much B the users can rescue for each A they deposited * * @param totalTokenA balanceOf this contract of token A * @param totalTokenB balanceOf this contract of token B * @param fImpOpening current Open Value Factor * @return multipliers multiplier struct containing the 4 multipliers: mAA, mBA, mBB, mAB */ function _getMultipliers( uint256 totalTokenA, uint256 totalTokenB, uint256 fImpOpening ) internal view returns (Mult memory multipliers) { uint256 totalTokenAWithPrecision = totalTokenA.mul(10**FIMP_DECIMALS); uint256 totalTokenBWithPrecision = totalTokenB.mul(10**FIMP_DECIMALS); uint256 mAA = 0; uint256 mBB = 0; uint256 mAB = 0; uint256 mBA = 0; if (deamortizedTokenABalance > 0) { mAA = (_min(deamortizedTokenABalance.mul(fImpOpening), totalTokenAWithPrecision)).div( deamortizedTokenABalance ); } if (deamortizedTokenBBalance > 0) { mBB = (_min(deamortizedTokenBBalance.mul(fImpOpening), totalTokenBWithPrecision)).div( deamortizedTokenBBalance ); } if (mAA > 0) { mAB = totalTokenBWithPrecision.sub(mBB.mul(deamortizedTokenBBalance)).div(deamortizedTokenABalance); } if (mBB > 0) { mBA = totalTokenAWithPrecision.sub(mAA.mul(deamortizedTokenABalance)).div(deamortizedTokenBBalance); } multipliers = Mult(mAA, mAB, mBA, mBB); } /** * @notice _getRemoveLiquidityAmounts internal function of getRemoveLiquidityAmounts * * @param percentA percent of exposition A to be removed * @param percentB percent of exposition B to be removed * @param user address of the account that will be removed * * @return withdrawAmountA amount of token A that will be rescued * @return withdrawAmountB amount of token B that will be rescued */ function _getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) internal view returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); (uint256 originalBalanceTokenA, uint256 originalBalanceTokenB, uint256 fImpOriginal) = _getUserDepositSnapshot( user ); uint256 originalBalanceAToReduce = percentA.mul(originalBalanceTokenA).div(PERCENT_PRECISION); uint256 originalBalanceBToReduce = percentB.mul(originalBalanceTokenB).div(PERCENT_PRECISION); bool hasNoLiquidity = totalTokenA == 0 && totalTokenB == 0; if (hasNoLiquidity) { return (0, 0); } uint256 ABPrice = _getABPrice(); uint256 fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); Mult memory multipliers = _getMultipliers(totalTokenA, totalTokenB, fImpOpening); (withdrawAmountA, withdrawAmountB) = _getWithdrawAmounts( originalBalanceAToReduce, originalBalanceBToReduce, fImpOriginal, multipliers ); } /** * @notice _getWithdrawAmounts internal function of getRemoveLiquidityAmounts * * @param _originalBalanceAToReduce amount of original deposit of the token A * @param _originalBalanceBToReduce amount of original deposit of the token B * @param _userFImp Opening Value Factor by the moment of the deposit * * @return withdrawAmountA amount of token A that will be rescued * @return withdrawAmountB amount of token B that will be rescued */ function _getWithdrawAmounts( uint256 _originalBalanceAToReduce, uint256 _originalBalanceBToReduce, uint256 _userFImp, Mult memory multipliers ) internal pure returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { if (_userFImp > 0) { withdrawAmountA = _originalBalanceAToReduce .mul(multipliers.AA) .add(_originalBalanceBToReduce.mul(multipliers.BA)) .div(_userFImp); withdrawAmountB = _originalBalanceBToReduce .mul(multipliers.BB) .add(_originalBalanceAToReduce.mul(multipliers.AB)) .div(_userFImp); } return (withdrawAmountA, withdrawAmountB); } /** * @notice _getUserBalanceToStore internal auxiliary function to help calculation the * tokenA and tokenB value that should be stored in UserDepositSnapshot struct * * @param amountOfA current deposit of the token A * @param amountOfB current deposit of the token B * @param fImpOpening Opening Value Factor by the moment of the deposit * * @return userToStoreTokenA amount of token A that will be stored * @return userToStoreTokenB amount of token B that will be stored */ function _getUserBalanceToStore( uint256 amountOfA, uint256 amountOfB, uint256 fImpOpening, UserDepositSnapshot memory userDepositSnapshot ) internal pure returns (uint256 userToStoreTokenA, uint256 userToStoreTokenB) { userToStoreTokenA = amountOfA; userToStoreTokenB = amountOfB; //Re-add Liquidity case if (userDepositSnapshot.fImp != 0) { userToStoreTokenA = userDepositSnapshot.tokenABalance.mul(fImpOpening).div(userDepositSnapshot.fImp).add( amountOfA ); userToStoreTokenB = userDepositSnapshot.tokenBBalance.mul(fImpOpening).div(userDepositSnapshot.fImp).add( amountOfB ); } } /** * @dev Returns the smallest of two numbers. */ function _min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function _getABPrice() internal virtual view returns (uint256 ABPrice); function _getTradeDetailsExactAInput(uint256 amountAIn) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactAOutput(uint256 amountAOut) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactBInput(uint256 amountBIn) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactBOutput(uint256 amountBOut) internal virtual returns (TradeDetails memory); function _onTrade(TradeDetails memory tradeDetails) internal virtual; function _onRemoveLiquidity( uint256 percentA, uint256 percentB, address owner ) internal virtual; function _onAddLiquidity(UserDepositSnapshot memory userDepositSnapshot, address owner) internal virtual; function _isValidAddress(address recipient) private pure { require(recipient != address(0), "AMM: transfer to zero address"); } function _isValidInput(uint256 input) private pure { require(input > 0, "AMM: input should be greater than zero"); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/ICapProvider.sol"; /** * @title CappedPool * @author Pods Finance * * @notice Controls a maximum cap for a guarded release */ abstract contract CappedPool { using SafeMath for uint256; IConfigurationManager private immutable _configurationManager; constructor(IConfigurationManager configurationManager) public { _configurationManager = configurationManager; } /** * @dev Modifier to stop transactions that exceed the cap */ modifier capped(address token, uint256 amountOfLiquidity) { uint256 cap = capSize(); if (cap > 0) { uint256 poolBalance = IERC20(token).balanceOf(address(this)); require(poolBalance.add(amountOfLiquidity) <= cap, "CappedPool: amount exceed cap"); } _; } /** * @dev Get the cap size */ function capSize() public view returns (uint256) { ICapProvider capProvider = ICapProvider(_configurationManager.getCapProvider()); return capProvider.getCap(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; contract CombinedActionsGuard { mapping(address => uint256) sessions; /** * @dev Prevents an address from calling more than one function that contains this * function in the same block */ function _nonCombinedActions() internal { require(sessions[tx.origin] != block.number, "CombinedActionsGuard: reentrant call"); sessions[tx.origin] = block.number; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IPriceProvider { function setAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function updateAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function removeAssetFeeds(address[] memory _assets) external; function getAssetPrice(address _asset) external view returns (uint256); function getAssetDecimals(address _asset) external view returns (uint8); function latestRoundData(address _asset) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getPriceFeed(address _asset) external view returns (address); function updateMinUpdateInterval() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IIVProvider { struct IVData { uint256 roundId; uint256 updatedAt; uint256 answer; uint8 decimals; } event UpdatedIV(address indexed option, uint256 roundId, uint256 updatedAt, uint256 answer, uint8 decimals); event UpdaterSet(address indexed admin, address indexed updater); function getIV(address option) external view returns ( uint256 roundId, uint256 updatedAt, uint256 answer, uint8 decimals ); function updateIV( address option, uint256 answer, uint8 decimals ) external; function setUpdater(address updater) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IBlackScholes { function getCallPrice( uint256 spotPrice, uint256 strikePrice, uint256 sigma, uint256 time, int256 riskFree ) external view returns (uint256); function getPutPrice( uint256 spotPrice, uint256 strikePrice, uint256 sigma, uint256 time, int256 riskFree ) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IIVGuesser { function blackScholes() external view returns (address); function getPutIV( uint256 _targetPrice, uint256 _initialIVGuess, uint256 _spotPrice, uint256 _strikePrice, uint256 _timeToMaturity, int256 _riskFree ) external view returns (uint256, uint256); function getCallIV( uint256 _targetPrice, uint256 _initialIVGuess, uint256 _spotPrice, uint256 _strikePrice, uint256 _timeToMaturity, int256 _riskFree ) external view returns (uint256, uint256); function updateAcceptableRange() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPodOption is IERC20 { /** Enums */ // @dev 0 for Put, 1 for Call enum OptionType { PUT, CALL } // @dev 0 for European, 1 for American enum ExerciseType { EUROPEAN, AMERICAN } /** Events */ event Mint(address indexed minter, uint256 amount); event Unmint(address indexed minter, uint256 optionAmount, uint256 strikeAmount, uint256 underlyingAmount); event Exercise(address indexed exerciser, uint256 amount); event Withdraw(address indexed minter, uint256 strikeAmount, uint256 underlyingAmount); /** Functions */ /** * @notice Locks collateral and write option tokens. * * @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token. * * The collateral could be the strike or the underlying asset depending on the option type: Put or Call, * respectively * * It presumes the caller has already called IERC20.approve() on the * strike/underlying token contract to move caller funds. * * Options can only be minted while the series is NOT expired. * * It is also important to notice that options will be sent back * to `msg.sender` and not the `owner`. This behavior is designed to allow * proxy contracts to mint on others behalf. The `owner` will be able to remove * the deposited collateral after series expiration or by calling unmint(), even * if a third-party minted options on its behalf. * * @param amountOfOptions The amount option tokens to be issued * @param owner Which address will be the owner of the options */ function mint(uint256 amountOfOptions, address owner) external; /** * @notice Allow option token holders to use them to exercise the amount of units * of the locked tokens for the equivalent amount of the exercisable assets. * * @dev It presumes the caller has already called IERC20.approve() exercisable asset * to move caller funds. * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. * * @param amountOfOptions The amount option tokens to be exercised */ function exercise(uint256 amountOfOptions) external; /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their collateral to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and collateral. */ function withdraw() external; /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external; function optionType() external view returns (OptionType); function exerciseType() external view returns (ExerciseType); function underlyingAsset() external view returns (address); function underlyingAssetDecimals() external view returns (uint8); function strikeAsset() external view returns (address); function strikeAssetDecimals() external view returns (uint8); function strikePrice() external view returns (uint256); function strikePriceDecimals() external view returns (uint8); function expiration() external view returns (uint256); function startOfExerciseWindow() external view returns (uint256); function hasExpired() external view returns (bool); function isTradeWindow() external view returns (bool); function isExerciseWindow() external view returns (bool); function isWithdrawWindow() external view returns (bool); function strikeToTransfer(uint256 amountOfOptions) external view returns (uint256); function getSellerWithdrawAmounts(address owner) external view returns (uint256 strikeAmount, uint256 underlyingAmount); function underlyingReserves() external view returns (uint256); function strikeReserves() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./IAMM.sol"; interface IOptionAMMPool is IAMM { // @dev 0 for when tokenA enter the pool and B leaving (A -> B) // and 1 for the opposite direction enum TradeDirection { AB, BA } function tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) external view returns ( uint256 amountBOutput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) external view returns ( uint256 amountBInput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) external view returns ( uint256 amountAOutput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) external view returns ( uint256 amountAInput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) external view returns (uint256 withdrawAmountA, uint256 withdrawAmountB); function getABPrice() external view returns (uint256); function getAdjustedIV() external view returns (uint256); function withdrawRewards() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IFeePool { struct Balance { uint256 shares; uint256 liability; } function setFee(uint256 feeBaseValue, uint8 decimals) external; function withdraw(address to, uint256 amount) external; function mint(address to, uint256 amount) external; function feeToken() external view returns (address); function feeValue() external view returns (uint256); function feeDecimals() external view returns (uint8); function getCollectable(uint256 amount, uint256 poolAmount) external view returns (uint256); function sharesOf(address owner) external view returns (uint256); function getWithdrawAmount(address owner, uint256 amountOfShares) external view returns (uint256, uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IConfigurationManager { function setParameter(bytes32 name, uint256 value) external; function setEmergencyStop(address emergencyStop) external; function setPricingMethod(address pricingMethod) external; function setIVGuesser(address ivGuesser) external; function setIVProvider(address ivProvider) external; function setPriceProvider(address priceProvider) external; function setCapProvider(address capProvider) external; function setAMMFactory(address ammFactory) external; function setOptionFactory(address optionFactory) external; function setOptionHelper(address optionHelper) external; function setOptionPoolRegistry(address optionPoolRegistry) external; function getParameter(bytes32 name) external view returns (uint256); function owner() external view returns (address); function getEmergencyStop() external view returns (address); function getPricingMethod() external view returns (address); function getIVGuesser() external view returns (address); function getIVProvider() external view returns (address); function getPriceProvider() external view returns (address); function getCapProvider() external view returns (address); function getAMMFactory() external view returns (address); function getOptionFactory() external view returns (address); function getOptionHelper() external view returns (address); function getOptionPoolRegistry() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IEmergencyStop { function stop(address target) external; function resume(address target) external; function isStopped(address target) external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./IFeePool.sol"; interface IFeePoolBuilder { function buildFeePool( address asset, uint256 feeBaseValue, uint8 feeDecimals, address owner ) external returns (IFeePool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../interfaces/IAaveIncentivesController.sol"; import "../../interfaces/IConfigurationManager.sol"; import "../../lib/Conversion.sol"; abstract contract AaveIncentives is Conversion { address public immutable rewardAsset; address public immutable rewardContract; event RewardsClaimed(address indexed claimer, uint256 rewardAmount); constructor(IConfigurationManager configurationManager) public { rewardAsset = _parseAddressFromUint(configurationManager.getParameter("REWARD_ASSET")); rewardContract = _parseAddressFromUint(configurationManager.getParameter("REWARD_CONTRACT")); } /** * @notice Gets the current reward claimed */ function _rewardBalance() internal view returns (uint256) { return IERC20(rewardAsset).balanceOf(address(this)); } /** * @notice Claim pending rewards */ function _claimRewards(address[] memory assets) internal { IAaveIncentivesController distributor = IAaveIncentivesController(rewardContract); uint256 amountToClaim = distributor.getRewardsBalance(assets, address(this)); distributor.claimRewards(assets, amountToClaim, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract RequiredDecimals { uint256 private constant _MAX_TOKEN_DECIMALS = 38; /** * Tries to fetch the decimals of a token, if not existent, fails with a require statement * * @param token An instance of IERC20 * @return The decimals of a token */ function tryDecimals(IERC20 token) internal view returns (uint8) { // solhint-disable-line private-vars-leading-underscore bytes memory payload = abi.encodeWithSignature("decimals()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(token).staticcall(payload); require(success, "RequiredDecimals: required decimals"); uint8 decimals = abi.decode(returnData, (uint8)); require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38"); return decimals; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAMM { function addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) external; function removeLiquidity(uint256 amountOfA, uint256 amountOfB) external; function tokenA() external view returns (address); function tokenB() external view returns (address); function tokenADecimals() external view returns (uint8); function tokenBDecimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICapProvider { function setCap(address target, uint256 value) external; function getCap(address target) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAaveIncentivesController { function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; contract Conversion { /** * @notice Parses the address represented by an uint */ function _parseAddressFromUint(uint256 x) internal pure returns (address) { bytes memory data = new bytes(32); assembly { mstore(add(data, 32), x) } return abi.decode(data, (address)); } }
How much A Im getting for rescuing one A that i've deposited
uint256 AA;
88,981
[ 1, 4625, 348, 7953, 560, 30, 225, 9017, 9816, 432, 2221, 8742, 364, 400, 6319, 310, 1245, 432, 716, 277, 8081, 443, 1724, 329, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 27343, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2018 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.5.7; import { ReentrancyGuard } from "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { ICore } from "../interfaces/ICore.sol"; import { IRebalancingSetToken } from "../interfaces/IRebalancingSetToken.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { IVault } from "../interfaces/IVault.sol"; import { ModuleCoreState } from "./lib/ModuleCoreState.sol"; /** * @title RebalanceAuctionModule * @author Set Protocol * * The RebalanceAuctionModule is a smart contract that exposes bidding and failed rebalance functionality. */ contract RebalanceAuctionModule is ModuleCoreState, ReentrancyGuard { using SafeMath for uint256; /* ============ Events ============ */ event BidPlaced( address indexed rebalancingSetToken, address indexed bidder, uint256 executionQuantity, address[] combinedTokenAddresses, uint256[] inflowTokenUnits, uint256[] outflowTokenUnits ); /* ============ Constructor ============ */ /** * Constructor function for RebalanceAuctionModule * * @param _core The address of Core * @param _vault The address of Vault */ constructor( address _core, address _vault ) public ModuleCoreState( _core, _vault ) {} /* ============ Public Functions ============ */ /** * Bid on rebalancing a given quantity of sets held by a rebalancing token * The tokens are attributed to the user in the vault. * * @param _rebalancingSetToken Address of the rebalancing token being bid on * @param _quantity Number of currentSets to rebalance * @param _allowPartialFill Set to true if want to partially fill bid when quantity is greater than currentRemainingSets */ function bid( address _rebalancingSetToken, uint256 _quantity, bool _allowPartialFill ) external nonReentrant { // If user allows partial fills calculate partial fill (if necessary) uint256 executionQuantity = calculateExecutionQuantity( _rebalancingSetToken, _quantity, _allowPartialFill ); // Place bid and retrieve token inflows and outflows address[] memory tokenArray; uint256[] memory inflowUnitArray; uint256[] memory outflowUnitArray; ( tokenArray, inflowUnitArray, outflowUnitArray ) = IRebalancingSetToken(_rebalancingSetToken).placeBid(executionQuantity); // Retrieve tokens from bidder and deposit in vault for rebalancing set token coreInstance.batchDepositModule( msg.sender, _rebalancingSetToken, tokenArray, inflowUnitArray ); // Transfer ownership of tokens in vault from rebalancing set token to bidder coreInstance.batchTransferBalanceModule( tokenArray, _rebalancingSetToken, msg.sender, outflowUnitArray ); // Log bid placed event emit BidPlaced( _rebalancingSetToken, msg.sender, executionQuantity, tokenArray, inflowUnitArray, outflowUnitArray ); } /** * Bid on rebalancing a given quantity of sets held by a rebalancing token * The tokens are returned to the user. * * @param _rebalancingSetToken Address of the rebalancing token being bid on * @param _quantity Number of currentSets to rebalance * @param _allowPartialFill Set to true if want to partially fill bid when quantity is greater than currentRemainingSets */ function bidAndWithdraw( address _rebalancingSetToken, uint256 _quantity, bool _allowPartialFill ) external nonReentrant { // If user allows partial fills calculate partial fill (if necessary) uint256 executionQuantity = calculateExecutionQuantity( _rebalancingSetToken, _quantity, _allowPartialFill ); // Place bid and retrieve token inflows and outflows address[] memory tokenArray; uint256[] memory inflowUnitArray; uint256[] memory outflowUnitArray; ( tokenArray, inflowUnitArray, outflowUnitArray ) = IRebalancingSetToken(_rebalancingSetToken).placeBid(executionQuantity); // Retrieve tokens from bidder and deposit in vault for rebalancing set token coreInstance.batchDepositModule( msg.sender, _rebalancingSetToken, tokenArray, inflowUnitArray ); // Withdraw tokens from Rebalancing Set Token vault account to bidder coreInstance.batchWithdrawModule( _rebalancingSetToken, msg.sender, tokenArray, outflowUnitArray ); // Log bid placed event emit BidPlaced( _rebalancingSetToken, msg.sender, executionQuantity, tokenArray, inflowUnitArray, outflowUnitArray ); } /** * If a Rebalancing Set Token Rebalance has failed (it includes paused token or exceeds gas limits) * and been put in Drawdown state, user's can withdraw their portion of the components collateralizing * the Rebalancing Set Token. This burns the user's portion of the Rebalancing Set Token. * * @param _rebalancingSetToken Address of the rebalancing token to withdraw from */ function redeemFromFailedRebalance( address _rebalancingSetToken ) external nonReentrant { // Create Rebalancing Set Token instance IRebalancingSetToken rebalancingSetToken = IRebalancingSetToken(_rebalancingSetToken); // Make sure the rebalancingSetToken is tracked by Core require( coreInstance.validSets(_rebalancingSetToken), "RebalanceAuctionModule.redeemFromFailedRebalance: Invalid or disabled SetToken address" ); // Get getFailedAuctionWithdrawComponents from RebalancingSetToken address[] memory withdrawComponents = rebalancingSetToken.getFailedAuctionWithdrawComponents(); // Get Rebalancing Set Token's total supply uint256 setTotalSupply = rebalancingSetToken.totalSupply(); // Get caller's balance uint256 callerBalance = rebalancingSetToken.balanceOf(msg.sender); // Get RebalancingSetToken component amounts and calculate caller's portion of each token uint256 transferArrayLength = withdrawComponents.length; uint256[] memory componentTransferAmount = new uint256[](transferArrayLength); for (uint256 i = 0; i < transferArrayLength; i++) { uint256 tokenCollateralAmount = vaultInstance.getOwnerBalance( withdrawComponents[i], _rebalancingSetToken ); componentTransferAmount[i] = tokenCollateralAmount.mul(callerBalance).div(setTotalSupply); } // Burn caller's balance of Rebalancing Set Token rebalancingSetToken.burn( msg.sender, callerBalance ); // Transfer token amounts to caller in Vault from Rebalancing Set Token coreInstance.batchTransferBalanceModule( withdrawComponents, _rebalancingSetToken, msg.sender, componentTransferAmount ); } /* ============ Internal Functions ============ */ /** * Get execution quantity in event bid quantity exceeds remainingCurrentSets * * @param _rebalancingSetToken Address of the rebalancing token being bid on * @param _quantity Number of currentSets to rebalance * @param _allowPartialFill Set to true if want to partially fill bid when quantity is greater than currentRemainingSets * @return executionQuantity Array of token addresses invovled in rebalancing */ function calculateExecutionQuantity( address _rebalancingSetToken, uint256 _quantity, bool _allowPartialFill ) internal view returns (uint256) { // Make sure the rebalancingSetToken is tracked by Core require( coreInstance.validSets(_rebalancingSetToken), "RebalanceAuctionModule.bid: Invalid or disabled SetToken address" ); // Receive bidding parameters of current auction uint256[] memory biddingParameters = IRebalancingSetToken(_rebalancingSetToken).getBiddingParameters(); uint256 minimumBid = biddingParameters[0]; uint256 remainingCurrentSets = biddingParameters[1]; if (_allowPartialFill && _quantity > remainingCurrentSets) { // If quantity is greater than remainingCurrentSets round amount to nearest multiple of // minimumBid that is less than remainingCurrentSets uint256 executionQuantity = remainingCurrentSets.div(minimumBid).mul(minimumBid); return executionQuantity; } else { return _quantity; } } }
@return executionQuantity Array of token addresses invovled in rebalancing/ Make sure the rebalancingSetToken is tracked by Core Receive bidding parameters of current auction If quantity is greater than remainingCurrentSets round amount to nearest multiple of minimumBid that is less than remainingCurrentSets
function calculateExecutionQuantity( address _rebalancingSetToken, uint256 _quantity, bool _allowPartialFill ) internal view returns (uint256) { require( coreInstance.validSets(_rebalancingSetToken), "RebalanceAuctionModule.bid: Invalid or disabled SetToken address" ); uint256[] memory biddingParameters = IRebalancingSetToken(_rebalancingSetToken).getBiddingParameters(); uint256 minimumBid = biddingParameters[0]; uint256 remainingCurrentSets = biddingParameters[1]; if (_allowPartialFill && _quantity > remainingCurrentSets) { uint256 executionQuantity = remainingCurrentSets.div(minimumBid).mul(minimumBid); return executionQuantity; return _quantity; } }
15,818,171
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 2463, 4588, 12035, 4202, 1510, 434, 1147, 6138, 2198, 1527, 1259, 316, 283, 28867, 19, 4344, 3071, 326, 283, 28867, 694, 1345, 353, 15200, 635, 4586, 17046, 324, 1873, 310, 1472, 434, 783, 279, 4062, 971, 10457, 353, 6802, 2353, 4463, 3935, 2785, 3643, 3844, 358, 11431, 3229, 434, 5224, 17763, 716, 353, 5242, 2353, 4463, 3935, 2785, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3210, 12035, 12, 203, 3639, 1758, 389, 266, 28867, 694, 1345, 16, 203, 3639, 2254, 5034, 389, 16172, 16, 203, 3639, 1426, 389, 5965, 9447, 8026, 203, 565, 262, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 2922, 1442, 18, 877, 2785, 24899, 266, 28867, 694, 1345, 3631, 203, 5411, 315, 426, 12296, 37, 4062, 3120, 18, 19773, 30, 1962, 578, 5673, 1000, 1345, 1758, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 8526, 3778, 324, 1873, 310, 2402, 273, 467, 426, 28867, 694, 1345, 24899, 266, 28867, 694, 1345, 2934, 588, 38, 1873, 310, 2402, 5621, 203, 3639, 2254, 5034, 5224, 17763, 273, 324, 1873, 310, 2402, 63, 20, 15533, 203, 3639, 2254, 5034, 4463, 3935, 2785, 273, 324, 1873, 310, 2402, 63, 21, 15533, 203, 203, 3639, 309, 261, 67, 5965, 9447, 8026, 597, 389, 16172, 405, 4463, 3935, 2785, 13, 288, 1377, 203, 5411, 2254, 5034, 4588, 12035, 273, 4463, 3935, 2785, 18, 2892, 12, 15903, 17763, 2934, 16411, 12, 15903, 17763, 1769, 203, 5411, 327, 4588, 12035, 31, 203, 5411, 327, 389, 16172, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; // Uncomment if needed. // import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../libraries/UniswapOracle.sol"; import "../libraries/FixedPoints.sol"; import "../multicall.sol"; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } /// @title Simple math library for Max and Min. library Math { function max(int24 a, int24 b) internal pure returns (int24) { return a >= b ? a : b; } function min(int24 a, int24 b) internal pure returns (int24) { return a < b ? a : b; } 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 tickFloor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) { c = c - 1; } c = c * tickSpacing; return c; } function tickUpper(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick > 0 && tick % tickSpacing != 0) { c = c + 1; } c = c * tickSpacing; return c; } } /// @title Uniswap V3 Liquidity Mining Main Contract contract MiningOneSideBoost is Ownable, Multicall, ReentrancyGuard { // using Math for int24; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using UniswapOracle for address; int24 internal constant TICK_MAX = 500000; int24 internal constant TICK_MIN = -500000; struct PoolInfo { address token0; address token1; uint24 fee; } bool uniIsETH; address uniToken; address lockToken; /// @dev Contract of the uniV3 Nonfungible Position Manager. address uniV3NFTManager; address uniFactory; address swapPool; PoolInfo public rewardPool; /// @dev Last block number that the accRewardRerShare is touched. uint256 lastTouchBlock; /// @dev The block number when NFT mining rewards starts/ends. uint256 startBlock; uint256 endBlock; uint256 lockBoostMultiplier; struct RewardInfo { /// @dev Contract of the reward erc20 token. address rewardToken; /// @dev who provides reward address provider; /// @dev Accumulated Reward Tokens per share, times Q128. uint256 accRewardPerShare; /// @dev Reward amount for each block. uint256 rewardPerBlock; } mapping(uint256 => RewardInfo) public rewardInfos; uint256 public rewardInfosLen; /// @dev Store the owner of the NFT token mapping(uint256 => address) public owners; /// @dev The inverse mapping of owners. mapping(address => EnumerableSet.UintSet) private tokenIds; /// @dev Record the status for a certain token for the last touched time. struct TokenStatus { uint256 nftId; // bool isDepositWithNFT; uint128 uniLiquidity; uint256 lockAmount; uint256 vLiquidity; uint256 validVLiquidity; uint256 nIZI; uint256 lastTouchBlock; uint256[] lastTouchAccRewardPerShare; } mapping(uint256 => TokenStatus) public tokenStatus; receive() external payable {} /// @dev token to lock, 0 for not boost IERC20 public iziToken; /// @dev current total nIZI. uint256 public totalNIZI; /// @dev Current total virtual liquidity. uint256 public totalVLiquidity; /// @dev Current total lock token uint256 public totalLock; // Events event Deposit(address indexed user, uint256 tokenId, uint256 nIZI); event Withdraw(address indexed user, uint256 tokenId); event CollectReward(address indexed user, uint256 tokenId, address token, uint256 amount); event ModifyEndBlock(uint256 endBlock); event ModifyRewardPerBlock(address indexed rewardToken, uint256 rewardPerBlock); event ModifyProvider(address indexed rewardToken, address provider); function _setRewardPool( address _uniToken, address _lockToken, uint24 fee ) internal { address token0; address token1; if (_uniToken < _lockToken) { token0 = _uniToken; token1 = _lockToken; } else { token0 = _lockToken; token1 = _uniToken; } rewardPool.token0 = token0; rewardPool.token1 = token1; rewardPool.fee = fee; } struct PoolParams { address uniV3NFTManager; address uniTokenAddr; address lockTokenAddr; uint24 fee; } constructor( PoolParams memory poolParams, RewardInfo[] memory _rewardInfos, uint256 _lockBoostMultiplier, address iziTokenAddr, uint256 _startBlock, uint256 _endBlock ) { uniV3NFTManager = poolParams.uniV3NFTManager; _setRewardPool( poolParams.uniTokenAddr, poolParams.lockTokenAddr, poolParams.fee ); address weth = INonfungiblePositionManager(uniV3NFTManager).WETH9(); require(weth != poolParams.lockTokenAddr, "WETH NOT SUPPORT"); uniFactory = INonfungiblePositionManager(uniV3NFTManager).factory(); uniToken = poolParams.uniTokenAddr; uniIsETH = (uniToken == weth); lockToken = poolParams.lockTokenAddr; IERC20(uniToken).safeApprove(uniV3NFTManager, type(uint256).max); swapPool = IUniswapV3Factory(uniFactory).getPool( lockToken, uniToken, poolParams.fee ); require(swapPool != address(0), "NO UNI POOL"); rewardInfosLen = _rewardInfos.length; require(rewardInfosLen > 0, "NO REWARD"); require(rewardInfosLen < 3, "AT MOST 2 REWARDS"); for (uint256 i = 0; i < rewardInfosLen; i++) { rewardInfos[i] = _rewardInfos[i]; rewardInfos[i].accRewardPerShare = 0; } require(_lockBoostMultiplier > 0, "M>0"); require(_lockBoostMultiplier < 4, "M<4"); lockBoostMultiplier = _lockBoostMultiplier; // iziTokenAddr == 0 means not boost iziToken = IERC20(iziTokenAddr); startBlock = _startBlock; endBlock = _endBlock; lastTouchBlock = startBlock; totalVLiquidity = 0; totalNIZI = 0; } /// @notice Get the overall info for the mining contract. function getMiningContractInfo() external view returns ( address uniToken_, address lockToken_, uint24 fee_, uint256 lockBoostMultiplier_, address iziTokenAddr_, uint256 lastTouchBlock_, uint256 totalVLiquidity_, uint256 totalLock_, uint256 totalNIZI_, uint256 startBlock_, uint256 endBlock_ ) { return ( uniToken, lockToken, rewardPool.fee, lockBoostMultiplier, address(iziToken), lastTouchBlock, totalVLiquidity, totalLock, totalNIZI, startBlock, endBlock ); } /// @dev compute amount of lockToken /// @param sqrtPriceX96 sqrtprice value viewed from uniswap pool /// @param uniAmount amount of uniToken user deposits /// or amount computed corresponding to deposited uniswap NFT /// @return lockAmount amount of lockToken function _getLockAmount(uint160 sqrtPriceX96, uint256 uniAmount) private view returns (uint256 lockAmount) { // uniAmount is less than Q96, checked before uint256 precision = FixedPoints.Q96; uint256 sqrtPriceXP = sqrtPriceX96; // if price > 1, we discard the useless precision if (sqrtPriceX96 > FixedPoints.Q96) { precision = FixedPoints.Q32; // sqrtPriceXP <= Q96 after >> operation sqrtPriceXP = (sqrtPriceXP >> 64); } // priceXP <= Q160 if price >= 1 // priceXP <= Q96 if price < 1 uint256 priceXP = (sqrtPriceXP * sqrtPriceXP) / precision; if (priceXP > 0) { if (uniToken < lockToken) { // price is lockToken / uniToken lockAmount = (uniAmount * priceXP) / precision; } else { lockAmount = (uniAmount * precision) / priceXP; } } else { // in this case sqrtPriceXP <= Q48, precision = Q96 if (uniToken < lockToken) { // price is lockToken / uniToken // lockAmount = uniAmount * sqrtPriceXP * sqrtPriceXP / precision / precision; // the above expression will always get 0 lockAmount = 0; } else { lockAmount = uniAmount * precision / sqrtPriceXP / sqrtPriceXP; // lockAmount is always < Q128, since sqrtPriceXP > Q32 // we still add the require statement to double check require(lockAmount < FixedPoints.Q160, "TOO MUCH LOCK"); lockAmount *= precision; } } require(lockAmount > 0, "LOCK 0"); } /// @notice new a token status when touched. function _newTokenStatus(TokenStatus memory newTokenStatus) internal { tokenStatus[newTokenStatus.nftId] = newTokenStatus; TokenStatus storage t = tokenStatus[newTokenStatus.nftId]; t.lastTouchBlock = lastTouchBlock; t.lastTouchAccRewardPerShare = new uint256[](rewardInfosLen); for (uint256 i = 0; i < rewardInfosLen; i++) { t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare; } } /// @notice update a token status when touched function _updateTokenStatus( uint256 tokenId, uint256 validVLiquidity, uint256 nIZI ) internal { TokenStatus storage t = tokenStatus[tokenId]; // when not boost, validVL == vL t.validVLiquidity = validVLiquidity; t.nIZI = nIZI; t.lastTouchBlock = lastTouchBlock; for (uint256 i = 0; i < rewardInfosLen; i++) { t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare; } } /// @notice Update reward variables to be up-to-date. function _updateVLiquidity(uint256 vLiquidity, bool isAdd) internal { if (isAdd) { totalVLiquidity = totalVLiquidity + vLiquidity; } else { totalVLiquidity = totalVLiquidity - vLiquidity; } // max lockBoostMultiplier is 3 require(totalVLiquidity <= FixedPoints.Q128 * 3, "TOO MUCH LIQUIDITY STAKED"); } function _updateNIZI(uint256 nIZI, bool isAdd) internal { if (isAdd) { totalNIZI = totalNIZI + nIZI; } else { totalNIZI = totalNIZI - nIZI; } } /// @notice Update the global status. function _updateGlobalStatus() internal { if (block.number <= lastTouchBlock) { return; } if (lastTouchBlock >= endBlock) { return; } uint256 currBlockNumber = Math.min(block.number, endBlock); if (totalVLiquidity == 0) { lastTouchBlock = currBlockNumber; return; } for (uint256 i = 0; i < rewardInfosLen; i++) { // tokenReward < 2^25 * 2^64 * 2*10, 15 years, 1000 r/block uint256 tokenReward = (currBlockNumber - lastTouchBlock) * rewardInfos[i].rewardPerBlock; // tokenReward * Q128 < 2^(25 + 64 + 10 + 128) rewardInfos[i].accRewardPerShare = rewardInfos[i].accRewardPerShare + ((tokenReward * FixedPoints.Q128) / totalVLiquidity); } lastTouchBlock = currBlockNumber; } function _computeValidVLiquidity(uint256 vLiquidity, uint256 nIZI) internal view returns (uint256) { if (totalNIZI == 0) { return vLiquidity; } uint256 iziVLiquidity = (vLiquidity * 4 + (totalVLiquidity * nIZI * 6) / totalNIZI) / 10; return Math.min(iziVLiquidity, vLiquidity); } /// @dev get sqrtPrice of pool(uniToken/tokenSwap/fee) /// and compute tick range converted from [TICK_MIN, PriceUni] or [PriceUni, TICK_MAX] /// @return sqrtPriceX96 current sqrtprice value viewed from uniswap pool, is a 96-bit fixed point number /// note this value might mean price of lockToken/uniToken (if uniToken < lockToken) /// or price of uniToken / lockToken (if uniToken > lockToken) /// @return tickLeft /// @return tickRight function _getPriceAndTickRange() private view returns ( uint160 sqrtPriceX96, int24 tickLeft, int24 tickRight ) { (int24 avgTick, uint160 avgSqrtPriceX96, int24 currTick, ) = swapPool .getAvgTickPriceWithin2Hour(); int24 tickSpacing = IUniswapV3Factory(uniFactory).feeAmountTickSpacing( rewardPool.fee ); if (uniToken < lockToken) { // price is lockToken / uniToken // uniToken is X tickLeft = Math.max(currTick + 1, avgTick); tickRight = TICK_MAX; tickLeft = Math.tickUpper(tickLeft, tickSpacing); tickRight = Math.tickUpper(tickRight, tickSpacing); } else { // price is uniToken / lockToken // uniToken is Y tickRight = Math.min(currTick, avgTick); tickLeft = TICK_MIN; tickLeft = Math.tickFloor(tickLeft, tickSpacing); tickRight = Math.tickFloor(tickRight, tickSpacing); } require(tickLeft < tickRight, "L<R"); sqrtPriceX96 = avgSqrtPriceX96; } function getOraclePrice() external view returns ( int24 avgTick, uint160 avgSqrtPriceX96 ) { (avgTick, avgSqrtPriceX96, , ) = swapPool.getAvgTickPriceWithin2Hour(); } // fill INonfungiblePositionManager.MintParams struct to call INonfungiblePositionManager.mint(...) function _mintUniswapParam( uint256 uniAmount, int24 tickLeft, int24 tickRight, uint256 deadline ) private view returns (INonfungiblePositionManager.MintParams memory params) { params.fee = rewardPool.fee; params.tickLower = tickLeft; params.tickUpper = tickRight; params.deadline = deadline; params.recipient = address(this); if (uniToken < lockToken) { params.token0 = uniToken; params.token1 = lockToken; params.amount0Desired = uniAmount; params.amount1Desired = 0; params.amount0Min = 1; params.amount1Min = 0; } else { params.token0 = lockToken; params.token1 = uniToken; params.amount0Desired = 0; params.amount1Desired = uniAmount; params.amount0Min = 0; params.amount1Min = 1; } } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "STE"); } function depositWithuniToken( uint256 uniAmount, uint256 numIZI, uint256 deadline ) external payable nonReentrant { require(uniAmount >= 1e7, "TOKENUNI AMOUNT TOO SMALL"); require(uniAmount < FixedPoints.Q96 / 3, "TOKENUNI AMOUNT TOO LARGE"); if (uniIsETH) { require(msg.value >= uniAmount, "ETHER INSUFFICIENT"); } else { IERC20(uniToken).safeTransferFrom( msg.sender, address(this), uniAmount ); } ( uint160 sqrtPriceX96, int24 tickLeft, int24 tickRight ) = _getPriceAndTickRange(); TokenStatus memory newTokenStatus; INonfungiblePositionManager.MintParams memory uniParams = _mintUniswapParam( uniAmount, tickLeft, tickRight, deadline ); uint256 actualAmountUni; if (uniToken < lockToken) { ( newTokenStatus.nftId, newTokenStatus.uniLiquidity, actualAmountUni, ) = INonfungiblePositionManager(uniV3NFTManager).mint{ value: msg.value }(uniParams); } else { ( newTokenStatus.nftId, newTokenStatus.uniLiquidity, , actualAmountUni ) = INonfungiblePositionManager(uniV3NFTManager).mint{ value: msg.value }(uniParams); } // mark owners and append to list owners[newTokenStatus.nftId] = msg.sender; bool res = tokenIds[msg.sender].add(newTokenStatus.nftId); require(res); if (actualAmountUni < uniAmount) { if (uniIsETH) { // refund uniToken // from uniswap to this INonfungiblePositionManager(uniV3NFTManager).refundETH(); // from this to msg.sender if (address(this).balance > 0) safeTransferETH(msg.sender, address(this).balance); } else { // refund uniToken IERC20(uniToken).safeTransfer( msg.sender, uniAmount - actualAmountUni ); } } _updateGlobalStatus(); newTokenStatus.vLiquidity = actualAmountUni * lockBoostMultiplier; newTokenStatus.lockAmount = _getLockAmount( sqrtPriceX96, newTokenStatus.vLiquidity ); // make vLiquidity lower newTokenStatus.vLiquidity = newTokenStatus.vLiquidity / 1e6; IERC20(lockToken).safeTransferFrom( msg.sender, address(this), newTokenStatus.lockAmount ); totalLock += newTokenStatus.lockAmount; _updateVLiquidity(newTokenStatus.vLiquidity, true); newTokenStatus.nIZI = numIZI; if (address(iziToken) == address(0)) { // boost is not enabled newTokenStatus.nIZI = 0; } _updateNIZI(newTokenStatus.nIZI, true); newTokenStatus.validVLiquidity = _computeValidVLiquidity( newTokenStatus.vLiquidity, newTokenStatus.nIZI ); require(newTokenStatus.nIZI < FixedPoints.Q128 / 6, "NIZI O"); _newTokenStatus(newTokenStatus); if (newTokenStatus.nIZI > 0) { // lock izi in this contract iziToken.safeTransferFrom( msg.sender, address(this), newTokenStatus.nIZI ); } emit Deposit(msg.sender, newTokenStatus.nftId, newTokenStatus.nIZI); } function _withdrawUniswapParam( uint256 uniPositionID, uint128 liquidity, uint256 deadline ) private pure returns ( INonfungiblePositionManager.DecreaseLiquidityParams memory params ) { params.tokenId = uniPositionID; params.liquidity = liquidity; params.amount0Min = 0; params.amount1Min = 0; params.deadline = deadline; } /// @notice deposit iZi to an nft token /// @param tokenId nft already deposited /// @param deltaNIZI amount of izi to deposit function depositIZI(uint256 tokenId, uint256 deltaNIZI) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER or NOT EXIST"); require(address(iziToken) != address(0), "NOT BOOST"); require(deltaNIZI > 0, "DEPOSIT IZI MUST BE POSITIVE"); _collectReward(tokenId); TokenStatus memory t = tokenStatus[tokenId]; _updateNIZI(deltaNIZI, true); uint256 nIZI = t.nIZI + deltaNIZI; // update validVLiquidity uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, nIZI); _updateTokenStatus(tokenId, validVLiquidity, nIZI); // transfer iZi from user iziToken.safeTransferFrom(msg.sender, address(this), deltaNIZI); } // fill INonfungiblePositionManager.CollectParams struct to call INonfungiblePositionManager.collect(...) function _collectUniswapParam(uint256 uniPositionID, address recipient) private pure returns (INonfungiblePositionManager.CollectParams memory params) { params.tokenId = uniPositionID; params.recipient = recipient; params.amount0Max = 0xffffffffffffffffffffffffffffffff; params.amount1Max = 0xffffffffffffffffffffffffffffffff; } /// @notice Widthdraw a single position. /// @param tokenId The related position id. /// @param noReward true if use want to withdraw without reward function withdraw(uint256 tokenId, bool noReward) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER OR NOT EXIST"); if (noReward) { _updateGlobalStatus(); } else { _collectReward(tokenId); } TokenStatus storage t = tokenStatus[tokenId]; _updateVLiquidity(t.vLiquidity, false); if (t.nIZI > 0) { _updateNIZI(t.nIZI, false); // refund iZi to user iziToken.safeTransfer(msg.sender, t.nIZI); } if (t.lockAmount > 0) { // refund lockToken to user IERC20(lockToken).safeTransfer(msg.sender, t.lockAmount); totalLock -= t.lockAmount; } INonfungiblePositionManager(uniV3NFTManager).decreaseLiquidity( _withdrawUniswapParam(tokenId, t.uniLiquidity, type(uint256).max) ); if (!uniIsETH) { INonfungiblePositionManager(uniV3NFTManager).collect( _collectUniswapParam(tokenId, msg.sender) ); } else { (uint256 amount0, uint256 amount1) = INonfungiblePositionManager( uniV3NFTManager ).collect( _collectUniswapParam( tokenId, address(this) ) ); (uint256 amountUni, uint256 amountLock) = (uniToken < lockToken)? (amount0, amount1) : (amount1, amount0); if (amountLock > 0) { IERC20(lockToken).safeTransfer(msg.sender, amountLock); } if (amountUni > 0) { IWETH9(uniToken).withdraw(amountUni); safeTransferETH(msg.sender, amountUni); } } owners[tokenId] = address(0); bool res = tokenIds[msg.sender].remove(tokenId); require(res); emit Withdraw(msg.sender, tokenId); } /// @notice Collect pending reward for a single position. /// @param tokenId The related position id. function _collectReward(uint256 tokenId) internal { TokenStatus memory t = tokenStatus[tokenId]; _updateGlobalStatus(); for (uint256 i = 0; i < rewardInfosLen; i++) { // multiplied by Q128 before uint256 _reward = (t.validVLiquidity * (rewardInfos[i].accRewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128; if (_reward > 0) { IERC20(rewardInfos[i].rewardToken).safeTransferFrom( rewardInfos[i].provider, msg.sender, _reward ); } emit CollectReward( msg.sender, tokenId, rewardInfos[i].rewardToken, _reward ); } // update validVLiquidity uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, t.nIZI); _updateTokenStatus(tokenId, validVLiquidity, t.nIZI); } /// @notice Collect pending reward for a single position. /// @param tokenId The related position id. function collect(uint256 tokenId) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER or NOT EXIST"); _collectReward(tokenId); INonfungiblePositionManager.CollectParams memory params = _collectUniswapParam(tokenId, msg.sender); // collect swap fee from uniswap INonfungiblePositionManager(uniV3NFTManager).collect(params); } /// @notice Collect all pending rewards. function collectAllTokens() external nonReentrant { EnumerableSet.UintSet storage ids = tokenIds[msg.sender]; for (uint256 i = 0; i < ids.length(); i++) { require(owners[ids.at(i)] == msg.sender, "NOT OWNER"); _collectReward(ids.at(i)); INonfungiblePositionManager.CollectParams memory params = _collectUniswapParam(ids.at(i), msg.sender); // collect swap fee from uniswap INonfungiblePositionManager(uniV3NFTManager).collect(params); } } /// @notice View function to get position ids staked here for an user. /// @param _user The related address. function getTokenIds(address _user) external view returns (uint256[] memory) { EnumerableSet.UintSet storage ids = tokenIds[_user]; // push could not be used in memory array // we set the tokenIdList into a fixed-length array rather than dynamic uint256[] memory tokenIdList = new uint256[](ids.length()); for (uint256 i = 0; i < ids.length(); i++) { tokenIdList[i] = ids.at(i); } return tokenIdList; } /// @notice Return reward multiplier over the given _from to _to block. /// @param _from The start block. /// @param _to The end block. function _getRewardBlockNum(uint256 _from, uint256 _to) internal view returns (uint256) { if (_from > _to) { return 0; } if (_to <= endBlock) { return _to - _from; } else if (_from >= endBlock) { return 0; } else { return endBlock - _from; } } /// @notice View function to see pending Reward for a single position. /// @param tokenId The related position id. function pendingReward(uint256 tokenId) public view returns (uint256[] memory) { TokenStatus memory t = tokenStatus[tokenId]; uint256[] memory _reward = new uint256[](rewardInfosLen); for (uint256 i = 0; i < rewardInfosLen; i++) { uint256 tokenReward = _getRewardBlockNum( lastTouchBlock, block.number ) * rewardInfos[i].rewardPerBlock; uint256 rewardPerShare = rewardInfos[i].accRewardPerShare + (tokenReward * FixedPoints.Q128) / totalVLiquidity; // l * (currentAcc - lastAcc) _reward[i] = (t.validVLiquidity * (rewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128; } return _reward; } /// @notice View function to see pending Rewards for an address. /// @param _user The related address. function pendingRewards(address _user) external view returns (uint256[] memory) { uint256[] memory _reward = new uint256[](rewardInfosLen); for (uint256 j = 0; j < rewardInfosLen; j++) { _reward[j] = 0; } for (uint256 i = 0; i < tokenIds[_user].length(); i++) { uint256[] memory r = pendingReward(tokenIds[_user].at(i)); for (uint256 j = 0; j < rewardInfosLen; j++) { _reward[j] += r[j]; } } return _reward; } // Control fuctions for the contract owner and operators. /// @notice If something goes wrong, we can send back user's nft and locked assets /// @param tokenId The related position id. function emergenceWithdraw(uint256 tokenId) external onlyOwner { address owner = owners[tokenId]; require(owner != address(0)); INonfungiblePositionManager(uniV3NFTManager).safeTransferFrom( address(this), owner, tokenId ); TokenStatus storage t = tokenStatus[tokenId]; if (t.nIZI > 0) { // we should ensure nft refund to user // omit the case when transfer() returns false unexpectedly iziToken.transfer(owner, t.nIZI); } if (t.lockAmount > 0) { // we should ensure nft refund to user // omit the case when transfer() returns false unexpectedly IERC20(lockToken).transfer(owner, t.lockAmount); } // makesure user cannot withdraw/depositIZI or collect reward on this nft owners[tokenId] = address(0); } /// @notice Set new reward end block. /// @param _endBlock New end block. function modifyEndBlock(uint256 _endBlock) external onlyOwner { require(_endBlock > block.number, "OUT OF DATE"); _updateGlobalStatus(); // jump if origin endBlock < block.number lastTouchBlock = block.number; endBlock = _endBlock; emit ModifyEndBlock(endBlock); } /// @notice Set new reward per block. /// @param rewardIdx which rewardInfo to modify /// @param _rewardPerBlock new reward per block function modifyRewardPerBlock(uint256 rewardIdx, uint256 _rewardPerBlock) external onlyOwner { require(rewardIdx < rewardInfosLen, "OUT OF REWARD INFO RANGE"); _updateGlobalStatus(); rewardInfos[rewardIdx].rewardPerBlock = _rewardPerBlock; emit ModifyRewardPerBlock( rewardInfos[rewardIdx].rewardToken, _rewardPerBlock ); } /// @notice Set new reward provider. /// @param rewardIdx which rewardInfo to modify /// @param provider New provider function modifyProvider(uint256 rewardIdx, address provider) external onlyOwner { require(rewardIdx < rewardInfosLen, "OUT OF REWARD INFO RANGE"); rewardInfos[rewardIdx].provider = provider; emit ModifyProvider(rewardInfos[rewardIdx].rewardToken, provider); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // 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 (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/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 pragma solidity ^0.8.4; import "../uniswap/interfaces.sol"; import "./LogPowMath.sol"; library UniswapOracle { using UniswapOracle for address; struct Observation { uint32 blockTimestamp; int56 tickCumulative; uint160 secondsPerLiquidityCumulativeX128; bool initialized; } /// @dev query a certain observation from uniswap pool /// @param pool address of uniswap pool /// @param observationIndex index of wanted observation /// @return observation desired observation, see Observation to learn more function getObservation(address pool, uint observationIndex) internal view returns (Observation memory observation) { ( observation.blockTimestamp, observation.tickCumulative, observation.secondsPerLiquidityCumulativeX128, observation.initialized ) = IUniswapV3Pool(pool).observations(observationIndex); } /// @dev query latest and oldest observations from uniswap pool /// @param pool address of uniswap pool /// @param latestIndex index of latest observation in the pool /// @param observationCardinality size of observation queue in the pool /// @return oldestObservation /// @return latestObservation function getObservationBoundary(address pool, uint16 latestIndex, uint16 observationCardinality) internal view returns (Observation memory oldestObservation, Observation memory latestObservation) { uint16 oldestIndex = (latestIndex + 1) % observationCardinality; oldestObservation = pool.getObservation(oldestIndex); if (!oldestObservation.initialized) { oldestIndex = 0; oldestObservation = pool.getObservation(0); } if (latestIndex == oldestIndex) { // oldest observation is latest observation latestObservation = oldestObservation; } else { latestObservation = pool.getObservation(latestIndex); } } struct Slot0 { int24 tick; uint160 sqrtPriceX96; uint16 observationIndex; uint16 observationCardinality; } /// @dev view slot0 infomations from uniswap pool /// @param pool address of uniswap /// @return slot0 a Slot0 struct with necessary info, see Slot0 struct above function getSlot0(address pool) internal view returns (Slot0 memory slot0) { ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); slot0.tick = tick; slot0.sqrtPriceX96 = sqrtPriceX96; slot0.observationIndex = observationIndex; slot0.observationCardinality = observationCardinality; } // note if we call this interface, we must ensure that the // oldest observation preserved in pool is older than 2h ago function _getAvgTickFromTarget(address pool, uint32 targetTimestamp, int56 latestTickCumu, uint32 latestTimestamp) private view returns (int24 tick) { uint32[] memory secondsAgo = new uint32[](1); secondsAgo[0] = uint32(block.timestamp) - targetTimestamp; int56[] memory tickCumulatives; (tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgo); uint56 timeDelta = latestTimestamp - targetTimestamp; int56 tickAvg = (latestTickCumu - tickCumulatives[0]) / int56(timeDelta); tick = int24(tickAvg); } /// @dev compute avg tick and avg sqrt price of pool within one hour from now /// @param pool address of uniswap pool /// @return tick computed avg tick /// @return sqrtPriceX96 computed avg sqrt price, in the form of 96-bit fixed point number function getAvgTickPriceWithin2Hour(address pool) internal view returns (int24 tick, uint160 sqrtPriceX96, int24 currTick, uint160 currSqrtPriceX96) { Slot0 memory slot0 = pool.getSlot0(); if (slot0.observationCardinality == 1) { // only 1 observation in the swap pool // we could simply return tick/sqrtPrice of slot0 return (slot0.tick, slot0.sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } else { // we will search the latest observation and the observation 1h ago // 1st, we should get the boundary of the observations in the pool Observation memory oldestObservation; Observation memory latestObservation; (oldestObservation, latestObservation) = pool.getObservationBoundary(slot0.observationIndex, slot0.observationCardinality); if (oldestObservation.blockTimestamp == latestObservation.blockTimestamp) { // there is only 1 valid observation in the pool return (slot0.tick, slot0.sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } uint32 twoHourAgo = uint32(block.timestamp - 7200); // now there must be at least 2 valid observations in the pool if (twoHourAgo <= oldestObservation.blockTimestamp || latestObservation.blockTimestamp <= oldestObservation.blockTimestamp + 3600) { // the oldest observation updated within 1h // we can not safely call IUniswapV3Pool.observe(...) for it 1h ago uint56 timeDelta = latestObservation.blockTimestamp - oldestObservation.blockTimestamp; int56 tickAvg = (latestObservation.tickCumulative - oldestObservation.tickCumulative) / int56(timeDelta); tick = int24(tickAvg); } else { // we are sure that the oldest observation is old enough // we can safely call IUniswapV3Pool.observe(...) for it 1h ago uint32 targetTimestamp = twoHourAgo; if (targetTimestamp + 3600 > latestObservation.blockTimestamp) { targetTimestamp = latestObservation.blockTimestamp - 3600; } tick = _getAvgTickFromTarget(pool, targetTimestamp, latestObservation.tickCumulative, latestObservation.blockTimestamp); } sqrtPriceX96 = LogPowMath.getSqrtPrice(tick); return (tick, sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library FixedPoints { uint256 constant Q32 = (1 << 32); uint256 constant Q64 = (1 << 64); uint256 constant Q96 = (1 << 96); uint256 constant Q128 = (1 << 128); uint256 constant Q160 = (1 << 160); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall { function multicall(bytes[] calldata data) external payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IUniswapV3Pool { function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } interface IUniswapV3Factory { /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); } interface INonfungiblePositionManager { /// @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); 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 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 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 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); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function ownerOf(uint256 tokenId) external view returns (address); function transferFrom( address from, address to, uint256 tokenId ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library LogPowMath { int24 internal constant MIN_POINT = -887272; int24 internal constant MAX_POINT = -MIN_POINT; uint160 internal constant MIN_SQRT_PRICE = 4295128739; uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342; /// @notice sqrt(1.0001^point) in form oy 96-bit fix point num function getSqrtPrice(int24 point) internal pure returns (uint160 sqrtPrice_96) { uint256 absIdx = point < 0 ? uint256(-int256(point)) : uint256(int256(point)); require(absIdx <= uint256(int256(MAX_POINT)), 'T'); uint256 value = absIdx & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absIdx & 0x2 != 0) value = (value * 0xfff97272373d413259a46990580e213a) >> 128; if (absIdx & 0x4 != 0) value = (value * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absIdx & 0x8 != 0) value = (value * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absIdx & 0x10 != 0) value = (value * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absIdx & 0x20 != 0) value = (value * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absIdx & 0x40 != 0) value = (value * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absIdx & 0x80 != 0) value = (value * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absIdx & 0x100 != 0) value = (value * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absIdx & 0x200 != 0) value = (value * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absIdx & 0x400 != 0) value = (value * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absIdx & 0x800 != 0) value = (value * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absIdx & 0x1000 != 0) value = (value * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absIdx & 0x2000 != 0) value = (value * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absIdx & 0x4000 != 0) value = (value * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absIdx & 0x8000 != 0) value = (value * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absIdx & 0x10000 != 0) value = (value * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absIdx & 0x20000 != 0) value = (value * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absIdx & 0x40000 != 0) value = (value * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absIdx & 0x80000 != 0) value = (value * 0x48a170391f7dc42444e8fa2) >> 128; if (point > 0) value = type(uint256).max / value; sqrtPrice_96 = uint160((value >> 32) + (value % (1 << 32) == 0 ? 0 : 1)); } // floor(log1.0001(sqrtPrice_96)) function getLogSqrtPriceFloor(uint160 sqrtPrice_96) internal pure returns (int24 logValue) { // second inequality must be < because the price can nevex reach the price at the max tick require(sqrtPrice_96 >= MIN_SQRT_PRICE && sqrtPrice_96 < MAX_SQRT_PRICE, 'R'); uint256 sqrtPrice_128 = uint256(sqrtPrice_96) << 32; uint256 x = sqrtPrice_128; uint256 m = 0; assembly { let y := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(5, gt(x, 0xFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(4, gt(x, 0xFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(3, gt(x, 0xFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(2, gt(x, 0xF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(1, gt(x, 0x3)) m := or(m, y) x := shr(y, x) } assembly { let y := gt(x, 0x1) m := or(m, y) } if (m >= 128) x = sqrtPrice_128 >> (m - 127); else x = sqrtPrice_128 << (127 - m); int256 l2 = (int256(m) - 128) << 64; assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(63, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(62, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(61, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(60, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(59, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(58, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(57, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(56, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(55, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(54, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(53, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(52, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(51, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(50, y)) } int256 ls10001 = l2 * 255738958999603826347141; int24 logFloor = int24((ls10001 - 3402992956809132418596140100660247210) >> 128); int24 logUpper = int24((ls10001 + 291339464771989622907027621153398088495) >> 128); logValue = logFloor == logUpper ? logFloor : getSqrtPrice(logUpper) <= sqrtPrice_96 ? logUpper : logFloor; } function getLogSqrtPriceFU(uint160 sqrtPrice_96) internal pure returns (int24 logFloor, int24 logUpper) { // second inequality must be < because the price can nevex reach the price at the max tick require(sqrtPrice_96 >= MIN_SQRT_PRICE && sqrtPrice_96 < MAX_SQRT_PRICE, 'R'); uint256 sqrtPrice_128 = uint256(sqrtPrice_96) << 32; uint256 x = sqrtPrice_128; uint256 m = 0; assembly { let y := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(5, gt(x, 0xFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(4, gt(x, 0xFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(3, gt(x, 0xFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(2, gt(x, 0xF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(1, gt(x, 0x3)) m := or(m, y) x := shr(y, x) } assembly { let y := gt(x, 0x1) m := or(m, y) } if (m >= 128) x = sqrtPrice_128 >> (m - 127); else x = sqrtPrice_128 << (127 - m); int256 l2 = (int256(m) - 128) << 64; assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(63, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(62, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(61, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(60, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(59, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(58, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(57, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(56, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(55, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(54, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(53, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(52, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(51, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(50, y)) } int256 ls10001 = l2 * 255738958999603826347141; logFloor = int24((ls10001 - 3402992956809132418596140100660247210) >> 128); logUpper = int24((ls10001 + 291339464771989622907027621153398088495) >> 128); } }
@dev current total nIZI.
uint256 public totalNIZI;
5,850,508
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 783, 2078, 290, 6867, 45, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2078, 50, 6867, 45, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xa35A4972D74d4B3e4486163066E5fFed6d62b213/sources/browser/flatgenlenderiron.sol
Liquidate as many assets as possible to `want`, irregardless of slippage, up to `_amountNeeded`. Any excess should be re-invested here as well./if we don't set reserve here withdrawer will be sent our full balance
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); if (_balance >= _amountNeeded) { return (_amountNeeded,0); uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance); if (received >= _amountNeeded) { return (_amountNeeded,0); return (received,0); } } }
3,044,112
[ 1, 4625, 348, 7953, 560, 30, 225, 511, 18988, 350, 340, 487, 4906, 7176, 487, 3323, 358, 1375, 17369, 9191, 9482, 1574, 1060, 2656, 434, 272, 3169, 2433, 16, 731, 358, 1375, 67, 8949, 11449, 8338, 5502, 23183, 1410, 506, 283, 17, 5768, 3149, 2674, 487, 5492, 18, 19, 430, 732, 2727, 1404, 444, 20501, 2674, 598, 9446, 264, 903, 506, 3271, 3134, 1983, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4501, 26595, 340, 2555, 12, 11890, 5034, 389, 8949, 11449, 13, 2713, 3849, 1135, 261, 11890, 5034, 389, 8949, 42, 15656, 16, 2254, 5034, 389, 7873, 13, 288, 203, 3639, 2254, 5034, 389, 12296, 273, 2545, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 309, 261, 67, 12296, 1545, 389, 8949, 11449, 13, 288, 203, 5411, 327, 261, 67, 8949, 11449, 16, 20, 1769, 203, 5411, 2254, 5034, 5079, 273, 389, 1918, 9446, 17358, 24899, 8949, 11449, 300, 389, 12296, 2934, 1289, 24899, 12296, 1769, 203, 5411, 309, 261, 15213, 1545, 389, 8949, 11449, 13, 288, 203, 7734, 327, 261, 67, 8949, 11449, 16, 20, 1769, 203, 7734, 203, 7734, 327, 261, 15213, 16, 20, 1769, 203, 5411, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-05 */ // File: kintarotoken.sol //Telegram: https://t.me/KintaroToken //Twitter: https://twitter.com/kintarotoken pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } } interface 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 ); } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Pair { function factory() external view returns (address); } interface IUniswapV2Router { 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 ); function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // solhint-disable contract Kintaro is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0x99bAD48e3455B750c5B8817bA2fBD4d0b2f39528); address payable public devAddress = payable(0x99bAD48e3455B750c5B8817bA2fBD4d0b2f39528); address payable public liquidityAddress = payable(0x198B8662Ed18fc590E0e259FD7FCC66db13A05FC); address payable public treasuryAddress = payable(0x99bAD48e3455B750c5B8817bA2fBD4d0b2f39528); address private _owner; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; // Anti-whale limits bool public limitsInEffect = true; mapping(address => bool) public blacklist; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10_000_000_000 * 1e9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Kintaro"; string private constant _symbol = "KINTARO"; uint8 private constant _decimals = 9; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _teamFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; // Here is where you set the fee breakdown uint256 public _buyTaxFee = 1; uint256 public _buyLiquidityFee = 2; uint256 public _buyTeamFee = 10; uint256 public _sellTaxFee = 1; uint256 public _sellLiquidityFee = 2; uint256 public _sellTeamFee = 15; // These values are % of team fees to distribute (add extra 0: 333 = 33.3%) // These combined values must be lower than 1000 (aka 100%) // Any leftover goes to marketing address uint256 public _percentTeamFundsToDev = 333; uint256 public _percentTeamFundsToTreasury = 333; uint256 public tradingActiveBlock = 0; // 0 means trading is not active uint256 public _liquidityTokensToSwap; uint256 public _teamTokensToSwap; uint256 public maxTransactionAmount; uint256 public maxWalletAmount; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router public uniswapV2Router; address public uniswapV2Pair; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 teamFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 teamFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedTeamAddress(address team); event UpdatedLiquidityAddress(address liquidity); event OwnerForcedSwapBack(uint256 timestamp); event BoughtEarly(address indexed sniper); event RemovedSniper(address indexed notsnipersupposedly); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() payable { _owner = msg.sender; _rOwned[_owner] = (_rTotal / 1000) * 550; _rOwned[address(this)] = (_rTotal / 1000) * 450; maxTransactionAmount = (_tTotal * 3) / 1000; // 0.3% maxTransactionAmountTxn maxWalletAmount = (_tTotal * 5) / 1000; // 0.5% maxWalletAmount minimumTokensBeforeSwap = (_tTotal * 5) / 10000; // 0.05% swap tokens amount _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; _isExcludedFromFee[treasuryAddress] = true; _isExcludedFromFee[devAddress] = true; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(marketingAddress, true); excludeFromMaxTransaction(liquidityAddress, true); excludeFromMaxTransaction(devAddress, true); excludeFromMaxTransaction(treasuryAddress, true); emit Transfer(address(0), _owner, (_tTotal * 550) / 1000); emit Transfer(address(0), address(this), (_tTotal * 450) / 1000); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // once enabled, can never be turned off function enableTrading() internal onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; } // send tokens and ETH for liquidity to contract directly, then call this (not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch) function launch() external onlyOwner returns (bool) { require(!tradingActive, "Trading is already active, cannot relaunch."); enableTrading(); IUniswapV2Router _uniswapV2Router = IUniswapV2Router( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); require( address(this).balance > 0, "Must have ETH on contract to launch" ); addLiquidity(balanceOf(address(this)), address(this).balance); transferOwnership(_owner); return true; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if (value) { excludeFromReward(pair); } if (!value) { includeInReward(pair); } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require( _excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address." ); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // swap and liquify if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; // If any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } else { // Buy if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; } else if (block.number == tradingActiveBlock + 1) { _taxFee = 0; _liquidityFee = 50; } else { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } // Sell else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; // higher tax if bought in the same block as trading active for 72 hours (sniper protect) if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; } else if (block.number == tradingActiveBlock + 1) { _taxFee = 0; _liquidityFee = 50; } else { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } // Normal transfers do not get taxed } else { removeAllFee(); buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } } _tokenTransfer(from, to, amount, takeFee); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _teamTokensToSwap; // Halve the amount of liquidity tokens uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_teamTokensToSwap).div( totalTokensToSwap ); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev = ethForMarketing.mul(_percentTeamFundsToDev).div( 1000 ); uint256 ethForTreasury = ethForMarketing .mul(_percentTeamFundsToTreasury) .div(1000); ethForMarketing -= ethForDev; ethForMarketing -= ethForTreasury; _liquidityTokensToSwap = 0; _teamTokensToSwap = 0; (bool success, ) = address(marketingAddress).call{ value: ethForMarketing }(""); (success, ) = address(devAddress).call{ value: ethForDev }(""); (success, ) = address(treasuryAddress).call{ value: ethForTreasury }( "" ); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); // send leftover to the marketing wallet so it doesn't get stuck on the contract. if (address(this).balance > 1e17) { (success, ) = address(marketingAddress).call{ value: address(this).balance }(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require( contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract" ); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } // Add to blacklist function addToBlacklist(address account) external onlyOwner { require(account != address(0), "Cannot blacklist 0 address"); blacklist[account] = true; } // Remove from blacklist function removeFromBlacklist(address account) external onlyOwner { require(account != address(0), "Cannot use 0 address"); blacklist[account] = false; } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{ value: ethAmount }( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if (buyOrSellSwitch == BUY) { _liquidityTokensToSwap += (tLiquidity * _buyLiquidityFee) / _liquidityFee; _teamTokensToSwap += (tLiquidity * _buyTeamFee) / _liquidityFee; } else if (buyOrSellSwitch == SELL) { _liquidityTokensToSwap += (tLiquidity * _sellLiquidityFee) / _liquidityFee; _teamTokensToSwap += (tLiquidity * _sellTeamFee) / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function setMaxTransactionAmount(uint256 newMaxBuy) external onlyOwner { require(newMaxBuy > 0, "Cannot be 0"); maxTransactionAmount = (_tTotal * newMaxBuy) / 1000; } function setMaxWallet(uint256 newMaxWallet) external onlyOwner { require(newMaxWallet > 0, "Cannot be 0"); maxWalletAmount = (_tTotal * newMaxWallet) / 1000; } function setBuyFee( uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyTeamFee ) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyTeamFee = buyTeamFee; require( _buyTaxFee + _buyLiquidityFee + _buyTeamFee <= 100, "Must keep buy taxes below 100%" ); emit SetBuyFee(buyTeamFee, buyLiquidityFee, buyTaxFee); } function setSellFee( uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellTeamFee ) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellTeamFee = sellTeamFee; require( _sellTaxFee + _sellLiquidityFee + _sellTeamFee <= 100, "Must keep sell taxes below 100%" ); emit SetSellFee(sellTeamFee, sellLiquidityFee, sellTaxFee); } function setTeamSplit(uint256 treasurySplit, uint256 devSplit) external onlyOwner { require(treasurySplit + devSplit < 1000, "Split over 100%"); _percentTeamFundsToTreasury = treasurySplit; _percentTeamFundsToDev = devSplit; } function setMarketingAddress(address _marketingAddress) external onlyOwner { require( _marketingAddress != address(0), "_marketingAddress address cannot be 0" ); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedTeamAddress(_marketingAddress); } function setLiquidityAddress(address _liquidityAddress) public onlyOwner { require( _liquidityAddress != address(0), "_liquidityAddress address cannot be 0" ); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress); } function setDeveloperAddress(address _devAddress) external onlyOwner { require(_devAddress != address(0), "Cannot be 0 address"); devAddress = payable(_devAddress); _isExcludedFromFee[devAddress] = true; } function setTreasuryAddress(address _treasuryAddress) external onlyOwner { require(_treasuryAddress != address(0), "Cannot be 0 address"); treasuryAddress = payable(_treasuryAddress); _isExcludedFromFee[treasuryAddress] = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck before launch function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; (success, ) = address(msg.sender).call{ value: address(this).balance }( "" ); } }
solhint-disable Anti-whale limits these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. Here is where you set the fee breakdown These values are % of team fees to distribute (add extra 0: 333 = 33.3%) These combined values must be lower than 1000 (aka 100%) Any leftover goes to marketing address store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract Kintaro is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0x99bAD48e3455B750c5B8817bA2fBD4d0b2f39528); address payable public devAddress = payable(0x99bAD48e3455B750c5B8817bA2fBD4d0b2f39528); address payable public liquidityAddress = payable(0x198B8662Ed18fc590E0e259FD7FCC66db13A05FC); address payable public treasuryAddress = payable(0x99bAD48e3455B750c5B8817bA2fBD4d0b2f39528); address private _owner; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; bool public limitsInEffect = true; mapping(address => bool) public blacklist; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10_000_000_000 * 1e9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Kintaro"; string private constant _symbol = "KINTARO"; uint8 private constant _decimals = 9; uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _teamFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public _buyTaxFee = 1; uint256 public _buyLiquidityFee = 2; uint256 public _buyTeamFee = 10; uint256 public _sellTaxFee = 1; uint256 public _sellLiquidityFee = 2; uint256 public _sellTeamFee = 15; uint256 public _percentTeamFundsToDev = 333; uint256 public _percentTeamFundsToTreasury = 333; uint256 public _liquidityTokensToSwap; uint256 public _teamTokensToSwap; uint256 public maxTransactionAmount; uint256 public maxWalletAmount; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router public uniswapV2Router; address public uniswapV2Pair; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 teamFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 teamFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedTeamAddress(address team); event UpdatedLiquidityAddress(address liquidity); event OwnerForcedSwapBack(uint256 timestamp); event BoughtEarly(address indexed sniper); event RemovedSniper(address indexed notsnipersupposedly); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() payable { _owner = msg.sender; _rOwned[_owner] = (_rTotal / 1000) * 550; _rOwned[address(this)] = (_rTotal / 1000) * 450; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; _isExcludedFromFee[treasuryAddress] = true; _isExcludedFromFee[devAddress] = true; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(marketingAddress, true); excludeFromMaxTransaction(liquidityAddress, true); excludeFromMaxTransaction(devAddress, true); excludeFromMaxTransaction(treasuryAddress, true); emit Transfer(address(0), _owner, (_tTotal * 550) / 1000); emit Transfer(address(0), address(this), (_tTotal * 450) / 1000); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function enableTrading() internal onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; } function launch() external onlyOwner returns (bool) { require(!tradingActive, "Trading is already active, cannot relaunch."); enableTrading(); IUniswapV2Router _uniswapV2Router = IUniswapV2Router( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); require( address(this).balance > 0, "Must have ETH on contract to launch" ); addLiquidity(balanceOf(address(this)), address(this).balance); transferOwnership(_owner); return true; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if (value) { excludeFromReward(pair); } if (!value) { includeInReward(pair); } } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if (value) { excludeFromReward(pair); } if (!value) { includeInReward(pair); } } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if (value) { excludeFromReward(pair); } if (!value) { includeInReward(pair); } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require( _excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address." ); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require( _excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address." ); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _tokenTransfer(from, to, amount, takeFee); } else if ( 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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _tokenTransfer(from, to, amount, takeFee); } if ( 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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _tokenTransfer(from, to, amount, takeFee); } } else if (block.number == tradingActiveBlock + 1) { } 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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _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"); require(!blacklist[from], "From address blacklist. Contact admin"); require(!blacklist[to], "To address blacklist. Contact admin"); if (!tradingActive) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet." ); } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ) { if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } if (!_isExcludedMaxTransactionAmount[to]) { require( balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded" ); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add( _teamTokensToSwap ); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; if (automatedMarketMakerPairs[from]) { removeAllFee(); buyOrSellSwitch = BUY; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyTeamFee; } } else if (automatedMarketMakerPairs[to]) { removeAllFee(); buyOrSellSwitch = SELL; if (block.number == tradingActiveBlock) { _taxFee = 0; _liquidityFee = 90; _taxFee = 0; _liquidityFee = 50; _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellTeamFee; } removeAllFee(); } } _tokenTransfer(from, to, amount, takeFee); } } else if (block.number == tradingActiveBlock + 1) { } else { } else { function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _teamTokensToSwap; uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_teamTokensToSwap).div( totalTokensToSwap ); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev = ethForMarketing.mul(_percentTeamFundsToDev).div( 1000 ); uint256 ethForTreasury = ethForMarketing .mul(_percentTeamFundsToTreasury) .div(1000); ethForMarketing -= ethForDev; ethForMarketing -= ethForTreasury; _liquidityTokensToSwap = 0; _teamTokensToSwap = 0; (bool success, ) = address(marketingAddress).call{ value: ethForMarketing }(""); "" ); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); if (address(this).balance > 1e17) { (success, ) = address(marketingAddress).call{ value: address(this).balance }(""); } } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _teamTokensToSwap; uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_teamTokensToSwap).div( totalTokensToSwap ); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev = ethForMarketing.mul(_percentTeamFundsToDev).div( 1000 ); uint256 ethForTreasury = ethForMarketing .mul(_percentTeamFundsToTreasury) .div(1000); ethForMarketing -= ethForDev; ethForMarketing -= ethForTreasury; _liquidityTokensToSwap = 0; _teamTokensToSwap = 0; (bool success, ) = address(marketingAddress).call{ value: ethForMarketing }(""); "" ); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); if (address(this).balance > 1e17) { (success, ) = address(marketingAddress).call{ value: address(this).balance }(""); } } (success, ) = address(devAddress).call{ value: ethForDev }(""); (success, ) = address(treasuryAddress).call{ value: ethForTreasury }( function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _teamTokensToSwap; uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_teamTokensToSwap).div( totalTokensToSwap ); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev = ethForMarketing.mul(_percentTeamFundsToDev).div( 1000 ); uint256 ethForTreasury = ethForMarketing .mul(_percentTeamFundsToTreasury) .div(1000); ethForMarketing -= ethForDev; ethForMarketing -= ethForTreasury; _liquidityTokensToSwap = 0; _teamTokensToSwap = 0; (bool success, ) = address(marketingAddress).call{ value: ethForMarketing }(""); "" ); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); if (address(this).balance > 1e17) { (success, ) = address(marketingAddress).call{ value: address(this).balance }(""); } } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _teamTokensToSwap; uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_teamTokensToSwap).div( totalTokensToSwap ); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev = ethForMarketing.mul(_percentTeamFundsToDev).div( 1000 ); uint256 ethForTreasury = ethForMarketing .mul(_percentTeamFundsToTreasury) .div(1000); ethForMarketing -= ethForDev; ethForMarketing -= ethForTreasury; _liquidityTokensToSwap = 0; _teamTokensToSwap = 0; (bool success, ) = address(marketingAddress).call{ value: ethForMarketing }(""); "" ); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); if (address(this).balance > 1e17) { (success, ) = address(marketingAddress).call{ value: address(this).balance }(""); } } function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require( contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract" ); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } function addToBlacklist(address account) external onlyOwner { require(account != address(0), "Cannot blacklist 0 address"); blacklist[account] = true; } function removeFromBlacklist(address account) external onlyOwner { require(account != address(0), "Cannot use 0 address"); blacklist[account] = false; } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, liquidityAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{ value: ethAmount }( function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if (buyOrSellSwitch == BUY) { _liquidityTokensToSwap += (tLiquidity * _buyLiquidityFee) / _liquidityFee; _teamTokensToSwap += (tLiquidity * _buyTeamFee) / _liquidityFee; _liquidityTokensToSwap += (tLiquidity * _sellLiquidityFee) / _liquidityFee; _teamTokensToSwap += (tLiquidity * _sellTeamFee) / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeLiquidity(uint256 tLiquidity) private { if (buyOrSellSwitch == BUY) { _liquidityTokensToSwap += (tLiquidity * _buyLiquidityFee) / _liquidityFee; _teamTokensToSwap += (tLiquidity * _buyTeamFee) / _liquidityFee; _liquidityTokensToSwap += (tLiquidity * _sellLiquidityFee) / _liquidityFee; _teamTokensToSwap += (tLiquidity * _sellTeamFee) / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } } else if (buyOrSellSwitch == SELL) { function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function setMaxTransactionAmount(uint256 newMaxBuy) external onlyOwner { require(newMaxBuy > 0, "Cannot be 0"); maxTransactionAmount = (_tTotal * newMaxBuy) / 1000; } function setMaxWallet(uint256 newMaxWallet) external onlyOwner { require(newMaxWallet > 0, "Cannot be 0"); maxWalletAmount = (_tTotal * newMaxWallet) / 1000; } function setBuyFee( uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyTeamFee ) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyTeamFee = buyTeamFee; require( _buyTaxFee + _buyLiquidityFee + _buyTeamFee <= 100, "Must keep buy taxes below 100%" ); emit SetBuyFee(buyTeamFee, buyLiquidityFee, buyTaxFee); } function setSellFee( uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellTeamFee ) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellTeamFee = sellTeamFee; require( _sellTaxFee + _sellLiquidityFee + _sellTeamFee <= 100, "Must keep sell taxes below 100%" ); emit SetSellFee(sellTeamFee, sellLiquidityFee, sellTaxFee); } function setTeamSplit(uint256 treasurySplit, uint256 devSplit) external onlyOwner { require(treasurySplit + devSplit < 1000, "Split over 100%"); _percentTeamFundsToTreasury = treasurySplit; _percentTeamFundsToDev = devSplit; } function setMarketingAddress(address _marketingAddress) external onlyOwner { require( _marketingAddress != address(0), "_marketingAddress address cannot be 0" ); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedTeamAddress(_marketingAddress); } function setLiquidityAddress(address _liquidityAddress) public onlyOwner { require( _liquidityAddress != address(0), "_liquidityAddress address cannot be 0" ); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress); } function setDeveloperAddress(address _devAddress) external onlyOwner { require(_devAddress != address(0), "Cannot be 0 address"); devAddress = payable(_devAddress); _isExcludedFromFee[devAddress] = true; } function setTreasuryAddress(address _treasuryAddress) external onlyOwner { require(_treasuryAddress != address(0), "Cannot be 0 address"); treasuryAddress = payable(_treasuryAddress); _isExcludedFromFee[treasuryAddress] = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; "" ); } (success, ) = address(msg.sender).call{ value: address(this).balance }( }
7,843,337
[ 1, 4625, 348, 7953, 560, 30, 225, 3704, 11317, 17, 8394, 18830, 77, 17, 3350, 5349, 8181, 4259, 924, 854, 7517, 9816, 11078, 3241, 2898, 336, 15345, 364, 3614, 7827, 16, 1496, 326, 12150, 1221, 518, 15857, 358, 1440, 598, 783, 6835, 18, 13743, 353, 1625, 1846, 444, 326, 14036, 898, 2378, 8646, 924, 854, 738, 434, 5927, 1656, 281, 358, 25722, 261, 1289, 2870, 374, 30, 890, 3707, 273, 13159, 18, 23, 9, 13, 8646, 8224, 924, 1297, 506, 2612, 2353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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 474, 14349, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 1758, 8843, 429, 1071, 13667, 310, 1887, 273, 203, 3639, 8843, 429, 12, 20, 92, 2733, 70, 1880, 8875, 73, 5026, 2539, 38, 27, 3361, 71, 25, 38, 5482, 4033, 70, 37, 22, 74, 18096, 24, 72, 20, 70, 22, 74, 5520, 25, 6030, 1769, 203, 565, 1758, 8843, 429, 1071, 4461, 1887, 273, 203, 3639, 8843, 429, 12, 20, 92, 2733, 70, 1880, 8875, 73, 5026, 2539, 38, 27, 3361, 71, 25, 38, 5482, 4033, 70, 37, 22, 74, 18096, 24, 72, 20, 70, 22, 74, 5520, 25, 6030, 1769, 203, 565, 1758, 8843, 429, 1071, 4501, 372, 24237, 1887, 273, 203, 3639, 8843, 429, 12, 20, 92, 30234, 38, 5292, 8898, 2671, 2643, 7142, 6162, 20, 41, 20, 73, 2947, 29, 16894, 27, 4488, 39, 6028, 1966, 3437, 37, 6260, 4488, 1769, 203, 565, 1758, 8843, 429, 1071, 9787, 345, 22498, 1887, 273, 203, 3639, 8843, 429, 12, 20, 92, 2733, 70, 1880, 8875, 73, 5026, 2539, 38, 27, 3361, 71, 25, 38, 5482, 4033, 70, 37, 22, 74, 18096, 24, 72, 20, 70, 22, 74, 5520, 25, 6030, 1769, 203, 203, 565, 1758, 3238, 389, 8443, 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, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 11709, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 565, 1758, 8526, 3238, 389, 24602, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 1728, 67, 3784, 67, 3784, 67, 3784, 380, 404, 73, 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, 533, 3238, 5381, 389, 529, 273, 315, 47, 474, 14349, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 47, 3217, 985, 51, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 11515, 7731, 14667, 273, 389, 8066, 14667, 31, 203, 203, 565, 2254, 5034, 3238, 389, 10035, 14667, 31, 203, 203, 565, 2254, 5034, 3238, 389, 549, 372, 24237, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 11515, 48, 18988, 24237, 14667, 273, 389, 549, 372, 24237, 14667, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 10937, 61, 273, 404, 31, 203, 565, 2254, 5034, 3238, 5381, 20853, 48, 273, 576, 31, 203, 565, 2254, 5034, 3238, 5381, 4235, 17598, 273, 890, 31, 203, 565, 2254, 5034, 3238, 30143, 1162, 55, 1165, 10200, 31, 203, 203, 203, 565, 2254, 5034, 1071, 389, 70, 9835, 7731, 14667, 273, 404, 31, 203, 565, 2254, 5034, 1071, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 576, 31, 203, 565, 2254, 5034, 1071, 389, 70, 9835, 8689, 14667, 273, 1728, 31, 203, 203, 565, 2254, 5034, 1071, 389, 87, 1165, 7731, 14667, 273, 404, 31, 203, 565, 2254, 5034, 1071, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 576, 31, 203, 565, 2254, 5034, 1071, 389, 87, 1165, 8689, 14667, 273, 4711, 31, 203, 203, 565, 2254, 5034, 1071, 389, 8849, 8689, 42, 1074, 11634, 8870, 273, 890, 3707, 31, 203, 565, 2254, 5034, 1071, 389, 8849, 8689, 42, 1074, 11634, 56, 266, 345, 22498, 273, 890, 3707, 31, 203, 203, 203, 565, 2254, 5034, 1071, 389, 549, 372, 24237, 5157, 774, 12521, 31, 203, 565, 2254, 5034, 1071, 389, 10035, 5157, 774, 12521, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 6275, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 291, 16461, 2747, 3342, 6275, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 18472, 690, 3882, 278, 12373, 10409, 31, 203, 203, 565, 2254, 5034, 3238, 5224, 5157, 4649, 12521, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 316, 12521, 1876, 48, 18988, 1164, 31, 203, 565, 1426, 1071, 7720, 1876, 48, 18988, 1164, 1526, 273, 629, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 203, 565, 871, 12738, 1876, 48, 18988, 1164, 1526, 7381, 12, 6430, 3696, 1769, 203, 565, 871, 12738, 1876, 48, 18988, 1164, 12, 203, 3639, 2254, 5034, 2430, 12521, 1845, 16, 203, 3639, 2254, 5034, 13750, 8872, 16, 203, 3639, 2254, 5034, 2430, 5952, 48, 18988, 24237, 203, 565, 11272, 203, 203, 565, 871, 12738, 1584, 44, 1290, 5157, 12, 11890, 5034, 3844, 382, 16, 1758, 8526, 589, 1769, 203, 203, 565, 871, 12738, 5157, 1290, 1584, 44, 12, 11890, 5034, 3844, 382, 16, 1758, 8526, 589, 1769, 203, 203, 565, 871, 1000, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 3082, 16, 1426, 460, 1769, 203, 203, 565, 871, 20760, 1265, 17631, 1060, 12, 2867, 8845, 1887, 1769, 203, 203, 565, 871, 12672, 382, 17631, 1060, 12, 2867, 5849, 1887, 1769, 203, 203, 565, 871, 20760, 1265, 14667, 12, 2867, 8845, 1887, 1769, 203, 203, 565, 871, 12672, 382, 14667, 12, 2867, 5849, 1887, 1769, 203, 203, 565, 871, 1000, 38, 9835, 14667, 12, 11890, 5034, 5927, 14667, 16, 2254, 5034, 4501, 372, 24237, 14667, 16, 2254, 5034, 3037, 14667, 1769, 203, 203, 565, 871, 1000, 55, 1165, 14667, 12, 11890, 5034, 5927, 14667, 16, 2254, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "@1001-digital/erc721-extensions/contracts/WithContractMetaData.sol"; import "@1001-digital/erc721-extensions/contracts/WithIPFSMetaData.sol"; import "@1001-digital/erc721-extensions/contracts/WithWithdrawals.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@%#*++===--===++*#%@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@%*+------===++===------=*%@@@@@@@@@@@@ // @@@@@@@@@@*=---=+*#%@@@@@@@@@@%#*+=---=*@@@@@@@@@@ // @@@@@@@@*---=*%@@@@@@@@@@@@@@@@@@@@#+=---*@@@@@@@@ // @@@@@@#--==#@@@@@@@@@@@@@@@@@@@@@@@@@@#==--#@@@@@@ // @@@@@+-==*@@%%############*********[email protected]@@@@ // @@@@===+#@#+++================----:::::-*#[email protected]@@@ // @@@+=++%@@#[email protected]@#===*@@@ // @@#-++#@@@@@@@@@@@@@@++***#@@@@@@@@@@@@@@@@*+++%@@ // @@[email protected]@@@@@@@@@@@@@%:****#@@@@@@@@@@@@@@@@@=++*@@ // @@-+**@@@@@@@@@@@@@@-:****@@@@@@@@@@@@@@@@@@+++*@@ // @@-+*#@@@@@@@@@@@@@% -***%@@@@@@@@@@@@@@@@@@++**@@ // @@-+**@@@@@@@@@@@@@- -***@@@@@@@@@@@@@@@@@@@++**@@ // @@=+**@@@@@@@@@@@@% -**%@@@@@@@@@@@@@@@@@@@=**#@@ // @@#=***@@@@@@@@@@@- =*#@@@@@@@@@@@@@@@@@@@++**@@@ // @@@++**#@@@@@@@@@% =*%@@@@@@@@@@@@@@@@@@#+**#@@@ // @@@@=+**#@@@@@@@@= =#@@@@@@@@@@@@@@@@@@*+**#@@@@ // @@@@@++***%@@@@@%. =%@@@@@@@@@@@@@@@@%++**#@@@@@ // @@@@@@#=+**#%@@@#: [email protected]@@@@@@@@@@@@@@%*+***%@@@@@@ // @@@@@@@@*=+***#@@#=-:#@@@@@@@@@@@@%#*++++*@@@@@@@@ // @@@@@@@@@@*=++***##%%@@@@@@@@%%#*++++++#@@@@@@@@@@ // @@@@@@@@@@@@%*+=+++**++++++++++++==+*%@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@%#*+==========+*#%@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // // _____ ____ ___ _ _ ___ ____ // |_ _|| _ \ / _ \ | \ | ||_ _|/ ___| // | | | |_) || | | || \| | | || | // | | | _ < | |_| || |\ | | || |___ // |_| |_| \_\ \___/ |_| \_||___|\____| // ____ _ ____ ___ _ _ ____ // | _ \ / \ / ___|_ _| \ | |/ ___| // | |_) | / _ \| | | || \| | | _ // | _ < / ___ \ |___ | || |\ | |_| | // |_| \_\/_/ \_\____|___|_| \_|\____| // // ================================================ // 5,555 3D toy cars ready to race! // Race with us! https://discord.gg/A4sFesmFUq // ================================================ // @author c0 // @dev shoutouts: // - Jonathan Snow and Tom Hirst: https://shiny.mirror.xyz/OUampBbIz9ebEicfGnQf5At_ReMHlZy0tB4glb9xQ0E // - Chance: https://nftchance.medium.com/the-gas-efficient-way-of-building-and-launching-an-erc721-nft-project-for-2022-b3b1dac5f2e1 contract TronicRacer is ERC721, Ownable, WithIPFSMetaData, WithContractMetaData, WithWithdrawals { using Counters for Counters.Counter; Counters.Counter private _nextTokenId; uint256 public constant MAX_SUPPLY = 5555; uint256 public constant MAX_PER_MINT = 5; uint256 public constant PRICE = 0.05 ether; uint256 public constant RESERVES = 55; bool public reservesCollected = false; string public constant PROVENANCE = "32a2edee8d3fb4a1e2f606504bc39a9ee03e0379aba7a420c5a48281911ad423"; // In seconds. Note: subtract 1 second to reduce gas when comparing uint256 public miniRacerSaleStartTimestamp = 0; uint256 public whitelistSaleStartTimestamp = 0; uint256 public saleStartTimestamp = 0; address public miniRacerContractAddress; mapping(uint256 => uint256) private redeemedMiniRacers; address public proxyRegistryAddress; mapping(address => bool) public projectProxy; bytes32 public whitelistMerkleRoot; constructor( string memory _cid, string memory _contractMetaDataURI, address _miniRacerContractAddress, address _proxyRegistryAddress, uint256 _miniRacerSaleStartTimestamp, uint256 _whitelistSaleStartTimestamp, uint256 _saleStartTimestamp ) ERC721("TronicRacer", "TRONICRACER") WithIPFSMetaData(_cid) WithContractMetaData(_contractMetaDataURI) { miniRacerContractAddress = _miniRacerContractAddress; proxyRegistryAddress = _proxyRegistryAddress; miniRacerSaleStartTimestamp = _miniRacerSaleStartTimestamp; whitelistSaleStartTimestamp = _whitelistSaleStartTimestamp; saleStartTimestamp = _saleStartTimestamp; _nextTokenId.increment(); // Start IDs at 1 } function mint(uint256 amount) external payable { require(saleStarted(), "Sale has not started"); require(totalSupply() + amount <= MAX_SUPPLY, "Racers are sold out!"); require(amount > 0, "You must mint at least one."); require(msg.value == PRICE * amount, "Too little or too much ETH sent"); require(amount <= MAX_PER_MINT, "Maximum of 5 per transaction"); for (uint256 index = 0; index < amount; index++) { _mintAndIncrement(); } } // Mint and redeem Mini Racer tokens for Tronic Racer tokens function mintWithMiniRacer(uint256 amount, uint256[] memory tokensToRedeem) external payable { require(miniRacerSaleStarted(), "Mini Racer MOGO has not started"); require(amount > 0, "You must mint at least one."); require(amount >= tokensToRedeem.length, "You can only redeem as many as you purchase."); // Ensure that the tokens paid for PLUS the number of redeemed mini racer tokens are available // Prevents accidentally over minting beyond 5,555 require(totalSupply() + amount + tokensToRedeem.length <= MAX_SUPPLY, "Racers are sold out!"); require(msg.value == PRICE * amount, "Too little or too much ETH sent"); require(amount <= MAX_PER_MINT, "Maximum of 5 per transaction"); // MOGO: mint one, get one for (uint256 t = 0; t < tokensToRedeem.length; t++) { require(_ownsMiniRacer(tokensToRedeem[t]) == true, "You must own the mini racer token to redeem it."); require( miniRacerAvailableToRedeem(tokensToRedeem[t]) == true, "One of the mini racers was already redeemed." ); redeemedMiniRacers[tokensToRedeem[t]] = 1; _mintAndIncrement(); } // Mint what was paid for for (uint256 index = 0; index < amount; index++) { _mintAndIncrement(); } } function mintFromWhitelist(uint256 amount, bytes32[] calldata proof) external payable { require(whitelistSaleStarted(), "Whitelist sale has not started"); string memory payload = string(abi.encodePacked(_msgSender())); require(_verify(_leaf(payload), proof), "Invalid Merkle Tree proof given."); require(totalSupply() + amount <= MAX_SUPPLY, "Racers are sold out!"); require(amount > 0, "You must mint at least one."); require(msg.value == PRICE * amount, "Too little or too much ETH sent"); require(amount <= MAX_PER_MINT, "Maximum of 5 per transaction"); for (uint256 index = 0; index < amount; index++) { _mintAndIncrement(); } } function remainingSupply() public view returns (uint256) { return MAX_SUPPLY - totalSupply(); } function totalSupply() public view returns (uint256) { return _nextTokenId.current() - 1; } function miniRacerSaleStarted() public view returns (bool) { return block.timestamp > miniRacerSaleStartTimestamp; } function whitelistSaleStarted() public view returns (bool) { return block.timestamp > whitelistSaleStartTimestamp; } function saleStarted() public view returns (bool) { return block.timestamp > saleStartTimestamp; } function setMiniRacerSaleStart(uint256 _miniRacerSaleStartTimestamp) external onlyOwner { miniRacerSaleStartTimestamp = _miniRacerSaleStartTimestamp; } function setWhitelistSaleStart(uint256 _whitelistSaleStartTimestamp) external onlyOwner { whitelistSaleStartTimestamp = _whitelistSaleStartTimestamp; } function setSaleStart(uint256 _saleStartTimestamp) external onlyOwner { saleStartTimestamp = _saleStartTimestamp; } function setWhitelistMerkleRoot(bytes32 _whitelistMerkleRoot) external onlyOwner { whitelistMerkleRoot = _whitelistMerkleRoot; } function collectReserves() external onlyOwner { require(reservesCollected == false, "Reserves have already been collected"); for (uint256 index = 0; index < RESERVES; index++) { _mintAndIncrement(); } reservesCollected = true; } function miniRacerAvailableToRedeem(uint256 tokenId) public view returns (bool) { if (tokenId > 100 || tokenId < 1) { return false; } return redeemedMiniRacers[tokenId] != 1; } function _ownsMiniRacer(uint256 tokenId) private view returns (bool) { return ITronicMiniRacer(miniRacerContractAddress).ownerOf(tokenId) == msg.sender; } function tokenURI(uint256 tokenId) public view override(WithIPFSMetaData, ERC721) returns (string memory) { return WithIPFSMetaData.tokenURI(tokenId); } function setCID(string memory _cid) external onlyOwner { cid = _cid; } function _mintAndIncrement() private { _safeMint(_msgSender(), _nextTokenId.current()); _nextTokenId.increment(); } function _leaf(string memory payload) private pure returns (bytes32) { return keccak256(abi.encodePacked(payload)); } function _verify(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { return MerkleProof.verify(proof, whitelistMerkleRoot, leaf); } function _baseURI() internal view override(WithIPFSMetaData, ERC721) returns (string memory) { return WithIPFSMetaData._baseURI(); } function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } function flipProxyState(address proxyAddress) public onlyOwner { projectProxy[proxyAddress] = !projectProxy[proxyAddress]; } function isApprovedForAll(address _owner, address operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator]) return true; return super.isApprovedForAll(_owner, operator); } } interface ITronicMiniRacer { function ownerOf(uint256 tokenId) external view returns (address owner); } contract OwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /// @author 1001.digital /// @title Link to your collection's contract meta data right from within your smart contract. abstract contract WithContractMetaData is Ownable { // The URI to the contract meta data. string private _contractURI; /// Instanciate the contract /// @param uri the URL to the contract metadata constructor (string memory uri) { _contractURI = uri; } /// Set the contract metadata URI /// @param uri the URI to set /// @dev the contract metadata should link to a metadata JSON file. function setContractURI(string memory uri) public virtual onlyOwner { _contractURI = uri; } /// Expose the contractURI /// @return the contract metadata URI. function contractURI() public view virtual returns (string memory) { return _contractURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @author 1001.digital /// @title Handle NFT Metadata stored on IPFS abstract contract WithIPFSMetaData is ERC721 { using Strings for uint256; /// @dev The content identifier of the folder containing all JSON files. string public cid; /// Instantiate the contract /// @param _cid the content identifier for the token metadata. /// @dev be careful & make sure your metadata is correct - you can't change this constructor (string memory _cid) { _setCID(_cid); } /// Get the tokenURI for a tokenID /// @param tokenId the token id for which to get the matadata URL /// @dev links to the metadata json file on IPFS. /// @return the URL to the token metadata file function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); // We don't check whether the _baseURI is set like in the OpenZeppelin implementation // as we're deploying the contract with the CID. return string(abi.encodePacked( _baseURI(), "/", tokenId.toString(), "/metadata.json" )); } /// Configure the baseURI for the tokenURI method. /// @dev override the standard OpenZeppelin implementation /// @return the IPFS base uri function _baseURI() internal view virtual override returns (string memory) { return string(abi.encodePacked("ipfs://", cid)); } /// Set the content identifier for this collection. /// @param _cid the new content identifier /// @dev update the content identifier for this nft. function _setCID(string memory _cid) internal virtual { cid = _cid; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /// @author 1001.digital /// @title An extension that enables the contract owner to withdraw funds stored in the contract. abstract contract WithWithdrawals is Ownable { /// Withdraws the ETH stored in the contract. /// @dev only the owner can withdraw funds. function withdraw() onlyOwner public { payable(owner()).transfer(address(this).balance); } } // 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/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Emitted when `tokenId` token is transferred from `from` to `to`./* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token./* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets./* @dev Returns the number of tokens in ``owner``'s account./* @dev Returns the owner of the `tokenId` token. Requirements: - `tokenId` must exist./* @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./* @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./* @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./* @dev Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist./* @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./* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. See {setApprovalForAll}/* @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./ SPDX-License-Identifier: MIT OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)* @title Counters @author Matt Condon (@shrugs) @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number of elements in a mapping, issuing ERC721 ids, or counting request ids. Include with `using Counters for Counters.Counter;`/
library Counters { function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; } pragma solidity ^0.8.0; struct Counter { } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } }
1,367,814
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 512, 7948, 1347, 1375, 2316, 548, 68, 1147, 353, 906, 4193, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 20308, 632, 5206, 512, 7948, 1347, 1375, 8443, 68, 19808, 1375, 25990, 68, 358, 10680, 326, 1375, 2316, 548, 68, 1147, 18, 20308, 632, 5206, 512, 7948, 1347, 1375, 8443, 68, 19808, 578, 24960, 21863, 25990, 24065, 1375, 9497, 68, 358, 10680, 777, 434, 2097, 7176, 18, 20308, 632, 5206, 2860, 326, 1300, 434, 2430, 316, 12176, 8443, 10335, 11, 87, 2236, 18, 20308, 632, 5206, 2860, 326, 3410, 434, 326, 1375, 2316, 548, 68, 1147, 18, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 20308, 632, 5206, 348, 1727, 2357, 29375, 1375, 2316, 548, 68, 1147, 628, 1375, 2080, 68, 358, 1375, 869, 9191, 6728, 1122, 716, 6835, 12045, 854, 18999, 434, 326, 4232, 39, 27, 5340, 1771, 358, 5309, 2430, 628, 3832, 21238, 8586, 18, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 1005, 471, 506, 16199, 635, 1375, 2080, 8338, 300, 971, 326, 4894, 353, 486, 1375, 2080, 9191, 518, 1297, 506, 1240, 2118, 2935, 358, 3635, 333, 1147, 635, 3344, 288, 12908, 537, 97, 578, 288, 542, 23461, 1290, 1595, 5496, 300, 971, 1375, 869, 68, 21368, 358, 279, 13706, 6835, 16, 518, 1297, 2348, 288, 45, 654, 39, 27, 5340, 12952, 17, 265, 654, 39, 27, 5340, 8872, 5779, 1492, 353, 2566, 12318, 279, 4183, 7412, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 20308, 632, 5206, 2604, 18881, 1375, 2316, 548, 68, 1147, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 9744, 30, 10858, 434, 333, 707, 353, 19169, 477, 11349, 16, 999, 288, 4626, 5912, 1265, 97, 17334, 3323, 18, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 506, 16199, 635, 1375, 2080, 8338, 300, 971, 326, 4894, 353, 486, 1375, 2080, 9191, 518, 1297, 506, 20412, 358, 3635, 333, 1147, 635, 3344, 288, 12908, 537, 97, 578, 288, 542, 23461, 1290, 1595, 5496, 7377, 1282, 279, 288, 5912, 97, 871, 18, 20308, 632, 5206, 611, 3606, 4132, 358, 1375, 869, 68, 358, 7412, 1375, 2316, 548, 68, 1147, 358, 4042, 2236, 18, 1021, 23556, 353, 16054, 1347, 326, 1147, 353, 906, 4193, 18, 5098, 279, 2202, 2236, 848, 506, 20412, 622, 279, 813, 16, 1427, 6617, 6282, 326, 3634, 1758, 22655, 2416, 6617, 4524, 18, 29076, 30, 300, 1021, 4894, 1297, 4953, 326, 1147, 578, 506, 392, 20412, 3726, 18, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 7377, 1282, 392, 288, 23461, 97, 871, 18, 20308, 632, 5206, 2860, 326, 2236, 20412, 364, 1375, 2316, 548, 68, 1147, 18, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 20308, 632, 5206, 1716, 685, 537, 578, 1206, 1375, 9497, 68, 487, 392, 3726, 364, 326, 4894, 18, 7692, 3062, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 9354, 87, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 16644, 5471, 19, 474, 26362, 19, 45, 654, 39, 28275, 18, 18281, 14432, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 1958, 9354, 288, 203, 565, 289, 203, 203, 565, 445, 783, 12, 4789, 2502, 3895, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 3895, 6315, 1132, 31, 203, 565, 289, 203, 203, 565, 445, 5504, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 22893, 288, 203, 5411, 3895, 6315, 1132, 1011, 404, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 5504, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 22893, 288, 203, 5411, 3895, 6315, 1132, 1011, 404, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 15267, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 2254, 5034, 460, 273, 3895, 6315, 1132, 31, 203, 3639, 2583, 12, 1132, 405, 374, 16, 315, 4789, 30, 15267, 9391, 8863, 203, 3639, 22893, 288, 203, 5411, 3895, 6315, 1132, 273, 460, 300, 404, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 15267, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 2254, 5034, 460, 273, 3895, 6315, 1132, 31, 203, 3639, 2583, 12, 1132, 405, 374, 16, 315, 4789, 30, 15267, 9391, 8863, 203, 3639, 22893, 288, 203, 5411, 3895, 6315, 1132, 273, 460, 300, 404, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 2715, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 3895, 6315, 1132, 273, 374, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: 0x32cf691c1a07677e68af4b315fdb6a5fe65703ee //Contract name: Bitwords //Balance: 0.001 Ether //Verification Date: 6/23/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.23; /** * @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; // A hashmap to help keep track of list of all owners mapping(address => uint) public allOwnersMap; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; allOwnersMap[msg.sender] = 1; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "You're not the owner!"); _; } /** * @dev Throws if called by any account other than the all owners in the history of * the smart contract. */ modifier onlyAnyOwners() { require(allOwnersMap[msg.sender] == 1, "You're not the owner or never were the owner!"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; // Keep track of list of owners allOwnersMap[newOwner] = 1; } // transfer ownership event event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); } /** * @title Suicidable * * @dev Suicidable is special contract with functions to suicide. This is a security measure added in * incase Bitwords gets hacked. */ contract Suicidable is Ownable { bool public hasSuicided = false; /** * @dev Throws if called the contract has not yet suicided */ modifier hasNotSuicided() { require(hasSuicided == false, "Contract has suicided!"); _; } /** * @dev Suicides the entire smart contract */ function suicideContract() public onlyAnyOwners { hasSuicided = true; emit SuicideContract(msg.sender); } // suicide contract event event SuicideContract(address indexed owner); } /** * @title Migratable * * @dev Migratable is special contract which allows the funds of a smart-contact to be migrated * to a new smart contract. */ contract Migratable is Suicidable { bool public hasRequestedForMigration = false; uint public requestedForMigrationAt = 0; address public migrationDestination; function() public payable { } /** * @dev Allows for a migration request to be created, all migrations requests * are timelocked by 7 days. * * @param destination The destination to send the ether to. */ function requestForMigration(address destination) public onlyOwner { hasRequestedForMigration = true; requestedForMigrationAt = now; migrationDestination = destination; emit MigrateFundsRequested(msg.sender, destination); } /** * @dev Cancels a migration */ function cancelMigration() public onlyOwner hasNotSuicided { hasRequestedForMigration = false; requestedForMigrationAt = 0; emit MigrateFundsCancelled(msg.sender); } /** * @dev Approves a migration and suicides the entire smart contract */ function approveMigration(uint gasCostInGwei) public onlyOwner hasNotSuicided { require(hasRequestedForMigration, "please make a migration request"); require(requestedForMigrationAt + 604800 < now, "migration is timelocked for 7 days"); require(gasCostInGwei > 0, "gas cost must be more than 0"); require(gasCostInGwei < 20, "gas cost can't be more than 20"); // Figure out how much ether to send uint gasLimit = 21000; uint gasPrice = gasCostInGwei * 1000000000; uint gasCost = gasLimit * gasPrice; uint etherToSend = address(this).balance - gasCost; require(etherToSend > 0, "not enough balance in smart contract"); // Send the funds to the new smart contract emit MigrateFundsApproved(msg.sender, etherToSend); migrationDestination.transfer(etherToSend); // suicide the contract so that no more funds/actions can take place suicideContract(); } // events event MigrateFundsCancelled(address indexed by); event MigrateFundsRequested(address indexed by, address indexed newSmartContract); event MigrateFundsApproved(address indexed by, uint amount); } /** * @title Bitwords * * @dev The Bitwords smart contract that allows advertisers and publishers to * safetly deposit/receive ether and interact with the Bitwords platform. * * TODO: * - timelock all chargeAdvertiser requests * - if suicide is called, then all timelocked requests need to be stopped and then later reversed */ contract Bitwords is Migratable { mapping(address => uint) public advertiserBalances; // This mapping overrides the default bitwords cut for a specific publisher. mapping(address => uint) public bitwordsCutOverride; // The bitwords address, where all the 30% cut is received ETH address public bitwordsWithdrawlAddress; // How much cut out of 100 Bitwords takes. By default 10% uint public bitwordsCutOutof100 = 10; // To store the advertiserChargeRequests // TODO: this needs to be used for the timelock struct advertiserChargeRequest { address advertiser; address publisher; uint amount; uint requestedAt; uint processAfter; } // How much days should each refund request be timelocked for uint public refundRequestTimelock = 7 days; // To store refund request struct refundRequest { address advertiser; uint amount; uint requestedAt; uint processAfter; } // An array of all the refund requests submitted by advertisers. refundRequest[] public refundQueue; // variables that help track where in the refund loop we are in. mapping(address => uint) private advertiserRefundRequestsIndex; uint private lastProccessedIndex = 0; /** * @dev The Bitwords constructor sets the address where all the withdrawals will * happen. */ constructor () public { bitwordsWithdrawlAddress = msg.sender; } /** * Anybody who deposits ether to the smart contract will be considered as an * advertiser and will get that much ether debitted into his account. */ function() public payable { advertiserBalances[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value, advertiserBalances[msg.sender]); } /** * Used by the owner to set the withdrawal address for Bitwords. This address * is where Bitwords will receive all the cut from the advertisements. * * @param newAddress the new withdrawal address */ function setBitwordsWithdrawlAddress (address newAddress) hasNotSuicided onlyOwner public { bitwordsWithdrawlAddress = newAddress; emit BitwordsWithdrawlAddressChanged(msg.sender, newAddress); } /** * Change the cut that Bitwords takes. * * @param cut the amount of cut that Bitwords takes. */ function setBitwordsCut (uint cut) hasNotSuicided onlyOwner public { require(cut <= 30, "cut cannot be more than 30%"); require(cut >= 0, "cut should be greater than 0%"); bitwordsCutOutof100 = cut; emit BitwordsCutChanged(msg.sender, cut); } /** * Set the new timelock for refund reuqests * * @param newTimelock the new timelock */ function setRefundTimelock (uint newTimelock) hasNotSuicided onlyOwner public { require(newTimelock >= 0, "timelock has to be greater than 0"); refundRequestTimelock = newTimelock; emit TimelockChanged(msg.sender, newTimelock); } /** * Process all the refund requests in the queue. This is called by the Bitwords * server ideally right after chargeAdvertisers has been called. * * This function will only process refunds that have passed it's timelock and * it will only refund maximum to how much the advertiser currently has in * his balance. */ bool private inProcessRefunds = false; function processRefunds () onlyAnyOwners public { // prevent reentry bug require(!inProcessRefunds, "prevent reentry bug"); inProcessRefunds = true; for (uint j = lastProccessedIndex; j < refundQueue.length; j++) { // If we haven't passed the timelock for this refund request, then // we stop the loop. Reaching here means that all the requests // in next iterations have also not reached their timelocks. if (refundQueue[j].processAfter > now) break; // Find the minimum that needs to be withdrawn. This is important // because since every call to chargeAdvertisers might update the // advertiser's balance, it is possible that the amount that the // advertiser requests for is small. uint cappedAmount = refundQueue[j].amount; if (advertiserBalances[refundQueue[j].advertiser] < cappedAmount) cappedAmount = advertiserBalances[refundQueue[j].advertiser]; // This refund is now invalid, skip it if (cappedAmount <= 0) { lastProccessedIndex++; continue; } // deduct advertiser's balance and send the ether advertiserBalances[refundQueue[j].advertiser] -= cappedAmount; refundQueue[j].advertiser.transfer(cappedAmount); refundQueue[j].amount = 0; // Emit events emit RefundAdvertiserProcessed(refundQueue[j].advertiser, cappedAmount, advertiserBalances[refundQueue[j].advertiser]); // Increment the last proccessed index, effectively marking this // refund request as completed. lastProccessedIndex++; } inProcessRefunds = false; } /** * Anybody can credit ether on behalf of an advertiser * * @param advertiser The advertiser to credit ether to */ function creditAdvertiser (address advertiser) hasNotSuicided public payable { advertiserBalances[advertiser] += msg.value; emit Deposit(advertiser, msg.value, advertiserBalances[msg.sender]); } /** * Anybody can credit ether on behalf of an advertiser * * @param publisher The address of the publisher * @param cut How much cut should be taken from this publisher */ function setPublisherCut (address publisher, uint cut) hasNotSuicided onlyOwner public { require(cut <= 30, "cut cannot be more than 30%"); require(cut >= 0, "cut should be greater than 0%"); bitwordsCutOverride[publisher] = cut; emit SetPublisherCut(publisher, cut); } /** * Charge the advertiser with whatever clicks have been served by the ad engine. * * @param advertisers Array of address of the advertiser from whom we should debit ether * @param costs Array of the cost to be paid to publisher by advertisers * @param publishers Array of address of the publisher from whom we should credit ether * @param publishersToCredit Array of indices of publishers that need to be credited than debited. */ bool private inChargeAdvertisers = false; function chargeAdvertisers (address[] advertisers, uint[] costs, address[] publishers, uint[] publishersToCredit) hasNotSuicided onlyOwner public { // Prevent re-entry bug require(!inChargeAdvertisers, "avoid rentry bug"); inChargeAdvertisers = true; uint creditArrayIndex = 0; for (uint i = 0; i < advertisers.length; i++) { uint toWithdraw = costs[i]; // First check if all advertisers have enough balance and cap it if needed if (advertiserBalances[advertisers[i]] <= 0) { emit InsufficientBalance(advertisers[i], advertiserBalances[advertisers[i]], costs[i]); continue; } if (advertiserBalances[advertisers[i]] < toWithdraw) toWithdraw = advertiserBalances[advertisers[i]]; // Update the advertiser's balance advertiserBalances[advertisers[i]] -= toWithdraw; emit DeductFromAdvertiser(advertisers[i], toWithdraw, advertiserBalances[advertisers[i]]); // Calculate how much cut Bitwords should take uint bitwordsCut = bitwordsCutOutof100; if (bitwordsCutOverride[publishers[i]] > 0 && bitwordsCutOverride[publishers[i]] <= 30) { bitwordsCut = bitwordsCutOverride[publishers[i]]; } // Figure out how much should go to Bitwords and to the publishers. uint publisherNetCut = toWithdraw * (100 - bitwordsCut) / 100; uint bitwordsNetCut = toWithdraw - publisherNetCut; // Send the ether to the publisher and to Bitwords // Either decide to credit the ether as an advertiser if (publishersToCredit.length > creditArrayIndex && publishersToCredit[creditArrayIndex] == i) { creditArrayIndex++; advertiserBalances[publishers[i]] += publisherNetCut; emit CreditPublisher(publishers[i], publisherNetCut, advertisers[i], advertiserBalances[publishers[i]]); } else { // or send it to the publisher. publishers[i].transfer(publisherNetCut); emit PayoutToPublisher(publishers[i], publisherNetCut, advertisers[i]); } // send bitwords it's cut bitwordsWithdrawlAddress.transfer(bitwordsNetCut); emit PayoutToBitwords(bitwordsWithdrawlAddress, bitwordsNetCut, advertisers[i]); } inChargeAdvertisers = false; } /** * Called by Bitwords to manually refund an advertiser. * * @param advertiser The advertiser address to be refunded * @param amount The amount the advertiser would like to withdraw */ bool private inRefundAdvertiser = false; function refundAdvertiser (address advertiser, uint amount) onlyAnyOwners public { // Ensure that the advertiser has enough balance to refund the smart // contract require(amount > 0, "Amount should be greater than 0"); require(advertiserBalances[advertiser] > 0, "Advertiser has no balance"); require(advertiserBalances[advertiser] >= amount, "Insufficient balance to refund"); // Prevent re-entry bug require(!inRefundAdvertiser, "avoid rentry bug"); inRefundAdvertiser = true; // deduct balance and send the ether advertiserBalances[advertiser] -= amount; advertiser.transfer(amount); // Emit events emit RefundAdvertiserProcessed(advertiser, amount, advertiserBalances[advertiser]); inRefundAdvertiser = false; } /** * Called by Bitwords to invalidate a refund sent by an advertiser. */ function invalidateAdvertiserRefund (uint refundIndex) hasNotSuicided onlyOwner public { require(refundIndex >= 0, "index should be greater than 0"); require(refundQueue.length >= refundIndex, "index is out of bounds"); refundQueue[refundIndex].amount = 0; emit RefundAdvertiserCancelled(refundQueue[refundIndex].advertiser); } /** * Called by an advertiser when he/she would like to make a refund request. * * @param amount The amount the advertiser would like to withdraw */ function requestForRefund (uint amount) public { // Make sure that advertisers are requesting a refund for how much ever // ether they have. require(amount > 0, "Amount should be greater than 0"); require(advertiserBalances[msg.sender] > 0, "You have no balance"); require(advertiserBalances[msg.sender] >= amount, "Insufficient balance to refund"); // push the refund request in a refundQueue so that it can be processed // later. refundQueue.push(refundRequest(msg.sender, amount, now, now + refundRequestTimelock)); // Add the index into a hashmap for later use advertiserRefundRequestsIndex[msg.sender] = refundQueue.length - 1; // Emit events emit RefundAdvertiserRequested(msg.sender, amount, refundQueue.length - 1); } /** * Called by an advertiser when he/she wants to manually process a refund * that he/she has requested for earlier. * * This function will first find a refund request, check if it's valid (as * in, has it passed it's timelock?, is there enough balance? etc.) and * then process it, updating the advertiser's balance along the way. */ mapping(address => bool) private inProcessMyRefund; function processMyRefund () public { // Check if a refund request even exists for this advertiser? require(advertiserRefundRequestsIndex[msg.sender] >= 0, "no refund request found"); // Get the refund request details uint refundRequestIndex = advertiserRefundRequestsIndex[msg.sender]; // Check if the refund has been proccessed require(refundQueue[refundRequestIndex].amount > 0, "refund already proccessed"); // Check if the advertiser has enough balance to request for this refund? require( advertiserBalances[msg.sender] >= refundQueue[refundRequestIndex].amount, "advertiser balance is low; refund amount is invalid." ); // Check the timelock require( now > refundQueue[refundRequestIndex].processAfter, "timelock for this request has not passed" ); // Prevent reentry bug require(!inProcessMyRefund[msg.sender], "prevent re-entry bug"); inProcessMyRefund[msg.sender] = true; // Send the amount uint amount = refundQueue[refundRequestIndex].amount; msg.sender.transfer(amount); // update the new balance and void this request. refundQueue[refundRequestIndex].amount = 0; advertiserBalances[msg.sender] -= amount; // reset the reentry flag inProcessMyRefund[msg.sender] = false; // Emit events emit SelfRefundAdvertiser(msg.sender, amount, advertiserBalances[msg.sender]); emit RefundAdvertiserProcessed(msg.sender, amount, advertiserBalances[msg.sender]); } /** Events */ event BitwordsCutChanged(address indexed _to, uint _value); event BitwordsWithdrawlAddressChanged(address indexed _to, address indexed _from); event CreditPublisher(address indexed _to, uint _value, address indexed _from, uint _newBalance); event DeductFromAdvertiser(address indexed _to, uint _value, uint _newBalance); event Deposit(address indexed _to, uint _value, uint _newBalance); event InsufficientBalance(address indexed _to, uint _balance, uint _valueToDeduct); event PayoutToBitwords(address indexed _to, uint _value, address indexed _from); event PayoutToPublisher(address indexed _to, uint _value, address indexed _from); event RefundAdvertiserCancelled(address indexed _to); event RefundAdvertiserProcessed(address indexed _to, uint _value, uint _newBalance); event RefundAdvertiserRequested(address indexed _to, uint _value, uint requestIndex); event SelfRefundAdvertiser(address indexed _to, uint _value, uint _newBalance); event SetPublisherCut(address indexed _to, uint _value); event TimelockChanged(address indexed _to, uint _value); }
* Anybody who deposits ether to the smart contract will be considered as an advertiser and will get that much ether debitted into his account./
function() public payable { advertiserBalances[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value, advertiserBalances[msg.sender]); }
12,832,872
[ 1, 4625, 348, 7953, 560, 30, 380, 5502, 3432, 10354, 443, 917, 1282, 225, 2437, 358, 326, 13706, 6835, 903, 506, 7399, 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, 63, 3576, 18, 15330, 65, 1011, 1234, 18, 1132, 31, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 16738, 15914, 38, 26488, 63, 3576, 18, 15330, 19226, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-31 */ // SPDX-License-Identifier: MIT pragma solidity =0.6.12; // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @dev 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); } // /** * @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"); } } } // // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context, Initializable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function init(address sender) internal virtual initializer { _owner = sender; } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // // MasterChef is the master of VEMP. He can make VEMP and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once VEMP is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChefAPE is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardAPEDebt; // Reward debt in APE. // // We do some fancy math here. Basically, any point in time, the amount of VEMPs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accVEMPPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accVEMPPerShare` (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 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. VEMPs to distribute per block. uint256 lastRewardBlock; // Last block number that VEMPs distribution occurs. uint256 accVEMPPerShare; // Accumulated VEMPs per share, times 1e12. See below. uint256 accAPEPerShare; // Accumulated APEs per share, times 1e12. See below. uint256 lastTotalAPEReward; // last total rewards uint256 lastAPERewardBalance; // last APE rewards tokens uint256 totalAPEReward; // total APE rewards tokens } // The VEMP TOKEN! IERC20 public VEMP; // admin address. address public adminaddr; // VEMP tokens created per block. uint256 public VEMPPerBlock; // Bonus muliplier for early VEMP makers. uint256 public constant BONUS_MULTIPLIER = 1; // Info of each pool. PoolInfo public poolInfo; // Info of each user that stakes LP tokens. mapping (address => UserInfo) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when VEMP mining starts. uint256 public startBlock; // total APE staked uint256 public totalAPEStaked; // total APE used for purchase land uint256 public totalAPEUsedForPurchase = 0; // withdraw status bool public withdrawStatus; // reward end status bool public rewardEndStatus; // reward end block number uint256 public rewardEndBlock; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event Set(uint256 allocPoint, bool overwrite); event RewardEndStatus(bool rewardStatus, uint256 rewardEndBlock); event RewardPerBlock(uint256 oldRewardPerBlock, uint256 newRewardPerBlock); event AccessAPEToken(address indexed user, uint256 amount, uint256 totalAPEUsedForPurchase); event AddAPETokensInPool(uint256 amount, uint256 totalAPEUsedForPurchase); constructor() public {} function initialize( IERC20 _VEMP, IERC20 _lpToken, address _adminaddr, uint256 _VEMPPerBlock, uint256 _startBlock ) public initializer { require(address(_VEMP) != address(0), "Invalid VEMP address"); require(address(_lpToken) != address(0), "Invalid lpToken address"); require(address(_adminaddr) != address(0), "Invalid admin address"); Ownable.init(_adminaddr); VEMP = _VEMP; adminaddr = _adminaddr; VEMPPerBlock = _VEMPPerBlock; startBlock = _startBlock; withdrawStatus = false; rewardEndStatus = false; rewardEndBlock = 0; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(100); poolInfo.lpToken = _lpToken; poolInfo.allocPoint = 100; poolInfo.lastRewardBlock = lastRewardBlock; poolInfo.accVEMPPerShare = 0; poolInfo.accAPEPerShare = 0; poolInfo.lastTotalAPEReward = 0; poolInfo.lastAPERewardBalance = 0; poolInfo.totalAPEReward = 0; } // Update the given pool's VEMP allocation point. Can only be called by the owner. function set( uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { updatePool(); } totalAllocPoint = totalAllocPoint.sub(poolInfo.allocPoint).add(_allocPoint); poolInfo.allocPoint = _allocPoint; emit Set(_allocPoint, _withUpdate); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { if (_to >= _from) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else { return _from.sub(_to); } } // View function to see pending VEMPs on frontend. function pendingVEMP(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accVEMPPerShare = pool.accVEMPPerShare; uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 lpSupply = totalAPEStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt); } // View function to see pending APEs on frontend. function pendingAPE(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accAPEPerShare = pool.accAPEPerShare; uint256 lpSupply = totalAPEStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = rewardBalance.sub(pool.lastAPERewardBalance); accAPEPerShare = accAPEPerShare.add(_totalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool() internal { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = pool.totalAPEReward.add(rewardBalance.sub(pool.lastAPERewardBalance)); pool.lastAPERewardBalance = rewardBalance; pool.totalAPEReward = _totalReward; uint256 lpSupply = totalAPEStaked; if (lpSupply == 0) { pool.lastRewardBlock = rewardBlockNumber; pool.accAPEPerShare = 0; pool.lastTotalAPEReward = 0; user.rewardAPEDebt = 0; pool.lastAPERewardBalance = 0; pool.totalAPEReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = rewardBlockNumber; uint256 reward = _totalReward.sub(pool.lastTotalAPEReward); pool.accAPEPerShare = pool.accAPEPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalAPEReward = _totalReward; } // Deposit LP tokens to MasterChef for VEMP allocation. function deposit(uint256 _amount) public { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); totalAPEStaked = totalAPEStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); emit Deposit(msg.sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount) public { require(withdrawStatus != true, "Withdraw not allowed"); PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); totalAPEStaked = totalAPEStaked.sub(_amount); pool.lpToken.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public { require(withdrawStatus != true, "Withdraw not allowed"); PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; pool.lpToken.safeTransfer(msg.sender, user.amount); totalAPEStaked = totalAPEStaked.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.rewardAPEDebt = 0; emit EmergencyWithdraw(msg.sender, user.amount); } // Safe VEMP transfer function, just in case if rounding error causes pool to not have enough VEMPs. function safeVEMPTransfer(address _to, uint256 _amount) internal { uint256 VEMPBal = VEMP.balanceOf(address(this)); if (_amount > VEMPBal) { VEMP.transfer(_to, VEMPBal); } else { VEMP.transfer(_to, _amount); } } // Earn APE tokens to MasterChef. function claimAPE() public { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; updatePool(); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); } // Safe APE transfer function to admin. function accessAPETokens(address _to, uint256 _amount) public { require(_to != address(0), "Invalid to address"); require(msg.sender == adminaddr, "sender must be admin address"); require(totalAPEStaked.sub(totalAPEUsedForPurchase) >= _amount, "Amount must be less than staked APE amount"); PoolInfo storage pool = poolInfo; uint256 APEBal = pool.lpToken.balanceOf(address(this)); if (_amount > APEBal) { pool.lpToken.safeTransfer(_to, APEBal); totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(APEBal); } else { pool.lpToken.safeTransfer(_to, _amount); totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(_amount); } emit AccessAPEToken(_to, _amount, totalAPEUsedForPurchase); } // Safe add APE in pool function addAPETokensInPool(uint256 _amount) public { require(_amount > 0, "APE amount must be greater than 0"); require(msg.sender == adminaddr, "sender must be admin address"); require(_amount.add(totalAPEStaked.sub(totalAPEUsedForPurchase)) <= totalAPEStaked, "Amount must be less than staked APE amount"); PoolInfo storage pool = poolInfo; totalAPEUsedForPurchase = totalAPEUsedForPurchase.sub(_amount); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); emit AddAPETokensInPool(_amount, totalAPEUsedForPurchase); } // Update Reward per block function updateRewardPerBlock(uint256 _newRewardPerBlock) public onlyOwner { updatePool(); emit RewardPerBlock(VEMPPerBlock, _newRewardPerBlock); VEMPPerBlock = _newRewardPerBlock; } // Update withdraw status function updateWithdrawStatus(bool _status) public onlyOwner { require(withdrawStatus != _status, "Already same status"); withdrawStatus = _status; } // Update reward end status function updateRewardEndStatus(bool _status, uint256 _rewardEndBlock) public onlyOwner { require(rewardEndStatus != _status, "Already same status"); rewardEndBlock = _rewardEndBlock; rewardEndStatus = _status; emit RewardEndStatus(_status, _rewardEndBlock); } // Update admin address by the previous admin. function admin(address _adminaddr) public { require(_adminaddr != address(0), "Invalid admin address"); require(msg.sender == adminaddr, "admin: wut?"); adminaddr = _adminaddr; } // Safe VEMP transfer function to admin. function emergencyWithdrawRewardTokens(address _to, uint256 _amount) public { require(_to != address(0), "Invalid to address"); require(msg.sender == adminaddr, "sender must be admin address"); safeVEMPTransfer(_to, _amount); } }
MasterChef is the master of VEMP. He can make VEMP and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once VEMP is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
contract MasterChefAPE is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { } struct PoolInfo { } event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event Set(uint256 allocPoint, bool overwrite); event RewardEndStatus(bool rewardStatus, uint256 rewardEndBlock); event RewardPerBlock(uint256 oldRewardPerBlock, uint256 newRewardPerBlock); event AccessAPEToken(address indexed user, uint256 amount, uint256 totalAPEUsedForPurchase); event AddAPETokensInPool(uint256 amount, uint256 totalAPEUsedForPurchase); IERC20 public VEMP; address public adminaddr; uint256 public VEMPPerBlock; uint256 public constant BONUS_MULTIPLIER = 1; PoolInfo public poolInfo; mapping (address => UserInfo) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; uint256 public totalAPEStaked; uint256 public totalAPEUsedForPurchase = 0; bool public withdrawStatus; bool public rewardEndStatus; uint256 public rewardEndBlock; constructor() public {} function initialize( IERC20 _VEMP, IERC20 _lpToken, address _adminaddr, uint256 _VEMPPerBlock, uint256 _startBlock ) public initializer { require(address(_VEMP) != address(0), "Invalid VEMP address"); require(address(_lpToken) != address(0), "Invalid lpToken address"); require(address(_adminaddr) != address(0), "Invalid admin address"); Ownable.init(_adminaddr); VEMP = _VEMP; adminaddr = _adminaddr; VEMPPerBlock = _VEMPPerBlock; startBlock = _startBlock; withdrawStatus = false; rewardEndStatus = false; rewardEndBlock = 0; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(100); poolInfo.lpToken = _lpToken; poolInfo.allocPoint = 100; poolInfo.lastRewardBlock = lastRewardBlock; poolInfo.accVEMPPerShare = 0; poolInfo.accAPEPerShare = 0; poolInfo.lastTotalAPEReward = 0; poolInfo.lastAPERewardBalance = 0; poolInfo.totalAPEReward = 0; } function set( uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { updatePool(); } totalAllocPoint = totalAllocPoint.sub(poolInfo.allocPoint).add(_allocPoint); poolInfo.allocPoint = _allocPoint; emit Set(_allocPoint, _withUpdate); } function set( uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { updatePool(); } totalAllocPoint = totalAllocPoint.sub(poolInfo.allocPoint).add(_allocPoint); poolInfo.allocPoint = _allocPoint; emit Set(_allocPoint, _withUpdate); } function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { if (_to >= _from) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _from.sub(_to); } } function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { if (_to >= _from) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _from.sub(_to); } } } else { function pendingVEMP(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accVEMPPerShare = pool.accVEMPPerShare; uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 lpSupply = totalAPEStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt); } function pendingVEMP(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accVEMPPerShare = pool.accVEMPPerShare; uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 lpSupply = totalAPEStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt); } function pendingVEMP(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accVEMPPerShare = pool.accVEMPPerShare; uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 lpSupply = totalAPEStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt); } function pendingAPE(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accAPEPerShare = pool.accAPEPerShare; uint256 lpSupply = totalAPEStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = rewardBalance.sub(pool.lastAPERewardBalance); accAPEPerShare = accAPEPerShare.add(_totalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); } function pendingAPE(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accAPEPerShare = pool.accAPEPerShare; uint256 lpSupply = totalAPEStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = rewardBalance.sub(pool.lastAPERewardBalance); accAPEPerShare = accAPEPerShare.add(_totalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); } function updatePool() internal { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = pool.totalAPEReward.add(rewardBalance.sub(pool.lastAPERewardBalance)); pool.lastAPERewardBalance = rewardBalance; pool.totalAPEReward = _totalReward; uint256 lpSupply = totalAPEStaked; if (lpSupply == 0) { pool.lastRewardBlock = rewardBlockNumber; pool.accAPEPerShare = 0; pool.lastTotalAPEReward = 0; user.rewardAPEDebt = 0; pool.lastAPERewardBalance = 0; pool.totalAPEReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = rewardBlockNumber; uint256 reward = _totalReward.sub(pool.lastTotalAPEReward); pool.accAPEPerShare = pool.accAPEPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalAPEReward = _totalReward; } function updatePool() internal { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = pool.totalAPEReward.add(rewardBalance.sub(pool.lastAPERewardBalance)); pool.lastAPERewardBalance = rewardBalance; pool.totalAPEReward = _totalReward; uint256 lpSupply = totalAPEStaked; if (lpSupply == 0) { pool.lastRewardBlock = rewardBlockNumber; pool.accAPEPerShare = 0; pool.lastTotalAPEReward = 0; user.rewardAPEDebt = 0; pool.lastAPERewardBalance = 0; pool.totalAPEReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = rewardBlockNumber; uint256 reward = _totalReward.sub(pool.lastTotalAPEReward); pool.accAPEPerShare = pool.accAPEPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalAPEReward = _totalReward; } function updatePool() internal { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = pool.totalAPEReward.add(rewardBalance.sub(pool.lastAPERewardBalance)); pool.lastAPERewardBalance = rewardBalance; pool.totalAPEReward = _totalReward; uint256 lpSupply = totalAPEStaked; if (lpSupply == 0) { pool.lastRewardBlock = rewardBlockNumber; pool.accAPEPerShare = 0; pool.lastTotalAPEReward = 0; user.rewardAPEDebt = 0; pool.lastAPERewardBalance = 0; pool.totalAPEReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = rewardBlockNumber; uint256 reward = _totalReward.sub(pool.lastTotalAPEReward); pool.accAPEPerShare = pool.accAPEPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalAPEReward = _totalReward; } function updatePool() internal { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBlockNumber = block.number; if(rewardEndStatus != false) { rewardBlockNumber = rewardEndBlock; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); uint256 _totalReward = pool.totalAPEReward.add(rewardBalance.sub(pool.lastAPERewardBalance)); pool.lastAPERewardBalance = rewardBalance; pool.totalAPEReward = _totalReward; uint256 lpSupply = totalAPEStaked; if (lpSupply == 0) { pool.lastRewardBlock = rewardBlockNumber; pool.accAPEPerShare = 0; pool.lastTotalAPEReward = 0; user.rewardAPEDebt = 0; pool.lastAPERewardBalance = 0; pool.totalAPEReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = rewardBlockNumber; uint256 reward = _totalReward.sub(pool.lastTotalAPEReward); pool.accAPEPerShare = pool.accAPEPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalAPEReward = _totalReward; } function deposit(uint256 _amount) public { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); totalAPEStaked = totalAPEStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); emit Deposit(msg.sender, _amount); } function deposit(uint256 _amount) public { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); totalAPEStaked = totalAPEStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); emit Deposit(msg.sender, _amount); } function withdraw(uint256 _amount) public { require(withdrawStatus != true, "Withdraw not allowed"); PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); totalAPEStaked = totalAPEStaked.sub(_amount); pool.lpToken.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function withdraw(uint256 _amount) public { require(withdrawStatus != true, "Withdraw not allowed"); PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); totalAPEStaked = totalAPEStaked.sub(_amount); pool.lpToken.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function emergencyWithdraw() public { require(withdrawStatus != true, "Withdraw not allowed"); PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; pool.lpToken.safeTransfer(msg.sender, user.amount); totalAPEStaked = totalAPEStaked.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.rewardAPEDebt = 0; emit EmergencyWithdraw(msg.sender, user.amount); } function safeVEMPTransfer(address _to, uint256 _amount) internal { uint256 VEMPBal = VEMP.balanceOf(address(this)); if (_amount > VEMPBal) { VEMP.transfer(_to, VEMPBal); VEMP.transfer(_to, _amount); } } function safeVEMPTransfer(address _to, uint256 _amount) internal { uint256 VEMPBal = VEMP.balanceOf(address(this)); if (_amount > VEMPBal) { VEMP.transfer(_to, VEMPBal); VEMP.transfer(_to, _amount); } } } else { function claimAPE() public { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; updatePool(); uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt); pool.lpToken.safeTransfer(msg.sender, APEReward); pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase)); user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12); } function accessAPETokens(address _to, uint256 _amount) public { require(_to != address(0), "Invalid to address"); require(msg.sender == adminaddr, "sender must be admin address"); require(totalAPEStaked.sub(totalAPEUsedForPurchase) >= _amount, "Amount must be less than staked APE amount"); PoolInfo storage pool = poolInfo; uint256 APEBal = pool.lpToken.balanceOf(address(this)); if (_amount > APEBal) { pool.lpToken.safeTransfer(_to, APEBal); totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(APEBal); pool.lpToken.safeTransfer(_to, _amount); totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(_amount); } emit AccessAPEToken(_to, _amount, totalAPEUsedForPurchase); } function accessAPETokens(address _to, uint256 _amount) public { require(_to != address(0), "Invalid to address"); require(msg.sender == adminaddr, "sender must be admin address"); require(totalAPEStaked.sub(totalAPEUsedForPurchase) >= _amount, "Amount must be less than staked APE amount"); PoolInfo storage pool = poolInfo; uint256 APEBal = pool.lpToken.balanceOf(address(this)); if (_amount > APEBal) { pool.lpToken.safeTransfer(_to, APEBal); totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(APEBal); pool.lpToken.safeTransfer(_to, _amount); totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(_amount); } emit AccessAPEToken(_to, _amount, totalAPEUsedForPurchase); } } else { function addAPETokensInPool(uint256 _amount) public { require(_amount > 0, "APE amount must be greater than 0"); require(msg.sender == adminaddr, "sender must be admin address"); require(_amount.add(totalAPEStaked.sub(totalAPEUsedForPurchase)) <= totalAPEStaked, "Amount must be less than staked APE amount"); PoolInfo storage pool = poolInfo; totalAPEUsedForPurchase = totalAPEUsedForPurchase.sub(_amount); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); emit AddAPETokensInPool(_amount, totalAPEUsedForPurchase); } function updateRewardPerBlock(uint256 _newRewardPerBlock) public onlyOwner { updatePool(); emit RewardPerBlock(VEMPPerBlock, _newRewardPerBlock); VEMPPerBlock = _newRewardPerBlock; } function updateWithdrawStatus(bool _status) public onlyOwner { require(withdrawStatus != _status, "Already same status"); withdrawStatus = _status; } function updateRewardEndStatus(bool _status, uint256 _rewardEndBlock) public onlyOwner { require(rewardEndStatus != _status, "Already same status"); rewardEndBlock = _rewardEndBlock; rewardEndStatus = _status; emit RewardEndStatus(_status, _rewardEndBlock); } function admin(address _adminaddr) public { require(_adminaddr != address(0), "Invalid admin address"); require(msg.sender == adminaddr, "admin: wut?"); adminaddr = _adminaddr; } function emergencyWithdrawRewardTokens(address _to, uint256 _amount) public { require(_to != address(0), "Invalid to address"); require(msg.sender == adminaddr, "sender must be admin address"); safeVEMPTransfer(_to, _amount); } }
2,416,948
[ 1, 4625, 348, 7953, 560, 30, 225, 13453, 39, 580, 74, 353, 326, 4171, 434, 776, 3375, 52, 18, 8264, 848, 1221, 776, 3375, 52, 471, 3904, 353, 279, 284, 1826, 3058, 93, 18, 3609, 716, 518, 1807, 4953, 429, 471, 326, 3410, 341, 491, 87, 268, 2764, 409, 1481, 7212, 18, 1021, 23178, 903, 506, 906, 4193, 358, 279, 314, 1643, 82, 1359, 13706, 6835, 3647, 776, 3375, 52, 353, 18662, 715, 16859, 471, 326, 19833, 848, 2405, 358, 314, 1643, 82, 6174, 18, 21940, 9831, 6453, 518, 18, 670, 1306, 4095, 518, 1807, 7934, 17, 9156, 18, 611, 369, 324, 2656, 18, 3807, 434, 1517, 729, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13453, 39, 580, 29534, 1423, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 1000, 12, 11890, 5034, 4767, 2148, 16, 1426, 6156, 1769, 203, 565, 871, 534, 359, 1060, 1638, 1482, 12, 6430, 19890, 1482, 16, 2254, 5034, 19890, 1638, 1768, 1769, 203, 565, 871, 534, 359, 1060, 2173, 1768, 12, 11890, 5034, 1592, 17631, 1060, 2173, 1768, 16, 2254, 5034, 394, 17631, 1060, 2173, 1768, 1769, 203, 565, 871, 5016, 37, 1423, 1345, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 16, 2254, 5034, 2078, 37, 1423, 6668, 1290, 23164, 1769, 203, 565, 871, 1436, 37, 1423, 5157, 382, 2864, 12, 11890, 5034, 3844, 16, 2254, 5034, 2078, 37, 1423, 6668, 1290, 23164, 1769, 203, 203, 203, 565, 467, 654, 39, 3462, 1071, 776, 3375, 52, 31, 203, 565, 1758, 1071, 3981, 4793, 31, 203, 565, 2254, 5034, 1071, 776, 3375, 52, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 404, 31, 203, 565, 8828, 966, 1071, 2845, 966, 31, 203, 565, 2874, 261, 2867, 516, 25003, 13, 1071, 16753, 31, 203, 565, 2254, 5034, 1071, 2078, 8763, 2148, 273, 374, 31, 203, 565, 2254, 5034, 1071, 787, 1768, 31, 203, 565, 2254, 5034, 1071, 2078, 37, 1423, 510, 9477, 31, 203, 565, 2254, 5034, 1071, 2078, 37, 1423, 6668, 1290, 23164, 273, 374, 31, 203, 565, 1426, 1071, 598, 9446, 1482, 31, 203, 565, 1426, 1071, 19890, 1638, 1482, 31, 203, 565, 2254, 5034, 1071, 19890, 1638, 1768, 31, 203, 565, 3885, 1435, 1071, 2618, 203, 565, 445, 4046, 12, 203, 3639, 467, 654, 39, 3462, 389, 58, 3375, 52, 16, 203, 3639, 467, 654, 39, 3462, 389, 9953, 1345, 16, 203, 3639, 1758, 389, 3666, 4793, 16, 203, 3639, 2254, 5034, 389, 58, 3375, 52, 2173, 1768, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 203, 565, 262, 1071, 12562, 288, 203, 3639, 2583, 12, 2867, 24899, 58, 3375, 52, 13, 480, 1758, 12, 20, 3631, 315, 1941, 776, 3375, 52, 1758, 8863, 203, 3639, 2583, 12, 2867, 24899, 9953, 1345, 13, 480, 1758, 12, 20, 3631, 315, 1941, 12423, 1345, 1758, 8863, 203, 3639, 2583, 12, 2867, 24899, 3666, 4793, 13, 480, 1758, 12, 20, 3631, 315, 1941, 3981, 1758, 8863, 203, 3639, 14223, 6914, 18, 2738, 24899, 3666, 4793, 1769, 203, 3639, 776, 3375, 52, 273, 389, 58, 3375, 52, 31, 203, 3639, 3981, 4793, 273, 389, 3666, 4793, 31, 203, 3639, 776, 3375, 52, 2173, 1768, 273, 389, 58, 3375, 52, 2173, 1768, 31, 203, 3639, 787, 1768, 273, 389, 1937, 1768, 31, 203, 3639, 598, 9446, 1482, 273, 629, 31, 203, 3639, 19890, 1638, 1482, 273, 629, 31, 203, 3639, 19890, 1638, 1768, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 12, 6625, 1769, 203, 3639, 2845, 966, 18, 9953, 1345, 273, 389, 9953, 1345, 31, 203, 3639, 2845, 966, 18, 9853, 2148, 273, 2130, 31, 203, 3639, 2845, 966, 18, 2722, 17631, 1060, 1768, 273, 1142, 17631, 1060, 1768, 31, 203, 3639, 2845, 966, 18, 8981, 58, 3375, 52, 2173, 9535, 273, 374, 31, 203, 3639, 2845, 966, 18, 8981, 37, 1423, 2173, 9535, 273, 374, 31, 203, 3639, 2845, 966, 18, 2722, 5269, 2203, 654, 359, 1060, 273, 374, 31, 203, 3639, 2845, 966, 18, 2722, 2203, 654, 359, 1060, 13937, 273, 374, 31, 203, 3639, 2845, 966, 18, 4963, 2203, 654, 359, 1060, 273, 374, 31, 203, 565, 289, 203, 203, 565, 445, 444, 12, 2254, 5034, 389, 9853, 2148, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 1089, 2864, 5621, 203, 3639, 289, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1717, 12, 6011, 966, 18, 9853, 2148, 2934, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 9853, 2148, 273, 389, 9853, 2148, 31, 203, 3639, 3626, 1000, 24899, 9853, 2148, 16, 389, 1918, 1891, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 444, 12, 2254, 5034, 389, 9853, 2148, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 1089, 2864, 5621, 203, 3639, 289, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1717, 12, 6011, 966, 18, 9853, 2148, 2934, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 9853, 2148, 273, 389, 9853, 2148, 31, 203, 3639, 3626, 1000, 24899, 9853, 2148, 16, 389, 1918, 1891, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 31863, 5742, 12, 11890, 5034, 389, 2080, 16, 2254, 5034, 389, 869, 13, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 67, 869, 1545, 389, 2080, 13, 288, 203, 5411, 327, 389, 869, 18, 1717, 24899, 2080, 2934, 16411, 12, 38, 673, 3378, 67, 24683, 2053, 654, 1769, 203, 5411, 327, 389, 2080, 18, 1717, 24899, 869, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 31863, 5742, 12, 11890, 5034, 389, 2080, 16, 2254, 5034, 389, 869, 13, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 67, 869, 1545, 389, 2080, 13, 288, 203, 5411, 327, 389, 869, 18, 1717, 24899, 2080, 2934, 16411, 12, 38, 673, 3378, 67, 24683, 2053, 654, 1769, 203, 5411, 327, 389, 2080, 18, 1717, 24899, 869, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 4634, 2 ]
./partial_match/8453/0x0a041C5f5f4c1fbFE521E47d4a3009f5777ebA59/sources/BaseBuyBot.sol
Anti-bot and anti-whale mappings and variables
contract BaseBuyBot is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); address public uniV2router = 0xfCD3842f85ed87ba2889b4D35893403796e67FF1; bool private swapping; address public marketingWallet; address public developmentWallet; address public liquidityWallet; address public operationsWallet; uint256 public maxTransaction; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; mapping(address => uint256) private _holderLastTransferTimestamp; bool public transferDelayEnabled = true; uint256 private launchBlock; mapping(address => bool) public blocked; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevelopmentFee; uint256 public buyOperationsFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevelopmentFee; uint256 public sellOperationsFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDevelopment; uint256 public tokensForOperations; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedmaxTransaction; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event developmentWalletUpdated( address indexed newWallet, address indexed oldWallet ); event liquidityWalletUpdated( address indexed newWallet, address indexed oldWallet ); event operationsWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("Base Buy Bot", "BBB") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniV2router); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 0; uint256 _buyDevelopmentFee = 0; uint256 _buyOperationsFee = 0; uint256 _sellMarketingFee = 19; uint256 _sellLiquidityFee = 0; uint256 _sellDevelopmentFee = 0; uint256 _sellOperationsFee = 0; uint256 totalSupply = 100_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevelopmentFee = _buyDevelopmentFee; buyOperationsFee = _buyOperationsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevelopmentFee = _sellDevelopmentFee; sellOperationsFee = _sellOperationsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee; marketingWallet = address(0xa70723b5fA17670818427C959f8b6AF9Aa42a55d); developmentWallet = address(0xa70723b5fA17670818427C959f8b6AF9Aa42a55d); liquidityWallet = address(0xa70723b5fA17670818427C959f8b6AF9Aa42a55d); operationsWallet = address(0xa70723b5fA17670818427C959f8b6AF9Aa42a55d); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { require(!tradingActive, "Token launched"); tradingActive = true; launchBlock = block.number; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTransaction(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransaction lower than 0.1%" ); maxTransaction = newNum * (10**18); } function updateMaxWallet(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedmaxTransaction[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee, uint256 _operationsFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevelopmentFee = _developmentFee; buyOperationsFee = _operationsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee; require(buyTotalFees <= 99); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee, uint256 _operationsFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevelopmentFee = _developmentFee; sellOperationsFee = _operationsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee; require(sellTotalFees <= 99); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updatemarketingWallet(address newmarketingWallet) external onlyOwner { emit marketingWalletUpdated(newmarketingWallet, marketingWallet); marketingWallet = newmarketingWallet; } function updatedevelopmentWallet(address newWallet) external onlyOwner { emit developmentWalletUpdated(newWallet, developmentWallet); developmentWallet = newWallet; } function updateoperationsWallet(address newWallet) external onlyOwner{ emit operationsWalletUpdated(newWallet, operationsWallet); operationsWallet = newWallet; } function updateliquidityWallet(address newliquidityWallet) external onlyOwner { emit liquidityWalletUpdated(newliquidityWallet, liquidityWallet); liquidityWallet = newliquidityWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedmaxTransaction[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, liquidityWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner { for(uint256 i = 0;i<blockees.length;i++){ address blockee = blockees[i]; if(blockee != address(this) && blockee != uniV2router && blockee != address(uniswapV2Pair)) blocked[blockee] = shouldBlock; } } function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner { for(uint256 i = 0;i<blockees.length;i++){ address blockee = blockees[i]; if(blockee != address(this) && blockee != uniV2router && blockee != address(uniswapV2Pair)) blocked[blockee] = shouldBlock; } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; (success, ) = address(developmentWallet).call{value: ethForDevelopment}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } (success, ) = address(operationsWallet).call{value: ethForOperations}(""); (success, ) = address(marketingWallet).call{value: address(this).balance}(""); }
16,758,040
[ 1, 4625, 348, 7953, 560, 30, 225, 18830, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3360, 38, 9835, 6522, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 565, 1758, 1071, 7738, 58, 22, 10717, 273, 374, 5841, 10160, 17295, 22, 74, 7140, 329, 11035, 12124, 22, 5482, 29, 70, 24, 40, 4763, 6675, 5026, 4630, 7235, 26, 73, 9599, 2246, 21, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 17772, 16936, 31, 203, 565, 1758, 1071, 4501, 372, 24237, 16936, 31, 203, 565, 1758, 1071, 5295, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 638, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3024, 5912, 4921, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 565, 2254, 5034, 3238, 8037, 1768, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 14547, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 26438, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 9343, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 26438, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 9343, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 2430, 1290, 3882, 21747, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 48, 18988, 24237, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 26438, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 9343, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2954, 281, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 291, 16461, 1896, 3342, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 18472, 690, 3882, 278, 12373, 10409, 31, 203, 203, 565, 871, 2315, 984, 291, 91, 438, 58, 22, 8259, 12, 203, 3639, 1758, 8808, 394, 1887, 16, 203, 3639, 1758, 8808, 1592, 1887, 203, 565, 11272, 203, 203, 565, 871, 20760, 1265, 2954, 281, 12, 2867, 8808, 2236, 16, 1426, 353, 16461, 1769, 203, 203, 565, 871, 1000, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 8808, 3082, 16, 1426, 8808, 460, 1769, 203, 203, 565, 871, 13667, 310, 16936, 7381, 12, 203, 3639, 1758, 8808, 394, 16936, 16, 203, 3639, 1758, 8808, 1592, 16936, 203, 565, 11272, 203, 203, 565, 871, 17772, 16936, 7381, 12, 203, 3639, 1758, 8808, 394, 16936, 16, 203, 3639, 1758, 8808, 1592, 16936, 203, 565, 11272, 203, 203, 565, 871, 4501, 372, 24237, 16936, 7381, 12, 203, 3639, 1758, 8808, 394, 16936, 16, 203, 3639, 1758, 8808, 1592, 16936, 203, 565, 11272, 203, 203, 565, 871, 5295, 16936, 7381, 12, 203, 3639, 1758, 8808, 394, 16936, 16, 203, 3639, 1758, 8808, 1592, 16936, 203, 565, 11272, 203, 203, 565, 871, 12738, 1876, 48, 18988, 1164, 12, 203, 3639, 2254, 5034, 2430, 12521, 1845, 16, 203, 3639, 2254, 5034, 13750, 8872, 16, 203, 3639, 2254, 5034, 2430, 5952, 48, 18988, 24237, 203, 565, 11272, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 2171, 605, 9835, 15039, 3113, 315, 9676, 38, 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, 318, 77, 58, 22, 10717, 1769, 7010, 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, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 890, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 26438, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 9343, 14667, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 389, 87, 1165, 3882, 21747, 14667, 273, 5342, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 26438, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 9343, 14667, 273, 374, 31, 203, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 2130, 67, 3784, 67, 3784, 380, 404, 73, 2643, 31, 203, 203, 203, 3639, 30143, 3882, 21747, 14667, 273, 389, 70, 9835, 3882, 21747, 14667, 31, 203, 3639, 30143, 48, 18988, 24237, 14667, 273, 389, 70, 9835, 48, 18988, 24237, 14667, 31, 203, 3639, 30143, 26438, 14667, 273, 389, 70, 9835, 26438, 14667, 31, 203, 3639, 30143, 9343, 14667, 273, 389, 70, 9835, 9343, 14667, 31, 203, 3639, 30143, 5269, 2954, 281, 273, 30143, 3882, 2 ]
pragma solidity ^0.5.6; import "./ownership/Ownable.sol"; import "./math/SafeMath.sol"; import "./Guseul.sol"; contract Game is Ownable { using SafeMath for uint256; Guseul public gsl; uint256 public round = 1; mapping(uint256 => mapping(address => uint256)) private _betGsl; mapping(uint256 => mapping(address => bool)) private _betBool; mapping(uint256 => mapping(address => uint256)) private _lastGet; mapping(uint256 => address[]) private _betListOdd; mapping(uint256 => address[]) private _betListEven; constructor(Guseul _gsl) public { gsl = _gsl; } // 이번 라운드 벳 했는지 안했는지 호출 function betOrNot(address adr) public returns (bool) { bool didbet = _betBool[round][adr]; return didbet; } // 이번 라운드 벳 액수 function betHowMuch(address adr) public returns (uint256) { uint256 howmuch = _betGsl[round][adr]; return howmuch; } // 저번 라운드 벳 액수 function earnHowMuchLast(address adr) public returns (uint256) { uint256 earnhowmuch = _lastGet[round.sub(1)][adr]; return earnhowmuch; } // 홀수 벳 function betOdd(uint256 amount) external payable { require(_betBool[round][msg.sender] != true); gsl.transferFrom(msg.sender, address(this), amount); _betGsl[round][msg.sender] = amount; _betBool[round][msg.sender] = true; _betListOdd[round].push(msg.sender); } //짝수 벳 function betEven(uint256 amount) external payable { require(_betBool[round][msg.sender] != true); gsl.transferFrom(msg.sender, address(this), amount); _betGsl[round][msg.sender] = amount; _betBool[round][msg.sender] = true; _betListEven[round].push(msg.sender); } function raffle(uint256 oddeven) external onlyOwner { //1이 홀수, 2가 짝수 uint256 _round = round; if (oddeven == 1) { uint256 len = _betListOdd[round].length; for (uint256 i = 0; i < len; i = i.add(1)) { gsl.transfer( _betListOdd[round][i], _betGsl[round][_betListOdd[round][i]].mul(2) ); _lastGet[round][_betListOdd[round][i]] = _betGsl[round][ _betListOdd[round][i] ].mul(2); } } else { uint256 len = _betListEven[round].length; for (uint256 i = 0; i < len; i = i.add(1)) { gsl.transfer( _betListEven[round][i], _betGsl[round][_betListEven[round][i]].mul(2) ); _lastGet[round][_betListEven[round][i]] = _betGsl[round][ _betListEven[round][i] ].mul(2); } } round = _round.add(1); } }
이번 라운드 벳 했는지 안했는지 호출
function betOrNot(address adr) public returns (bool) { bool didbet = _betBool[round][adr]; return didbet; }
955,632
[ 1, 4625, 348, 7953, 560, 30, 225, 225, 173, 256, 117, 172, 115, 235, 225, 172, 256, 125, 173, 253, 117, 172, 246, 255, 225, 172, 115, 116, 225, 174, 249, 235, 172, 237, 247, 173, 105, 227, 225, 173, 248, 235, 174, 249, 235, 172, 237, 247, 173, 105, 227, 225, 174, 251, 121, 173, 119, 255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2701, 1162, 1248, 12, 2867, 1261, 86, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 1426, 5061, 70, 278, 273, 389, 70, 278, 7464, 63, 2260, 6362, 361, 86, 15533, 203, 3639, 327, 5061, 70, 278, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; contract Keccak { uint8[24] rho = [ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44 ]; uint8[24] pi = [ 10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1 ]; // Dave: Replaced with x86_64 values //uint64[24] RC = [ // 0x1, 0x8082, 0x800000000000808a, 0x8000000080008000, // 0x808b, 0x80000001, 0x8000000080008081, 0x8000000000008009, // 0x8a, 0x88, 0x80008009, 0x8000000a, // 0x8000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, // 0x8000000000008002, 0x8000000000000080, 0x800a, 0x800000008000000a, // 0x8000000080008081, 0x8000000000008080, 0x80000001, 0x8000000080008008 //]; // Dave: Optimised for x86_64 uint64[48] RC = [ 0x00000001, 0x00000000, 0x00008082, 0x00000000, 0x0000808A, 0x80000000, 0x80008000, 0x80000000, 0x0000808B, 0x00000000, 0x80000001, 0x00000000, 0x80008081, 0x80000000, 0x00008009, 0x80000000, 0x0000008A, 0x00000000, 0x00000088, 0x00000000, 0x80008009, 0x00000000, 0x8000000A, 0x00000000, 0x8000808B, 0x00000000, 0x0000008B, 0x80000000, 0x00008089, 0x80000000, 0x00008003, 0x80000000, 0x00008002, 0x80000000, 0x00000080, 0x80000000, 0x0000800A, 0x00000000, 0x8000000A, 0x80000000, 0x80008081, 0x80000000, 0x00008080, 0x80000000, 0x80000001, 0x00000000, 0x80008008, 0x80000000 ]; // Dave: Changed from public to external function keccakf(bytes memory a) public view returns (bytes memory) //function keccakf(bytes memory a) external view returns (bytes memory) { // This is the memory location where the input data resides. // first byte is for the size of the array // https://docs.soliditylang.org/en/v0.7.4/internals/layout_in_storage.html#bytes-and-string uint aPtr; assembly { aPtr := add(a, 32) } uint64[5] memory b; uint bPtr; assembly { bPtr := add(b, 32) } uint8 rounds = 24; // 24 for (uint8 i = 0; i < rounds; i++) { // Theta for(uint8 x = 0; x < 5; x++) { for(uint8 y = 0; y < 25; y += 5) { uint64 packedState; assembly { packedState := mload(add(aPtr, add(x, y))) } b[x] ^= packedState; } } for(uint8 x = 0; x < 5; x++) { for(uint8 y = 0; y < 25; y += 5) { //uint64 temp = b[0]; uint64 temp = b[(x + 4) % 5] ^ (((b[(x + 1) % 5]) << 1) | ((b[(x + 1) % 5]) >> (64 - 1))); assembly { //a[x + y] ^= temp; mstore(add(aPtr, add(x, y)), xor(mload(add(aPtr, add(x, y))), temp)) } } } // Rho and Pi uint64 t; assembly { //t = a[1] t := mload(add(aPtr, 8)) } for(uint8 x = 0; x < 24; x++) { uint8 piIndex = pi[x]; uint64 temp = (((t) << rho[x]) | ((t) >> (64 - rho[x]))); assembly { //b[0] = a[piIndex]; mstore(bPtr, mload(add(aPtr, piIndex))) //a[piIndex] = temp; mstore(add(aPtr, piIndex), temp) } t = b[0]; } // Chi for(uint8 y = 0; y < 25; y += 5) { for(uint8 x = 0; x < 5; x++) { //b[x] = a[y + x]; assembly { mstore(add(bPtr, x), mload(add(aPtr, add(y, x)))) } } for(uint8 x = 0; x < 5; x++) { uint64 temp = b[x] ^ ((~b[(x + 1) % 5]) & b[(x + 2) % 5]); assembly { //a[y + x] = temp; mstore(add(aPtr, add(y, x)), temp) } } } // Iota uint64 rcValue = RC[i]; assembly { //a[0] ^= rcValue; mstore(aPtr, xor(mload(aPtr), rcValue)) } } return a; } }
This is the memory location where the input data resides. first byte is for the size of the array https:docs.soliditylang.org/en/v0.7.4/internals/layout_in_storage.html#bytes-and-string Thetauint64 temp = b[0];a[x + y] ^= temp;t = a[1]b[0] = a[piIndex];a[piIndex] = temp;b[x] = a[y + x];a[y + x] = temp;a[0] ^= rcValue;
{ uint aPtr; assembly { aPtr := add(a, 32) } uint64[5] memory b; uint bPtr; assembly { bPtr := add(b, 32) } for (uint8 i = 0; i < rounds; i++) { for(uint8 x = 0; x < 5; x++) { for(uint8 y = 0; y < 25; y += 5) { uint64 packedState; assembly { packedState := mload(add(aPtr, add(x, y))) } b[x] ^= packedState; } } for(uint8 x = 0; x < 5; x++) { for(uint8 y = 0; y < 25; y += 5) { uint64 temp = b[(x + 4) % 5] ^ (((b[(x + 1) % 5]) << 1) | ((b[(x + 1) % 5]) >> (64 - 1))); assembly { mstore(add(aPtr, add(x, y)), xor(mload(add(aPtr, add(x, y))), temp)) } } } assembly { t := mload(add(aPtr, 8)) } for(uint8 x = 0; x < 24; x++) { uint8 piIndex = pi[x]; uint64 temp = (((t) << rho[x]) | ((t) >> (64 - rho[x]))); assembly { mstore(bPtr, mload(add(aPtr, piIndex))) mstore(add(aPtr, piIndex), temp) } t = b[0]; } { for(uint8 x = 0; x < 5; x++) { assembly { mstore(add(bPtr, x), mload(add(aPtr, add(y, x)))) } } for(uint8 x = 0; x < 5; x++) { uint64 temp = b[x] ^ ((~b[(x + 1) % 5]) & b[(x + 2) % 5]); assembly { mstore(add(aPtr, add(y, x)), temp) } } } assembly { mstore(aPtr, xor(mload(aPtr), rcValue)) } } return a; }
5,423,697
[ 1, 4625, 348, 7953, 560, 30, 225, 1220, 353, 326, 3778, 2117, 1625, 326, 810, 501, 400, 4369, 18, 1122, 1160, 353, 364, 326, 963, 434, 326, 526, 2333, 30, 8532, 18, 30205, 560, 4936, 18, 3341, 19, 275, 19, 90, 20, 18, 27, 18, 24, 19, 267, 798, 1031, 19, 6741, 67, 267, 67, 5697, 18, 2620, 7, 3890, 17, 464, 17, 1080, 935, 1066, 11890, 1105, 1906, 273, 324, 63, 20, 15533, 69, 63, 92, 397, 677, 65, 10352, 1906, 31, 88, 273, 279, 63, 21, 65, 70, 63, 20, 65, 273, 279, 63, 7259, 1016, 15533, 69, 63, 7259, 1016, 65, 273, 1906, 31, 70, 63, 92, 65, 273, 279, 63, 93, 397, 619, 15533, 69, 63, 93, 397, 619, 65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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 203, 3639, 2254, 279, 5263, 31, 203, 3639, 19931, 203, 3639, 288, 203, 5411, 279, 5263, 519, 527, 12, 69, 16, 3847, 13, 203, 3639, 289, 203, 3639, 2254, 1105, 63, 25, 65, 3778, 324, 31, 203, 3639, 2254, 324, 5263, 31, 203, 3639, 19931, 203, 3639, 288, 203, 5411, 324, 5263, 519, 527, 12, 70, 16, 3847, 13, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 21196, 31, 277, 27245, 203, 3639, 288, 203, 5411, 364, 12, 11890, 28, 619, 273, 374, 31, 619, 411, 1381, 31, 619, 27245, 203, 5411, 288, 203, 7734, 364, 12, 11890, 28, 677, 273, 374, 31, 677, 411, 6969, 31, 677, 1011, 1381, 13, 203, 7734, 288, 203, 10792, 2254, 1105, 12456, 1119, 31, 203, 10792, 19931, 203, 10792, 288, 203, 13491, 12456, 1119, 519, 312, 945, 12, 1289, 12, 69, 5263, 16, 527, 12, 92, 16, 677, 20349, 203, 10792, 289, 203, 10792, 324, 63, 92, 65, 10352, 12456, 1119, 31, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 364, 12, 11890, 28, 619, 273, 374, 31, 619, 411, 1381, 31, 619, 27245, 203, 5411, 288, 203, 7734, 364, 12, 11890, 28, 677, 273, 374, 31, 677, 411, 6969, 31, 677, 1011, 1381, 13, 203, 7734, 288, 203, 10792, 2254, 1105, 1906, 273, 324, 63, 12, 92, 397, 1059, 13, 738, 1381, 65, 3602, 261, 12443, 70, 63, 12, 92, 397, 404, 13, 738, 1381, 5717, 2296, 404, 13, 571, 14015, 70, 63, 12, 92, 397, 404, 13, 738, 1381, 5717, 1671, 261, 1105, 300, 404, 3719, 1769, 203, 10792, 19931, 203, 10792, 288, 203, 13491, 312, 2233, 12, 1289, 12, 69, 5263, 16, 527, 12, 92, 16, 677, 13, 3631, 17586, 12, 81, 945, 12, 1289, 12, 69, 5263, 16, 527, 12, 92, 16, 677, 3719, 3631, 1906, 3719, 203, 10792, 289, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 19931, 203, 5411, 288, 203, 7734, 268, 519, 312, 945, 12, 1289, 12, 69, 5263, 16, 1725, 3719, 203, 5411, 289, 203, 5411, 364, 12, 11890, 28, 619, 273, 374, 31, 619, 411, 4248, 31, 619, 27245, 203, 5411, 288, 203, 7734, 2254, 28, 4790, 1016, 273, 4790, 63, 92, 15533, 203, 7734, 2254, 1105, 1906, 273, 261, 12443, 88, 13, 2296, 10360, 63, 92, 5717, 571, 14015, 88, 13, 1671, 261, 1105, 300, 10360, 63, 92, 22643, 1769, 203, 7734, 19931, 203, 7734, 288, 203, 10792, 312, 2233, 12, 70, 5263, 16, 312, 945, 12, 1289, 12, 69, 5263, 16, 4790, 1016, 20349, 203, 10792, 312, 2233, 12, 1289, 12, 69, 5263, 16, 4790, 1016, 3631, 1906, 13, 203, 7734, 289, 203, 7734, 268, 273, 324, 63, 20, 15533, 203, 5411, 289, 203, 203, 5411, 288, 203, 7734, 364, 12, 11890, 28, 619, 273, 374, 31, 619, 411, 1381, 31, 619, 27245, 203, 7734, 288, 203, 10792, 19931, 203, 10792, 288, 203, 13491, 312, 2233, 12, 1289, 12, 70, 5263, 16, 619, 3631, 312, 945, 12, 1289, 12, 69, 5263, 16, 527, 12, 93, 16, 619, 3719, 3719, 203, 10792, 289, 203, 7734, 289, 203, 7734, 364, 12, 11890, 28, 619, 273, 374, 31, 619, 411, 1381, 31, 619, 27245, 203, 7734, 288, 203, 10792, 2254, 1105, 1906, 273, 324, 63, 92, 65, 3602, 14015, 98, 70, 63, 12, 92, 397, 404, 13, 738, 1381, 5717, 473, 324, 63, 12, 92, 397, 576, 13, 738, 1381, 19226, 203, 10792, 19931, 203, 10792, 288, 203, 13491, 312, 2233, 12, 1289, 12, 69, 5263, 16, 527, 12, 93, 16, 619, 13, 3631, 1906, 13, 203, 10792, 289, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 19931, 203, 5411, 288, 203, 7734, 312, 2233, 12, 69, 5263, 16, 17586, 12, 81, 945, 12, 69, 5263, 3631, 4519, 620, 3719, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 279, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; contract BBFarmEvents { event BallotCreatedWithID(uint ballotId); event BBFarmInit(bytes4 namespace); event Sponsorship(uint ballotId, uint value); event Vote(uint indexed ballotId, bytes32 vote, address voter, bytes extra); } library BBLib { using BytesLib for bytes; // ballot meta uint256 constant BB_VERSION = 6; /* 4 deprecated due to insecure vote by proxy 5 deprecated to - add `returns (address)` to submitProxyVote */ // voting settings uint16 constant USE_ETH = 1; // 2^0 uint16 constant USE_SIGNED = 2; // 2^1 uint16 constant USE_NO_ENC = 4; // 2^2 uint16 constant USE_ENC = 8; // 2^3 // ballot settings uint16 constant IS_BINDING = 8192; // 2^13 uint16 constant IS_OFFICIAL = 16384; // 2^14 uint16 constant USE_TESTING = 32768; // 2^15 // other consts uint32 constant MAX_UINT32 = 0xFFFFFFFF; //// ** Storage Variables // struct for ballot struct Vote { bytes32 voteData; bytes32 castTsAndSender; bytes extra; } struct Sponsor { address sender; uint amount; } //// ** Events event CreatedBallot(bytes32 _specHash, uint64 startTs, uint64 endTs, uint16 submissionBits); event SuccessfulVote(address indexed voter, uint voteId); event SeckeyRevealed(bytes32 secretKey); event TestingEnabled(); event DeprecatedContract(); // The big database struct struct DB { // Maps to store ballots, along with corresponding log of voters. // Should only be modified through internal functions mapping (uint256 => Vote) votes; uint256 nVotesCast; // we need replay protection for proxy ballots - this will let us check against a sequence number // note: votes directly from a user ALWAYS take priority b/c they do not have sequence numbers // (sequencing is done by Ethereum itself via the tx nonce). mapping (address => uint32) sequenceNumber; // NOTE - We don't actually want to include the encryption PublicKey because _it's included in the ballotSpec_. // It's better to ensure ppl actually have the ballot spec by not including it in the contract. // Plus we're already storing the hash of the ballotSpec anyway... // Private key to be set after ballot conclusion - curve25519 bytes32 ballotEncryptionSeckey; // packed contains: // 1. Timestamps for start and end of ballot (UTC) // 2. bits used to decide which options are enabled or disabled for submission of ballots uint256 packed; // specHash by which to validate the ballots integrity bytes32 specHash; // extradata if we need it - allows us to upgrade spechash format, etc bytes16 extraData; // allow tracking of sponsorship for this ballot & connection to index Sponsor[] sponsors; IxIface index; // deprecation flag - doesn't actually do anything besides signal that this contract is deprecated; bool deprecated; address ballotOwner; uint256 creationTs; } // ** Modifiers -- note, these are functions here to allow use as a lib function requireBallotClosed(DB storage db) internal view { require(now > BPackedUtils.packedToEndTime(db.packed), "!b-closed"); } function requireBallotOpen(DB storage db) internal view { uint64 _n = uint64(now); uint64 startTs; uint64 endTs; (, startTs, endTs) = BPackedUtils.unpackAll(db.packed); require(_n >= startTs && _n < endTs, "!b-open"); require(db.deprecated == false, "b-deprecated"); } function requireBallotOwner(DB storage db) internal view { require(msg.sender == db.ballotOwner, "!b-owner"); } function requireTesting(DB storage db) internal view { require(isTesting(BPackedUtils.packedToSubmissionBits(db.packed)), "!testing"); } /* Library meta */ function getVersion() external pure returns (uint) { // even though this is constant we want to make sure that it's actually // callable on Ethereum so we don't accidentally package the constant code // in with an SC using BBLib. This function _must_ be external. return BB_VERSION; } /* Functions */ // "Constructor" function - init core params on deploy // timestampts are uint64s to give us plenty of room for millennia function init(DB storage db, bytes32 _specHash, uint256 _packed, IxIface ix, address ballotOwner, bytes16 extraData) external { require(db.specHash == bytes32(0), "b-exists"); db.index = ix; db.ballotOwner = ballotOwner; uint64 startTs; uint64 endTs; uint16 sb; (sb, startTs, endTs) = BPackedUtils.unpackAll(_packed); bool _testing = isTesting(sb); if (_testing) { emit TestingEnabled(); } else { require(endTs > now, "bad-end-time"); // 0x1ff2 is 0001111111110010 in binary // by ANDing with subBits we make sure that only bits in positions 0,2,3,13,14,15 // can be used. these correspond to the option flags at the top, and ETH ballots // that are enc'd or plaintext. require(sb & 0x1ff2 == 0, "bad-sb"); // if we give bad submission bits (e.g. all 0s) then refuse to deploy ballot bool okaySubmissionBits = 1 == (isEthNoEnc(sb) ? 1 : 0) + (isEthWithEnc(sb) ? 1 : 0); require(okaySubmissionBits, "!valid-sb"); // take the max of the start time provided and the blocks timestamp to avoid a DoS against recent token holders // (which someone might be able to do if they could set the timestamp in the past) startTs = startTs > now ? startTs : uint64(now); } require(_specHash != bytes32(0), "null-specHash"); db.specHash = _specHash; db.packed = BPackedUtils.pack(sb, startTs, endTs); db.creationTs = now; if (extraData != bytes16(0)) { db.extraData = extraData; } emit CreatedBallot(db.specHash, startTs, endTs, sb); } /* sponsorship */ function logSponsorship(DB storage db, uint value) internal { db.sponsors.push(Sponsor(msg.sender, value)); } /* getters */ function getVote(DB storage db, uint id) internal view returns (bytes32 voteData, address sender, bytes extra, uint castTs) { return (db.votes[id].voteData, address(db.votes[id].castTsAndSender), db.votes[id].extra, uint(db.votes[id].castTsAndSender) >> 160); } function getSequenceNumber(DB storage db, address voter) internal view returns (uint32) { return db.sequenceNumber[voter]; } function getTotalSponsorship(DB storage db) internal view returns (uint total) { for (uint i = 0; i < db.sponsors.length; i++) { total += db.sponsors[i].amount; } } function getSponsor(DB storage db, uint i) external view returns (address sender, uint amount) { sender = db.sponsors[i].sender; amount = db.sponsors[i].amount; } /* ETH BALLOTS */ // Ballot submission // note: if USE_ENC then curve25519 keys should be generated for // each ballot (then thrown away). // the curve25519 PKs go in the extra param function submitVote(DB storage db, bytes32 voteData, bytes extra) external { _addVote(db, voteData, msg.sender, extra); // set the sequence number to max uint32 to disable proxy submitted ballots // after a voter submits a transaction personally - effectivley disables proxy // ballots. You can _always_ submit a new vote _personally_ with this scheme. if (db.sequenceNumber[msg.sender] != MAX_UINT32) { // using an IF statement here let's us save 4800 gas on repeat votes at the cost of 20k extra gas initially db.sequenceNumber[msg.sender] = MAX_UINT32; } } // Boundaries for constructing the msg we'll validate the signature of function submitProxyVote(DB storage db, bytes32[5] proxyReq, bytes extra) external returns (address voter) { // a proxy vote (where the vote is submitted (i.e. tx fee paid by someone else) // docs for datastructs: https://github.com/secure-vote/tokenvote/blob/master/Docs/DataStructs.md bytes32 r = proxyReq[0]; bytes32 s = proxyReq[1]; uint8 v = uint8(proxyReq[2][0]); // converting to uint248 will truncate the first byte, and we can then convert it to a bytes31. // we truncate the first byte because it's the `v` parm used above bytes31 proxyReq2 = bytes31(uint248(proxyReq[2])); // proxyReq[3] is ballotId - required for verifying sig but not used for anything else bytes32 ballotId = proxyReq[3]; bytes32 voteData = proxyReq[4]; // using abi.encodePacked is much cheaper than making bytes in other ways... bytes memory signed = abi.encodePacked(proxyReq2, ballotId, voteData, extra); bytes32 msgHash = keccak256(signed); // need to be sure we are signing the entire ballot and any extra data that comes with it voter = ecrecover(msgHash, v, r, s); // we need to make sure that this is the most recent vote the voter made, and that it has // not been seen before. NOTE: we've already validated the BBFarm namespace before this, so // we know it's meant for _this_ ballot. uint32 sequence = uint32(proxyReq2); // last 4 bytes of proxyReq2 - the sequence number _proxyReplayProtection(db, voter, sequence); _addVote(db, voteData, voter, extra); } function _addVote(DB storage db, bytes32 voteData, address sender, bytes extra) internal returns (uint256 id) { requireBallotOpen(db); id = db.nVotesCast; db.votes[id].voteData = voteData; // pack the casting ts right next to the sender db.votes[id].castTsAndSender = bytes32(sender) ^ bytes32(now << 160); if (extra.length > 0) { db.votes[id].extra = extra; } db.nVotesCast += 1; emit SuccessfulVote(sender, id); } function _proxyReplayProtection(DB storage db, address voter, uint32 sequence) internal { // we want the replay protection sequence number to be STRICTLY MORE than what // is stored in the mapping. This means we can set sequence to MAX_UINT32 to disable // any future votes. require(db.sequenceNumber[voter] < sequence, "bad-sequence-n"); db.sequenceNumber[voter] = sequence; } /* Admin */ function setEndTime(DB storage db, uint64 newEndTime) external { uint16 sb; uint64 sTs; (sb, sTs,) = BPackedUtils.unpackAll(db.packed); db.packed = BPackedUtils.pack(sb, sTs, newEndTime); } function revealSeckey(DB storage db, bytes32 sk) internal { db.ballotEncryptionSeckey = sk; emit SeckeyRevealed(sk); } /* Submission Bits (Ballot Classifications) */ // do (bits & SETTINGS_MASK) to get just operational bits (as opposed to testing or official flag) uint16 constant SETTINGS_MASK = 0xFFFF ^ USE_TESTING ^ IS_OFFICIAL ^ IS_BINDING; function isEthNoEnc(uint16 submissionBits) pure internal returns (bool) { return checkFlags(submissionBits, USE_ETH | USE_NO_ENC); } function isEthWithEnc(uint16 submissionBits) pure internal returns (bool) { return checkFlags(submissionBits, USE_ETH | USE_ENC); } function isOfficial(uint16 submissionBits) pure internal returns (bool) { return (submissionBits & IS_OFFICIAL) == IS_OFFICIAL; } function isBinding(uint16 submissionBits) pure internal returns (bool) { return (submissionBits & IS_BINDING) == IS_BINDING; } function isTesting(uint16 submissionBits) pure internal returns (bool) { return (submissionBits & USE_TESTING) == USE_TESTING; } function qualifiesAsCommunityBallot(uint16 submissionBits) pure internal returns (bool) { // if submissionBits AND any of the bits that make this _not_ a community // ballot is equal to zero that means none of those bits were active, so // it could be a community ballot return (submissionBits & (IS_BINDING | IS_OFFICIAL | USE_ENC)) == 0; } function checkFlags(uint16 submissionBits, uint16 expected) pure internal returns (bool) { // this should ignore ONLY the testing/flag bits - all other bits are significant uint16 sBitsNoSettings = submissionBits & SETTINGS_MASK; // then we want ONLY expected return sBitsNoSettings == expected; } } library BPackedUtils { // the uint16 ending at 128 bits should be 0s uint256 constant sbMask = 0xffffffffffffffffffffffffffff0000ffffffffffffffffffffffffffffffff; uint256 constant startTimeMask = 0xffffffffffffffffffffffffffffffff0000000000000000ffffffffffffffff; uint256 constant endTimeMask = 0xffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000; function packedToSubmissionBits(uint256 packed) internal pure returns (uint16) { return uint16(packed >> 128); } function packedToStartTime(uint256 packed) internal pure returns (uint64) { return uint64(packed >> 64); } function packedToEndTime(uint256 packed) internal pure returns (uint64) { return uint64(packed); } function unpackAll(uint256 packed) internal pure returns (uint16 submissionBits, uint64 startTime, uint64 endTime) { submissionBits = uint16(packed >> 128); startTime = uint64(packed >> 64); endTime = uint64(packed); } function pack(uint16 sb, uint64 st, uint64 et) internal pure returns (uint256 packed) { return uint256(sb) << 128 | uint256(st) << 64 | uint256(et); } function setSB(uint256 packed, uint16 newSB) internal pure returns (uint256) { return (packed & sbMask) | uint256(newSB) << 128; } // function setStartTime(uint256 packed, uint64 startTime) internal pure returns (uint256) { // return (packed & startTimeMask) | uint256(startTime) << 64; // } // function setEndTime(uint256 packed, uint64 endTime) internal pure returns (uint256) { // return (packed & endTimeMask) | uint256(endTime); // } } interface CommAuctionIface { function getNextPrice(bytes32 democHash) external view returns (uint); function noteBallotDeployed(bytes32 democHash) external; // add more when we need it function upgradeMe(address newSC) external; } library IxLib { /** * Usage: `using IxLib for IxIface` * The idea is to (instead of adding methods that already use * available public info to the index) we can create `internal` * methods in the lib to do this instead (which means the code * is inserted into other contracts inline, without a `delegatecall`. * * For this reason it's crucial to have no methods in IxLib with the * same name as methods in IxIface */ /* Global price and payments data */ function getPayTo(IxIface ix) internal view returns (address) { return ix.getPayments().getPayTo(); } /* Global Ix data */ function getBBFarmFromBallotID(IxIface ix, uint256 ballotId) internal view returns (BBFarmIface) { bytes4 bbNamespace = bytes4(ballotId >> 48); uint8 bbFarmId = ix.getBBFarmID(bbNamespace); return ix.getBBFarm(bbFarmId); } /* Global backend data */ function getGDemocsN(IxIface ix) internal view returns (uint256) { return ix.getBackend().getGDemocsN(); } function getGDemoc(IxIface ix, uint256 n) internal view returns (bytes32) { return ix.getBackend().getGDemoc(n); } function getGErc20ToDemocs(IxIface ix, address erc20) internal view returns (bytes32[] democHashes) { return ix.getBackend().getGErc20ToDemocs(erc20); } /* Democ specific payment/account data */ function accountInGoodStanding(IxIface ix, bytes32 democHash) internal view returns (bool) { return ix.getPayments().accountInGoodStanding(democHash); } function accountPremiumAndInGoodStanding(IxIface ix, bytes32 democHash) internal view returns (bool) { IxPaymentsIface payments = ix.getPayments(); return payments.accountInGoodStanding(democHash) && payments.getPremiumStatus(democHash); } function payForDemocracy(IxIface ix, bytes32 democHash) internal { ix.getPayments().payForDemocracy.value(msg.value)(democHash); } /* Democ getters */ function getDOwner(IxIface ix, bytes32 democHash) internal view returns (address) { return ix.getBackend().getDOwner(democHash); } function isDEditor(IxIface ix, bytes32 democHash, address editor) internal view returns (bool) { return ix.getBackend().isDEditor(democHash, editor); } function getDBallotsN(IxIface ix, bytes32 democHash) internal view returns (uint256) { return ix.getBackend().getDBallotsN(democHash); } function getDBallotID(IxIface ix, bytes32 democHash, uint256 n) internal view returns (uint256) { return ix.getBackend().getDBallotID(democHash, n); } function getDInfo(IxIface ix, bytes32 democHash) internal view returns (address erc20, address admin, uint256 _nBallots) { return ix.getBackend().getDInfo(democHash); } function getDErc20(IxIface ix, bytes32 democHash) internal view returns (address erc20) { return ix.getBackend().getDErc20(democHash); } function getDHash(IxIface ix, bytes13 prefix) internal view returns (bytes32) { return ix.getBackend().getDHash(prefix); } function getDCategoriesN(IxIface ix, bytes32 democHash) internal view returns (uint) { return ix.getBackend().getDCategoriesN(democHash); } function getDCategory(IxIface ix, bytes32 democHash, uint categoryId) internal view returns (bool, bytes32, bool, uint) { return ix.getBackend().getDCategory(democHash, categoryId); } function getDArbitraryData(IxIface ix, bytes32 democHash, bytes key) external view returns (bytes) { return ix.getBackend().getDArbitraryData(democHash, key); } } contract SVBallotConsts { // voting settings uint16 constant USE_ETH = 1; // 2^0 uint16 constant USE_SIGNED = 2; // 2^1 uint16 constant USE_NO_ENC = 4; // 2^2 uint16 constant USE_ENC = 8; // 2^3 // ballot settings uint16 constant IS_BINDING = 8192; // 2^13 uint16 constant IS_OFFICIAL = 16384; // 2^14 uint16 constant USE_TESTING = 32768; // 2^15 } contract safeSend { bool private txMutex3847834; // we want to be able to call outside contracts (e.g. the admin proxy contract) // but reentrency is bad, so here's a mutex. function doSafeSend(address toAddr, uint amount) internal { doSafeSendWData(toAddr, "", amount); } function doSafeSendWData(address toAddr, bytes data, uint amount) internal { require(txMutex3847834 == false, "ss-guard"); txMutex3847834 = true; // we need to use address.call.value(v)() because we want // to be able to send to other contracts, even with no data, // which might use more than 2300 gas in their fallback function. require(toAddr.call.value(amount)(data), "ss-failed"); txMutex3847834 = false; } } contract payoutAllC is safeSend { address private _payTo; event PayoutAll(address payTo, uint value); constructor(address initPayTo) public { // DEV NOTE: you can overwrite _getPayTo if you want to reuse other storage vars assert(initPayTo != address(0)); _payTo = initPayTo; } function _getPayTo() internal view returns (address) { return _payTo; } function _setPayTo(address newPayTo) internal { _payTo = newPayTo; } function payoutAll() external { address a = _getPayTo(); uint bal = address(this).balance; doSafeSend(a, bal); emit PayoutAll(a, bal); } } contract payoutAllCSettable is payoutAllC { constructor (address initPayTo) payoutAllC(initPayTo) public { } function setPayTo(address) external; function getPayTo() external view returns (address) { return _getPayTo(); } } contract owned { address public owner; event OwnerChanged(address newOwner); modifier only_owner() { require(msg.sender == owner, "only_owner: forbidden"); _; } modifier owner_or(address addr) { require(msg.sender == addr || msg.sender == owner, "!owner-or"); _; } constructor() public { owner = msg.sender; } function setOwner(address newOwner) only_owner() external { owner = newOwner; emit OwnerChanged(newOwner); } } contract CanReclaimToken is owned { /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Interface token) external only_owner { uint256 balance = token.balanceOf(this); require(token.approve(owner, balance)); } } contract CommunityAuctionSimple is owned { // about $1USD at $600usd/eth uint public commBallotPriceWei = 1666666666000000; struct Record { bytes32 democHash; uint ts; } mapping (address => Record[]) public ballotLog; mapping (address => address) public upgrades; function getNextPrice(bytes32) external view returns (uint) { return commBallotPriceWei; } function noteBallotDeployed(bytes32 d) external { require(upgrades[msg.sender] == address(0)); ballotLog[msg.sender].push(Record(d, now)); } function upgradeMe(address newSC) external { require(upgrades[msg.sender] == address(0)); upgrades[msg.sender] = newSC; } function getBallotLogN(address a) external view returns (uint) { return ballotLog[a].length; } function setPriceWei(uint newPrice) only_owner() external { commBallotPriceWei = newPrice; } } contract controlledIface { function controller() external view returns (address); } contract hasAdmins is owned { mapping (uint => mapping (address => bool)) admins; uint public currAdminEpoch = 0; bool public adminsDisabledForever = false; address[] adminLog; event AdminAdded(address indexed newAdmin); event AdminRemoved(address indexed oldAdmin); event AdminEpochInc(); event AdminDisabledForever(); modifier only_admin() { require(adminsDisabledForever == false, "admins must not be disabled"); require(isAdmin(msg.sender), "only_admin: forbidden"); _; } constructor() public { _setAdmin(msg.sender, true); } function isAdmin(address a) view public returns (bool) { return admins[currAdminEpoch][a]; } function getAdminLogN() view external returns (uint) { return adminLog.length; } function getAdminLog(uint n) view external returns (address) { return adminLog[n]; } function upgradeMeAdmin(address newAdmin) only_admin() external { // note: already checked msg.sender has admin with `only_admin` modifier require(msg.sender != owner, "owner cannot upgrade self"); _setAdmin(msg.sender, false); _setAdmin(newAdmin, true); } function setAdmin(address a, bool _givePerms) only_admin() external { require(a != msg.sender && a != owner, "cannot change your own (or owner's) permissions"); _setAdmin(a, _givePerms); } function _setAdmin(address a, bool _givePerms) internal { admins[currAdminEpoch][a] = _givePerms; if (_givePerms) { emit AdminAdded(a); adminLog.push(a); } else { emit AdminRemoved(a); } } // safety feature if admins go bad or something function incAdminEpoch() only_owner() external { currAdminEpoch++; admins[currAdminEpoch][msg.sender] = true; emit AdminEpochInc(); } // this is internal so contracts can all it, but not exposed anywhere in this // contract. function disableAdminForever() internal { currAdminEpoch++; adminsDisabledForever = true; emit AdminDisabledForever(); } } contract EnsOwnerProxy is hasAdmins { bytes32 public ensNode; ENSIface public ens; PublicResolver public resolver; /** * @param _ensNode The node to administer * @param _ens The ENS Registrar * @param _resolver The ENS Resolver */ constructor(bytes32 _ensNode, ENSIface _ens, PublicResolver _resolver) public { ensNode = _ensNode; ens = _ens; resolver = _resolver; } function setAddr(address addr) only_admin() external { _setAddr(addr); } function _setAddr(address addr) internal { resolver.setAddr(ensNode, addr); } function returnToOwner() only_owner() external { ens.setOwner(ensNode, owner); } function fwdToENS(bytes data) only_owner() external { require(address(ens).call(data), "fwding to ens failed"); } function fwdToResolver(bytes data) only_owner() external { require(address(resolver).call(data), "fwding to resolver failed"); } } contract permissioned is owned, hasAdmins { mapping (address => bool) editAllowed; bool public adminLockdown = false; event PermissionError(address editAddr); event PermissionGranted(address editAddr); event PermissionRevoked(address editAddr); event PermissionsUpgraded(address oldSC, address newSC); event SelfUpgrade(address oldSC, address newSC); event AdminLockdown(); modifier only_editors() { require(editAllowed[msg.sender], "only_editors: forbidden"); _; } modifier no_lockdown() { require(adminLockdown == false, "no_lockdown: check failed"); _; } constructor() owned() hasAdmins() public { } function setPermissions(address e, bool _editPerms) no_lockdown() only_admin() external { editAllowed[e] = _editPerms; if (_editPerms) emit PermissionGranted(e); else emit PermissionRevoked(e); } function upgradePermissionedSC(address oldSC, address newSC) no_lockdown() only_admin() external { editAllowed[oldSC] = false; editAllowed[newSC] = true; emit PermissionsUpgraded(oldSC, newSC); } // always allow SCs to upgrade themselves, even after lockdown function upgradeMe(address newSC) only_editors() external { editAllowed[msg.sender] = false; editAllowed[newSC] = true; emit SelfUpgrade(msg.sender, newSC); } function hasPermissions(address a) public view returns (bool) { return editAllowed[a]; } function doLockdown() external only_owner() no_lockdown() { disableAdminForever(); adminLockdown = true; emit AdminLockdown(); } } contract upgradePtr { address ptr = address(0); modifier not_upgraded() { require(ptr == address(0), "upgrade pointer is non-zero"); _; } function getUpgradePointer() view external returns (address) { return ptr; } function doUpgradeInternal(address nextSC) internal { ptr = nextSC; } } interface ERC20Interface { // Get the total token supply function totalSupply() constant external returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant external returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) external returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) external returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant external returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ixEvents { event PaymentMade(uint[2] valAndRemainder); event AddedBBFarm(uint8 bbFarmId); event SetBackend(bytes32 setWhat, address newSC); event DeprecatedBBFarm(uint8 bbFarmId); event CommunityBallot(bytes32 democHash, uint256 ballotId); event ManuallyAddedBallot(bytes32 democHash, uint256 ballotId, uint256 packed); // copied from BBFarm - unable to inherit from BBFarmEvents... event BallotCreatedWithID(uint ballotId); event BBFarmInit(bytes4 namespace); } contract ixBackendEvents { event NewDemoc(bytes32 democHash); event ManuallyAddedDemoc(bytes32 democHash, address erc20); event NewBallot(bytes32 indexed democHash, uint ballotN); event DemocOwnerSet(bytes32 indexed democHash, address owner); event DemocEditorSet(bytes32 indexed democHash, address editor, bool canEdit); event DemocEditorsWiped(bytes32 indexed democHash); event DemocErc20Set(bytes32 indexed democHash, address erc20); event DemocDataSet(bytes32 indexed democHash, bytes32 keyHash); event DemocCatAdded(bytes32 indexed democHash, uint catId); event DemocCatDeprecated(bytes32 indexed democHash, uint catId); event DemocCommunityBallotsEnabled(bytes32 indexed democHash, bool enabled); event DemocErc20OwnerClaimDisabled(bytes32 indexed democHash); event DemocClaimed(bytes32 indexed democHash); event EmergencyDemocOwner(bytes32 indexed democHash, address newOwner); } library SafeMath { function subToZero(uint a, uint b) internal pure returns (uint) { if (a < b) { // then (a - b) would overflow return 0; } return a - b; } } contract ixPaymentEvents { event UpgradedToPremium(bytes32 indexed democHash); event GrantedAccountTime(bytes32 indexed democHash, uint additionalSeconds, bytes32 ref); event AccountPayment(bytes32 indexed democHash, uint additionalSeconds); event SetCommunityBallotFee(uint amount); event SetBasicCentsPricePer30Days(uint amount); event SetPremiumMultiplier(uint8 multiplier); event DowngradeToBasic(bytes32 indexed democHash); event UpgradeToPremium(bytes32 indexed democHash); event SetExchangeRate(uint weiPerCent); event FreeExtension(bytes32 democHash); event SetBallotsPer30Days(uint amount); event SetFreeExtension(bytes32 democHash, bool hasFreeExt); event SetDenyPremium(bytes32 democHash, bool isPremiumDenied); event SetPayTo(address payTo); event SetMinorEditsAddr(address minorEditsAddr); event SetMinWeiForDInit(uint amount); } interface hasVersion { function getVersion() external pure returns (uint); } contract BBFarmIface is BBFarmEvents, permissioned, hasVersion, payoutAllC { /* global bbfarm getters */ function getNamespace() external view returns (bytes4); function getBBLibVersion() external view returns (uint256); function getNBallots() external view returns (uint256); /* init a ballot */ // note that the ballotId returned INCLUDES the namespace. function initBallot( bytes32 specHash , uint256 packed , IxIface ix , address bbAdmin , bytes24 extraData ) external returns (uint ballotId); /* Sponsorship of ballots */ function sponsor(uint ballotId) external payable; /* Voting functions */ function submitVote(uint ballotId, bytes32 vote, bytes extra) external; function submitProxyVote(bytes32[5] proxyReq, bytes extra) external; /* Ballot Getters */ function getDetails(uint ballotId, address voter) external view returns ( bool hasVoted , uint nVotesCast , bytes32 secKey , uint16 submissionBits , uint64 startTime , uint64 endTime , bytes32 specHash , bool deprecated , address ballotOwner , bytes16 extraData); function getVote(uint ballotId, uint voteId) external view returns (bytes32 voteData, address sender, bytes extra); function getTotalSponsorship(uint ballotId) external view returns (uint); function getSponsorsN(uint ballotId) external view returns (uint); function getSponsor(uint ballotId, uint sponsorN) external view returns (address sender, uint amount); function getCreationTs(uint ballotId) external view returns (uint); /* Admin on ballots */ function revealSeckey(uint ballotId, bytes32 sk) external; function setEndTime(uint ballotId, uint64 newEndTime) external; // note: testing only function setDeprecated(uint ballotId) external; function setBallotOwner(uint ballotId, address newOwner) external; } contract BBFarm is BBFarmIface { using BBLib for BBLib.DB; using IxLib for IxIface; // namespaces should be unique for each bbFarm bytes4 constant NAMESPACE = 0x00000001; // last 48 bits uint256 constant BALLOT_ID_MASK = 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint constant VERSION = 2; mapping (uint224 => BBLib.DB) dbs; // note - start at 100 to avoid any test for if 0 is a valid ballotId // also gives us some space to play with low numbers if we want. uint nBallots = 0; /* modifiers */ modifier req_namespace(uint ballotId) { // bytes4() will take the _first_ 4 bytes require(bytes4(ballotId >> 224) == NAMESPACE, "bad-namespace"); _; } /* Constructor */ constructor() payoutAllC(msg.sender) public { // this bbFarm requires v5 of BBLib (note: v4 deprecated immediately due to insecure submitProxyVote) // note: even though we can't test for this in coverage, this has stopped me deploying to kovan with the wrong version tho, so I consider it tested :) assert(BBLib.getVersion() == 6); emit BBFarmInit(NAMESPACE); } /* base SCs */ function _getPayTo() internal view returns (address) { return owner; } function getVersion() external pure returns (uint) { return VERSION; } /* global funcs */ function getNamespace() external view returns (bytes4) { return NAMESPACE; } function getBBLibVersion() external view returns (uint256) { return BBLib.getVersion(); } function getNBallots() external view returns (uint256) { return nBallots; } /* db lookup helper */ function getDb(uint ballotId) internal view returns (BBLib.DB storage) { // cut off anything above 224 bits (where the namespace goes) return dbs[uint224(ballotId)]; } /* Init ballot */ function initBallot( bytes32 specHash , uint256 packed , IxIface ix , address bbAdmin , bytes24 extraData ) only_editors() external returns (uint ballotId) { // calculate the ballotId based on the last 224 bits of the specHash. ballotId = uint224(specHash) ^ (uint256(NAMESPACE) << 224); // we need to call the init functions on our libraries getDb(ballotId).init(specHash, packed, ix, bbAdmin, bytes16(uint128(extraData))); nBallots += 1; emit BallotCreatedWithID(ballotId); } /* Sponsorship */ function sponsor(uint ballotId) external payable { BBLib.DB storage db = getDb(ballotId); db.logSponsorship(msg.value); doSafeSend(db.index.getPayTo(), msg.value); emit Sponsorship(ballotId, msg.value); } /* Voting */ function submitVote(uint ballotId, bytes32 vote, bytes extra) req_namespace(ballotId) external { getDb(ballotId).submitVote(vote, extra); emit Vote(ballotId, vote, msg.sender, extra); } function submitProxyVote(bytes32[5] proxyReq, bytes extra) req_namespace(uint256(proxyReq[3])) external { // see https://github.com/secure-vote/tokenvote/blob/master/Docs/DataStructs.md for breakdown of params // pr[3] is the ballotId, and pr[4] is the vote uint ballotId = uint256(proxyReq[3]); address voter = getDb(ballotId).submitProxyVote(proxyReq, extra); bytes32 vote = proxyReq[4]; emit Vote(ballotId, vote, voter, extra); } /* Getters */ // note - this is the maxmimum number of vars we can return with one // function call (taking 2 args) function getDetails(uint ballotId, address voter) external view returns ( bool hasVoted , uint nVotesCast , bytes32 secKey , uint16 submissionBits , uint64 startTime , uint64 endTime , bytes32 specHash , bool deprecated , address ballotOwner , bytes16 extraData) { BBLib.DB storage db = getDb(ballotId); uint packed = db.packed; return ( db.getSequenceNumber(voter) > 0, db.nVotesCast, db.ballotEncryptionSeckey, BPackedUtils.packedToSubmissionBits(packed), BPackedUtils.packedToStartTime(packed), BPackedUtils.packedToEndTime(packed), db.specHash, db.deprecated, db.ballotOwner, db.extraData ); } function getVote(uint ballotId, uint voteId) external view returns (bytes32 voteData, address sender, bytes extra) { (voteData, sender, extra, ) = getDb(ballotId).getVote(voteId); } function getSequenceNumber(uint ballotId, address voter) external view returns (uint32 sequence) { return getDb(ballotId).getSequenceNumber(voter); } function getTotalSponsorship(uint ballotId) external view returns (uint) { return getDb(ballotId).getTotalSponsorship(); } function getSponsorsN(uint ballotId) external view returns (uint) { return getDb(ballotId).sponsors.length; } function getSponsor(uint ballotId, uint sponsorN) external view returns (address sender, uint amount) { return getDb(ballotId).getSponsor(sponsorN); } function getCreationTs(uint ballotId) external view returns (uint) { return getDb(ballotId).creationTs; } /* ADMIN */ // Allow the owner to reveal the secret key after ballot conclusion function revealSeckey(uint ballotId, bytes32 sk) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.requireBallotClosed(); db.revealSeckey(sk); } // note: testing only. function setEndTime(uint ballotId, uint64 newEndTime) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.requireTesting(); db.setEndTime(newEndTime); } function setDeprecated(uint ballotId) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.deprecated = true; } function setBallotOwner(uint ballotId, address newOwner) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.ballotOwner = newOwner; } } contract IxIface is hasVersion, ixPaymentEvents, ixBackendEvents, ixEvents, SVBallotConsts, owned, CanReclaimToken, upgradePtr, payoutAllC { /* owner functions */ function addBBFarm(BBFarmIface bbFarm) external returns (uint8 bbFarmId); function setABackend(bytes32 toSet, address newSC) external; function deprecateBBFarm(uint8 bbFarmId, BBFarmIface _bbFarm) external; /* global getters */ function getPayments() external view returns (IxPaymentsIface); function getBackend() external view returns (IxBackendIface); function getBBFarm(uint8 bbFarmId) external view returns (BBFarmIface); function getBBFarmID(bytes4 bbNamespace) external view returns (uint8 bbFarmId); function getCommAuction() external view returns (CommAuctionIface); /* init a democ */ function dInit(address defualtErc20, bool disableErc20OwnerClaim) external payable returns (bytes32); /* democ owner / editor functions */ function setDEditor(bytes32 democHash, address editor, bool canEdit) external; function setDNoEditors(bytes32 democHash) external; function setDOwner(bytes32 democHash, address newOwner) external; function dOwnerErc20Claim(bytes32 democHash) external; function setDErc20(bytes32 democHash, address newErc20) external; function dAddCategory(bytes32 democHash, bytes32 categoryName, bool hasParent, uint parent) external; function dDeprecateCategory(bytes32 democHash, uint categoryId) external; function dUpgradeToPremium(bytes32 democHash) external; function dDowngradeToBasic(bytes32 democHash) external; function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) external; function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) external; function dDisableErc20OwnerClaim(bytes32 democHash) external; /* democ getters (that used to be here) should be called on either backend or payments directly */ /* use IxLib for convenience functions from other SCs */ /* ballot deployment */ // only ix owner - used for adding past or special ballots function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed) external; function dDeployCommunityBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint128 packedTimes) external payable; function dDeployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint256 packed) external payable; } contract SVIndex is IxIface { uint256 constant VERSION = 2; // generated from: `address public owner;` bytes4 constant OWNER_SIG = 0x8da5cb5b; // generated from: `address public controller;` bytes4 constant CONTROLLER_SIG = 0xf77c4791; /* backend & other SC storage */ IxBackendIface backend; IxPaymentsIface payments; EnsOwnerProxy public ensOwnerPx; BBFarmIface[] bbFarms; CommAuctionIface commAuction; // mapping from bbFarm namespace to bbFarmId mapping (bytes4 => uint8) bbFarmIdLookup; mapping (uint8 => bool) deprecatedBBFarms; //* MODIFIERS / modifier onlyDemocOwner(bytes32 democHash) { require(msg.sender == backend.getDOwner(democHash), "!d-owner"); _; } modifier onlyDemocEditor(bytes32 democHash) { require(backend.isDEditor(democHash, msg.sender), "!d-editor"); _; } /* FUNCTIONS */ // constructor constructor( IxBackendIface _b , IxPaymentsIface _pay , EnsOwnerProxy _ensOwnerPx , BBFarmIface _bbFarm0 , CommAuctionIface _commAuction ) payoutAllC(msg.sender) public { backend = _b; payments = _pay; ensOwnerPx = _ensOwnerPx; _addBBFarm(0x0, _bbFarm0); commAuction = _commAuction; } /* payoutAllC */ function _getPayTo() internal view returns (address) { return payments.getPayTo(); } /* UPGRADE STUFF */ function doUpgrade(address nextSC) only_owner() not_upgraded() external { doUpgradeInternal(nextSC); backend.upgradeMe(nextSC); payments.upgradeMe(nextSC); ensOwnerPx.setAddr(nextSC); ensOwnerPx.upgradeMeAdmin(nextSC); commAuction.upgradeMe(nextSC); for (uint i = 0; i < bbFarms.length; i++) { bbFarms[i].upgradeMe(nextSC); } } function _addBBFarm(bytes4 bbNamespace, BBFarmIface _bbFarm) internal returns (uint8 bbFarmId) { uint256 bbFarmIdLong = bbFarms.length; require(bbFarmIdLong < 2**8, "too-many-farms"); bbFarmId = uint8(bbFarmIdLong); bbFarms.push(_bbFarm); bbFarmIdLookup[bbNamespace] = bbFarmId; emit AddedBBFarm(bbFarmId); } // adding a new BBFarm function addBBFarm(BBFarmIface bbFarm) only_owner() external returns (uint8 bbFarmId) { bytes4 bbNamespace = bbFarm.getNamespace(); require(bbNamespace != bytes4(0), "bb-farm-namespace"); require(bbFarmIdLookup[bbNamespace] == 0 && bbNamespace != bbFarms[0].getNamespace(), "bb-namespace-used"); bbFarmId = _addBBFarm(bbNamespace, bbFarm); } function setABackend(bytes32 toSet, address newSC) only_owner() external { emit SetBackend(toSet, newSC); if (toSet == bytes32("payments")) { payments = IxPaymentsIface(newSC); } else if (toSet == bytes32("backend")) { backend = IxBackendIface(newSC); } else if (toSet == bytes32("commAuction")) { commAuction = CommAuctionIface(newSC); } else { revert("404"); } } function deprecateBBFarm(uint8 bbFarmId, BBFarmIface _bbFarm) only_owner() external { require(address(_bbFarm) != address(0)); require(bbFarms[bbFarmId] == _bbFarm); deprecatedBBFarms[bbFarmId] = true; emit DeprecatedBBFarm(bbFarmId); } /* Getters for backends */ function getPayments() external view returns (IxPaymentsIface) { return payments; } function getBackend() external view returns (IxBackendIface) { return backend; } function getBBFarm(uint8 bbFarmId) external view returns (BBFarmIface) { return bbFarms[bbFarmId]; } function getBBFarmID(bytes4 bbNamespace) external view returns (uint8 bbFarmId) { return bbFarmIdLookup[bbNamespace]; } function getCommAuction() external view returns (CommAuctionIface) { return commAuction; } //* GLOBAL INFO */ function getVersion() external pure returns (uint256) { return VERSION; } //* DEMOCRACY FUNCTIONS - INDIVIDUAL */ function dInit(address defaultErc20, bool disableErc20OwnerClaim) not_upgraded() external payable returns (bytes32) { require(msg.value >= payments.getMinWeiForDInit()); bytes32 democHash = backend.dInit(defaultErc20, msg.sender, disableErc20OwnerClaim); payments.payForDemocracy.value(msg.value)(democHash); return democHash; } // admin methods function setDEditor(bytes32 democHash, address editor, bool canEdit) onlyDemocOwner(democHash) external { backend.setDEditor(democHash, editor, canEdit); } function setDNoEditors(bytes32 democHash) onlyDemocOwner(democHash) external { backend.setDNoEditors(democHash); } function setDOwner(bytes32 democHash, address newOwner) onlyDemocOwner(democHash) external { backend.setDOwner(democHash, newOwner); } function dOwnerErc20Claim(bytes32 democHash) external { address erc20 = backend.getDErc20(democHash); // test if we can call the erc20.owner() method, etc // also limit gas use to 3000 because we don't know what they'll do with it // during testing both owned and controlled could be called from other contracts for 2525 gas. if (erc20.call.gas(3000)(OWNER_SIG)) { require(msg.sender == owned(erc20).owner.gas(3000)(), "!erc20-owner"); } else if (erc20.call.gas(3000)(CONTROLLER_SIG)) { require(msg.sender == controlledIface(erc20).controller.gas(3000)(), "!erc20-controller"); } else { revert(); } // now we are certain the sender deployed or controls the erc20 backend.setDOwnerFromClaim(democHash, msg.sender); } function setDErc20(bytes32 democHash, address newErc20) onlyDemocOwner(democHash) external { backend.setDErc20(democHash, newErc20); } function dAddCategory(bytes32 democHash, bytes32 catName, bool hasParent, uint parent) onlyDemocEditor(democHash) external { backend.dAddCategory(democHash, catName, hasParent, parent); } function dDeprecateCategory(bytes32 democHash, uint catId) onlyDemocEditor(democHash) external { backend.dDeprecateCategory(democHash, catId); } function dUpgradeToPremium(bytes32 democHash) onlyDemocOwner(democHash) external { payments.upgradeToPremium(democHash); } function dDowngradeToBasic(bytes32 democHash) onlyDemocOwner(democHash) external { payments.downgradeToBasic(democHash); } function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) external { if (msg.sender == backend.getDOwner(democHash)) { backend.dSetArbitraryData(democHash, key, value); } else if (backend.isDEditor(democHash, msg.sender)) { backend.dSetEditorArbitraryData(democHash, key, value); } else { revert(); } } function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) onlyDemocOwner(democHash) external { backend.dSetCommunityBallotsEnabled(democHash, enabled); } // this is one way only! function dDisableErc20OwnerClaim(bytes32 democHash) onlyDemocOwner(democHash) external { backend.dDisableErc20OwnerClaim(democHash); } /* Democ Getters - deprecated */ // NOTE: the getters that used to live here just proxied to the backend. // this has been removed to reduce gas costs + size of Ix contract // For SCs you should use IxLib for convenience. // For Offchain use you should query the backend directly (via ix.getBackend()) /* Add and Deploy Ballots */ // manually add a ballot - only the owner can call this // WARNING - it's required that we make ABSOLUTELY SURE that // ballotId is valid and can resolve via the appropriate BBFarm. // this function _DOES NOT_ validate that everything else is done. function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed) only_owner() external { _addBallot(democHash, ballotId, packed, false); emit ManuallyAddedBallot(democHash, ballotId, packed); } function _deployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint packed, bool checkLimit, bool alreadySentTx) internal returns (uint ballotId) { require(BBLib.isTesting(BPackedUtils.packedToSubmissionBits(packed)) == false, "b-testing"); // the most significant byte of extraData signals the bbFarm to use. uint8 bbFarmId = uint8(extraData[0]); require(deprecatedBBFarms[bbFarmId] == false, "bb-dep"); BBFarmIface _bbFarm = bbFarms[bbFarmId]; // anything that isn't a community ballot counts towards the basic limit. // we want to check in cases where // the ballot doesn't qualify as a community ballot // OR (the ballot qualifies as a community ballot // AND the admins have _disabled_ community ballots). bool countTowardsLimit = checkLimit; bool performedSend; if (checkLimit) { uint64 endTime = BPackedUtils.packedToEndTime(packed); (countTowardsLimit, performedSend) = _basicBallotLimitOperations(democHash, _bbFarm); _accountOkayChecks(democHash, endTime); } if (!performedSend && msg.value > 0 && alreadySentTx == false) { // refund if we haven't send value anywhere (which might happen if someone accidentally pays us) doSafeSend(msg.sender, msg.value); } ballotId = _bbFarm.initBallot( specHash, packed, this, msg.sender, // we are certain that the first 8 bytes are for index use only. // truncating extraData like this means we can occasionally // save on gas. we need to use uint192 first because that will take // the _last_ 24 bytes of extraData. bytes24(uint192(extraData))); _addBallot(democHash, ballotId, packed, countTowardsLimit); } function dDeployCommunityBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint128 packedTimes) external payable { uint price = commAuction.getNextPrice(democHash); require(msg.value >= price, "!cb-fee"); doSafeSend(payments.getPayTo(), price); doSafeSend(msg.sender, msg.value - price); bool canProceed = backend.getDCommBallotsEnabled(democHash) || !payments.accountInGoodStanding(democHash); require(canProceed, "!cb-enabled"); uint256 packed = BPackedUtils.setSB(uint256(packedTimes), (USE_ETH | USE_NO_ENC)); uint ballotId = _deployBallot(democHash, specHash, extraData, packed, false, true); commAuction.noteBallotDeployed(democHash); emit CommunityBallot(democHash, ballotId); } // only way a democ admin can deploy a ballot function dDeployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint256 packed) onlyDemocEditor(democHash) external payable { _deployBallot(democHash, specHash, extraData, packed, true, false); } // internal logic around adding a ballot function _addBallot(bytes32 democHash, uint256 ballotId, uint256 packed, bool countTowardsLimit) internal { // backend handles events backend.dAddBallot(democHash, ballotId, packed, countTowardsLimit); } // check an account has paid up enough for this ballot function _accountOkayChecks(bytes32 democHash, uint64 endTime) internal view { // if the ballot is marked as official require the democracy is paid up to // some relative amount - exclude NFP accounts from this check uint secsLeft = payments.getSecondsRemaining(democHash); // must be positive due to ending in future check uint256 secsToEndTime = endTime - now; // require ballots end no more than twice the time left on the democracy require(secsLeft * 2 > secsToEndTime, "unpaid"); } function _basicBallotLimitOperations(bytes32 democHash, BBFarmIface _bbFarm) internal returns (bool shouldCount, bool performedSend) { // if we're an official ballot and the democ is basic, ensure the democ // isn't over the ballots/mo limit if (payments.getPremiumStatus(democHash) == false) { uint nBallotsAllowed = payments.getBasicBallotsPer30Days(); uint nBallotsBasicCounted = backend.getDCountedBasicBallotsN(democHash); // if the democ has less than nBallotsAllowed then it's guarenteed to be okay if (nBallotsAllowed > nBallotsBasicCounted) { // and we should count this ballot return (true, false); } // we want to check the creation timestamp of the nth most recent ballot // where n is the # of ballots allowed per month. Note: there isn't an off // by 1 error here because if 1 ballots were allowed per month then we'd want // to look at the most recent ballot, so nBallotsBasicCounted-1 in this case. // similarly, if X ballots were allowed per month we want to look at // nBallotsBasicCounted-X. There would thus be (X-1) ballots that are _more_ // recent than the one we're looking for. uint earlyBallotId = backend.getDCountedBasicBallotID(democHash, nBallotsBasicCounted - nBallotsAllowed); uint earlyBallotTs = _bbFarm.getCreationTs(earlyBallotId); // if the earlyBallot was created more than 30 days in the past we should // count the new ballot if (earlyBallotTs < now - 30 days) { return (true, false); } // at this point it may be the case that we shouldn't allow the ballot // to be created. (It's an official ballot for a basic tier democracy // where the Nth most recent ballot was created within the last 30 days.) // We should now check for payment uint extraBallotFee = payments.getBasicExtraBallotFeeWei(); require(msg.value >= extraBallotFee, "!extra-b-fee"); // now that we know they've paid the fee, we should send Eth to `payTo` // and return the remainder. uint remainder = msg.value - extraBallotFee; doSafeSend(address(payments), extraBallotFee); doSafeSend(msg.sender, remainder); emit PaymentMade([extraBallotFee, remainder]); // only in this case (for basic) do we want to return false - don't count towards the // limit because it's been paid for here. return (false, true); } else { // if we're premium we don't count ballots return (false, false); } } } contract IxBackendIface is hasVersion, ixBackendEvents, permissioned, payoutAllC { /* global getters */ function getGDemocsN() external view returns (uint); function getGDemoc(uint id) external view returns (bytes32); function getGErc20ToDemocs(address erc20) external view returns (bytes32[] democHashes); /* owner functions */ function dAdd(bytes32 democHash, address erc20, bool disableErc20OwnerClaim) external; function emergencySetDOwner(bytes32 democHash, address newOwner) external; /* democ admin */ function dInit(address defaultErc20, address initOwner, bool disableErc20OwnerClaim) external returns (bytes32 democHash); function setDOwner(bytes32 democHash, address newOwner) external; function setDOwnerFromClaim(bytes32 democHash, address newOwner) external; function setDEditor(bytes32 democHash, address editor, bool canEdit) external; function setDNoEditors(bytes32 democHash) external; function setDErc20(bytes32 democHash, address newErc20) external; function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) external; function dSetEditorArbitraryData(bytes32 democHash, bytes key, bytes value) external; function dAddCategory(bytes32 democHash, bytes32 categoryName, bool hasParent, uint parent) external; function dDeprecateCategory(bytes32 democHash, uint catId) external; function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) external; function dDisableErc20OwnerClaim(bytes32 democHash) external; /* actually add a ballot */ function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed, bool countTowardsLimit) external; /* global democ getters */ function getDOwner(bytes32 democHash) external view returns (address); function isDEditor(bytes32 democHash, address editor) external view returns (bool); function getDHash(bytes13 prefix) external view returns (bytes32); function getDInfo(bytes32 democHash) external view returns (address erc20, address owner, uint256 nBallots); function getDErc20(bytes32 democHash) external view returns (address); function getDArbitraryData(bytes32 democHash, bytes key) external view returns (bytes value); function getDEditorArbitraryData(bytes32 democHash, bytes key) external view returns (bytes value); function getDBallotsN(bytes32 democHash) external view returns (uint256); function getDBallotID(bytes32 democHash, uint n) external view returns (uint ballotId); function getDCountedBasicBallotsN(bytes32 democHash) external view returns (uint256); function getDCountedBasicBallotID(bytes32 democHash, uint256 n) external view returns (uint256); function getDCategoriesN(bytes32 democHash) external view returns (uint); function getDCategory(bytes32 democHash, uint catId) external view returns (bool deprecated, bytes32 name, bool hasParent, uint parent); function getDCommBallotsEnabled(bytes32 democHash) external view returns (bool); function getDErc20OwnerClaimEnabled(bytes32 democHash) external view returns (bool); } contract SVIndexBackend is IxBackendIface { uint constant VERSION = 2; struct Democ { address erc20; address owner; bool communityBallotsDisabled; bool erc20OwnerClaimDisabled; uint editorEpoch; mapping (uint => mapping (address => bool)) editors; uint256[] allBallots; uint256[] includedBasicBallots; // the IDs of official ballots } struct BallotRef { bytes32 democHash; uint ballotId; } struct Category { bool deprecated; bytes32 name; bool hasParent; uint parent; } struct CategoriesIx { uint nCategories; mapping(uint => Category) categories; } mapping (bytes32 => Democ) democs; mapping (bytes32 => CategoriesIx) democCategories; mapping (bytes13 => bytes32) democPrefixToHash; mapping (address => bytes32[]) erc20ToDemocs; bytes32[] democList; // allows democ admins to store arbitrary data // this lets us (for example) set particular keys to signal cerain // things to client apps s.t. the admin can turn them on and off. // arbitraryData[democHash][key] mapping (bytes32 => mapping (bytes32 => bytes)) arbitraryData; /* constructor */ constructor() payoutAllC(msg.sender) public { // do nothing } /* base contract overloads */ function _getPayTo() internal view returns (address) { return owner; } function getVersion() external pure returns (uint) { return VERSION; } /* GLOBAL INFO */ function getGDemocsN() external view returns (uint) { return democList.length; } function getGDemoc(uint id) external view returns (bytes32) { return democList[id]; } function getGErc20ToDemocs(address erc20) external view returns (bytes32[] democHashes) { return erc20ToDemocs[erc20]; } /* DEMOCRACY ADMIN FUNCTIONS */ function _addDemoc(bytes32 democHash, address erc20, address initOwner, bool disableErc20OwnerClaim) internal { democList.push(democHash); Democ storage d = democs[democHash]; d.erc20 = erc20; if (disableErc20OwnerClaim) { d.erc20OwnerClaimDisabled = true; } // this should never trigger if we have a good security model - entropy for 13 bytes ~ 2^(8*13) ~ 10^31 assert(democPrefixToHash[bytes13(democHash)] == bytes32(0)); democPrefixToHash[bytes13(democHash)] = democHash; erc20ToDemocs[erc20].push(democHash); _setDOwner(democHash, initOwner); emit NewDemoc(democHash); } /* owner democ admin functions */ function dAdd(bytes32 democHash, address erc20, bool disableErc20OwnerClaim) only_owner() external { _addDemoc(democHash, erc20, msg.sender, disableErc20OwnerClaim); emit ManuallyAddedDemoc(democHash, erc20); } /* Preferably for emergencies only */ function emergencySetDOwner(bytes32 democHash, address newOwner) only_owner() external { _setDOwner(democHash, newOwner); emit EmergencyDemocOwner(democHash, newOwner); } /* user democ admin functions */ function dInit(address defaultErc20, address initOwner, bool disableErc20OwnerClaim) only_editors() external returns (bytes32 democHash) { // generating the democHash in this way guarentees it'll be unique/hard-to-brute-force // (particularly because prevBlockHash and now are part of the hash) democHash = keccak256(abi.encodePacked(democList.length, blockhash(block.number-1), defaultErc20, now)); _addDemoc(democHash, defaultErc20, initOwner, disableErc20OwnerClaim); } function _setDOwner(bytes32 democHash, address newOwner) internal { Democ storage d = democs[democHash]; uint epoch = d.editorEpoch; d.owner = newOwner; // unset prev owner as editor - does little if one was not set d.editors[epoch][d.owner] = false; // make new owner an editor too d.editors[epoch][newOwner] = true; emit DemocOwnerSet(democHash, newOwner); } function setDOwner(bytes32 democHash, address newOwner) only_editors() external { _setDOwner(democHash, newOwner); } function setDOwnerFromClaim(bytes32 democHash, address newOwner) only_editors() external { Democ storage d = democs[democHash]; // make sure that the owner claim is enabled (i.e. the disabled flag is false) require(d.erc20OwnerClaimDisabled == false, "!erc20-claim"); // set owner and editor d.owner = newOwner; d.editors[d.editorEpoch][newOwner] = true; // disable the ability to claim now that it's done d.erc20OwnerClaimDisabled = true; emit DemocOwnerSet(democHash, newOwner); emit DemocClaimed(democHash); } function setDEditor(bytes32 democHash, address editor, bool canEdit) only_editors() external { Democ storage d = democs[democHash]; d.editors[d.editorEpoch][editor] = canEdit; emit DemocEditorSet(democHash, editor, canEdit); } function setDNoEditors(bytes32 democHash) only_editors() external { democs[democHash].editorEpoch += 1; emit DemocEditorsWiped(democHash); } function setDErc20(bytes32 democHash, address newErc20) only_editors() external { democs[democHash].erc20 = newErc20; erc20ToDemocs[newErc20].push(democHash); emit DemocErc20Set(democHash, newErc20); } function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) only_editors() external { bytes32 k = keccak256(key); arbitraryData[democHash][k] = value; emit DemocDataSet(democHash, k); } function dSetEditorArbitraryData(bytes32 democHash, bytes key, bytes value) only_editors() external { bytes32 k = keccak256(_calcEditorKey(key)); arbitraryData[democHash][k] = value; emit DemocDataSet(democHash, k); } function dAddCategory(bytes32 democHash, bytes32 name, bool hasParent, uint parent) only_editors() external { uint catId = democCategories[democHash].nCategories; democCategories[democHash].categories[catId].name = name; if (hasParent) { democCategories[democHash].categories[catId].hasParent = true; democCategories[democHash].categories[catId].parent = parent; } democCategories[democHash].nCategories += 1; emit DemocCatAdded(democHash, catId); } function dDeprecateCategory(bytes32 democHash, uint catId) only_editors() external { democCategories[democHash].categories[catId].deprecated = true; emit DemocCatDeprecated(democHash, catId); } function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) only_editors() external { democs[democHash].communityBallotsDisabled = !enabled; emit DemocCommunityBallotsEnabled(democHash, enabled); } function dDisableErc20OwnerClaim(bytes32 democHash) only_editors() external { democs[democHash].erc20OwnerClaimDisabled = true; emit DemocErc20OwnerClaimDisabled(democHash); } //* ADD BALLOT TO RECORD */ function _commitBallot(bytes32 democHash, uint ballotId, uint256 packed, bool countTowardsLimit) internal { uint16 subBits; subBits = BPackedUtils.packedToSubmissionBits(packed); uint localBallotId = democs[democHash].allBallots.length; democs[democHash].allBallots.push(ballotId); // do this for anything that doesn't qualify as a community ballot if (countTowardsLimit) { democs[democHash].includedBasicBallots.push(ballotId); } emit NewBallot(democHash, localBallotId); } // what SVIndex uses to add a ballot function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed, bool countTowardsLimit) only_editors() external { _commitBallot(democHash, ballotId, packed, countTowardsLimit); } /* democ getters */ function getDOwner(bytes32 democHash) external view returns (address) { return democs[democHash].owner; } function isDEditor(bytes32 democHash, address editor) external view returns (bool) { Democ storage d = democs[democHash]; // allow either an editor or always the owner return d.editors[d.editorEpoch][editor] || editor == d.owner; } function getDHash(bytes13 prefix) external view returns (bytes32) { return democPrefixToHash[prefix]; } function getDInfo(bytes32 democHash) external view returns (address erc20, address owner, uint256 nBallots) { return (democs[democHash].erc20, democs[democHash].owner, democs[democHash].allBallots.length); } function getDErc20(bytes32 democHash) external view returns (address) { return democs[democHash].erc20; } function getDArbitraryData(bytes32 democHash, bytes key) external view returns (bytes) { return arbitraryData[democHash][keccak256(key)]; } function getDEditorArbitraryData(bytes32 democHash, bytes key) external view returns (bytes) { return arbitraryData[democHash][keccak256(_calcEditorKey(key))]; } function getDBallotsN(bytes32 democHash) external view returns (uint256) { return democs[democHash].allBallots.length; } function getDBallotID(bytes32 democHash, uint256 n) external view returns (uint ballotId) { return democs[democHash].allBallots[n]; } function getDCountedBasicBallotsN(bytes32 democHash) external view returns (uint256) { return democs[democHash].includedBasicBallots.length; } function getDCountedBasicBallotID(bytes32 democHash, uint256 n) external view returns (uint256) { return democs[democHash].includedBasicBallots[n]; } function getDCategoriesN(bytes32 democHash) external view returns (uint) { return democCategories[democHash].nCategories; } function getDCategory(bytes32 democHash, uint catId) external view returns (bool deprecated, bytes32 name, bool hasParent, uint256 parent) { deprecated = democCategories[democHash].categories[catId].deprecated; name = democCategories[democHash].categories[catId].name; hasParent = democCategories[democHash].categories[catId].hasParent; parent = democCategories[democHash].categories[catId].parent; } function getDCommBallotsEnabled(bytes32 democHash) external view returns (bool) { return !democs[democHash].communityBallotsDisabled; } function getDErc20OwnerClaimEnabled(bytes32 democHash) external view returns (bool) { return !democs[democHash].erc20OwnerClaimDisabled; } /* util for calculating editor key */ function _calcEditorKey(bytes key) internal pure returns (bytes) { return abi.encodePacked("editor.", key); } } contract IxPaymentsIface is hasVersion, ixPaymentEvents, permissioned, CanReclaimToken, payoutAllCSettable { /* in emergency break glass */ function emergencySetOwner(address newOwner) external; /* financial calcluations */ function weiBuysHowManySeconds(uint amount) public view returns (uint secs); function weiToCents(uint w) public view returns (uint); function centsToWei(uint c) public view returns (uint); /* account management */ function payForDemocracy(bytes32 democHash) external payable; function doFreeExtension(bytes32 democHash) external; function downgradeToBasic(bytes32 democHash) external; function upgradeToPremium(bytes32 democHash) external; /* account status - getters */ function accountInGoodStanding(bytes32 democHash) external view returns (bool); function getSecondsRemaining(bytes32 democHash) external view returns (uint); function getPremiumStatus(bytes32 democHash) external view returns (bool); function getFreeExtension(bytes32 democHash) external view returns (bool); function getAccount(bytes32 democHash) external view returns (bool isPremium, uint lastPaymentTs, uint paidUpTill, bool hasFreeExtension); function getDenyPremium(bytes32 democHash) external view returns (bool); /* admin utils for accounts */ function giveTimeToDemoc(bytes32 democHash, uint additionalSeconds, bytes32 ref) external; /* admin setters global */ function setPayTo(address) external; function setMinorEditsAddr(address) external; function setBasicCentsPricePer30Days(uint amount) external; function setBasicBallotsPer30Days(uint amount) external; function setPremiumMultiplier(uint8 amount) external; function setWeiPerCent(uint) external; function setFreeExtension(bytes32 democHash, bool hasFreeExt) external; function setDenyPremium(bytes32 democHash, bool isPremiumDenied) external; function setMinWeiForDInit(uint amount) external; /* global getters */ function getBasicCentsPricePer30Days() external view returns(uint); function getBasicExtraBallotFeeWei() external view returns (uint); function getBasicBallotsPer30Days() external view returns (uint); function getPremiumMultiplier() external view returns (uint8); function getPremiumCentsPricePer30Days() external view returns (uint); function getWeiPerCent() external view returns (uint weiPerCent); function getUsdEthExchangeRate() external view returns (uint centsPerEth); function getMinWeiForDInit() external view returns (uint); /* payments stuff */ function getPaymentLogN() external view returns (uint); function getPaymentLog(uint n) external view returns (bool _external, bytes32 _democHash, uint _seconds, uint _ethValue); } contract SVPayments is IxPaymentsIface { uint constant VERSION = 2; struct Account { bool isPremium; uint lastPaymentTs; uint paidUpTill; uint lastUpgradeTs; // timestamp of the last time it was upgraded to premium } struct PaymentLog { bool _external; bytes32 _democHash; uint _seconds; uint _ethValue; } // this is an address that's only allowed to make minor edits // e.g. setExchangeRate, setDenyPremium, giveTimeToDemoc address public minorEditsAddr; // payment details uint basicCentsPricePer30Days = 125000; // $1250/mo uint basicBallotsPer30Days = 10; uint8 premiumMultiplier = 5; uint weiPerCent = 0.000016583747 ether; // $603, 4th June 2018 uint minWeiForDInit = 1; // minimum 1 wei - match existing behaviour in SVIndex mapping (bytes32 => Account) accounts; PaymentLog[] payments; // can set this on freeExtension democs to deny them premium upgrades mapping (bytes32 => bool) denyPremium; // this is used for non-profits or organisations that have perpetual licenses, etc mapping (bytes32 => bool) freeExtension; /* BREAK GLASS IN CASE OF EMERGENCY */ // this is included here because something going wrong with payments is possibly // the absolute worst case. Note: does this have negligable benefit if the other // contracts are compromised? (e.g. by a leaked privkey) address public emergencyAdmin; function emergencySetOwner(address newOwner) external { require(msg.sender == emergencyAdmin, "!emergency-owner"); owner = newOwner; } /* END BREAK GLASS */ constructor(address _emergencyAdmin) payoutAllCSettable(msg.sender) public { emergencyAdmin = _emergencyAdmin; assert(_emergencyAdmin != address(0)); } /* base SCs */ function getVersion() external pure returns (uint) { return VERSION; } function() payable public { _getPayTo().transfer(msg.value); } function _modAccountBalance(bytes32 democHash, uint additionalSeconds) internal { uint prevPaidTill = accounts[democHash].paidUpTill; if (prevPaidTill < now) { prevPaidTill = now; } accounts[democHash].paidUpTill = prevPaidTill + additionalSeconds; accounts[democHash].lastPaymentTs = now; } /* Financial Calculations */ function weiBuysHowManySeconds(uint amount) public view returns (uint) { uint centsPaid = weiToCents(amount); // multiply by 10**18 to ensure we make rounding errors insignificant uint monthsOffsetPaid = ((10 ** 18) * centsPaid) / basicCentsPricePer30Days; uint secondsOffsetPaid = monthsOffsetPaid * (30 days); uint additionalSeconds = secondsOffsetPaid / (10 ** 18); return additionalSeconds; } function weiToCents(uint w) public view returns (uint) { return w / weiPerCent; } function centsToWei(uint c) public view returns (uint) { return c * weiPerCent; } /* account management */ function payForDemocracy(bytes32 democHash) external payable { require(msg.value > 0, "need to send some ether to make payment"); uint additionalSeconds = weiBuysHowManySeconds(msg.value); if (accounts[democHash].isPremium) { additionalSeconds /= premiumMultiplier; } if (additionalSeconds >= 1) { _modAccountBalance(democHash, additionalSeconds); } payments.push(PaymentLog(false, democHash, additionalSeconds, msg.value)); emit AccountPayment(democHash, additionalSeconds); _getPayTo().transfer(msg.value); } function doFreeExtension(bytes32 democHash) external { require(freeExtension[democHash], "!free"); uint newPaidUpTill = now + 60 days; accounts[democHash].paidUpTill = newPaidUpTill; emit FreeExtension(democHash); } function downgradeToBasic(bytes32 democHash) only_editors() external { require(accounts[democHash].isPremium, "!premium"); accounts[democHash].isPremium = false; // convert premium minutes to basic uint paidTill = accounts[democHash].paidUpTill; uint timeRemaining = SafeMath.subToZero(paidTill, now); // if we have time remaining: convert it if (timeRemaining > 0) { // prevent accounts from downgrading if they have time remaining // and upgraded less than 24hrs ago require(accounts[democHash].lastUpgradeTs < (now - 24 hours), "downgrade-too-soon"); timeRemaining *= premiumMultiplier; accounts[democHash].paidUpTill = now + timeRemaining; } emit DowngradeToBasic(democHash); } function upgradeToPremium(bytes32 democHash) only_editors() external { require(denyPremium[democHash] == false, "upgrade-denied"); require(!accounts[democHash].isPremium, "!basic"); accounts[democHash].isPremium = true; // convert basic minutes to premium minutes uint paidTill = accounts[democHash].paidUpTill; uint timeRemaining = SafeMath.subToZero(paidTill, now); // if we have time remaning then convert it - otherwise don't need to do anything if (timeRemaining > 0) { timeRemaining /= premiumMultiplier; accounts[democHash].paidUpTill = now + timeRemaining; } accounts[democHash].lastUpgradeTs = now; emit UpgradedToPremium(democHash); } /* account status - getters */ function accountInGoodStanding(bytes32 democHash) external view returns (bool) { return accounts[democHash].paidUpTill >= now; } function getSecondsRemaining(bytes32 democHash) external view returns (uint) { return SafeMath.subToZero(accounts[democHash].paidUpTill, now); } function getPremiumStatus(bytes32 democHash) external view returns (bool) { return accounts[democHash].isPremium; } function getFreeExtension(bytes32 democHash) external view returns (bool) { return freeExtension[democHash]; } function getAccount(bytes32 democHash) external view returns (bool isPremium, uint lastPaymentTs, uint paidUpTill, bool hasFreeExtension) { isPremium = accounts[democHash].isPremium; lastPaymentTs = accounts[democHash].lastPaymentTs; paidUpTill = accounts[democHash].paidUpTill; hasFreeExtension = freeExtension[democHash]; } function getDenyPremium(bytes32 democHash) external view returns (bool) { return denyPremium[democHash]; } /* admin utils for accounts */ function giveTimeToDemoc(bytes32 democHash, uint additionalSeconds, bytes32 ref) owner_or(minorEditsAddr) external { _modAccountBalance(democHash, additionalSeconds); payments.push(PaymentLog(true, democHash, additionalSeconds, 0)); emit GrantedAccountTime(democHash, additionalSeconds, ref); } /* admin setters global */ function setPayTo(address newPayTo) only_owner() external { _setPayTo(newPayTo); emit SetPayTo(newPayTo); } function setMinorEditsAddr(address a) only_owner() external { minorEditsAddr = a; emit SetMinorEditsAddr(a); } function setBasicCentsPricePer30Days(uint amount) only_owner() external { basicCentsPricePer30Days = amount; emit SetBasicCentsPricePer30Days(amount); } function setBasicBallotsPer30Days(uint amount) only_owner() external { basicBallotsPer30Days = amount; emit SetBallotsPer30Days(amount); } function setPremiumMultiplier(uint8 m) only_owner() external { premiumMultiplier = m; emit SetPremiumMultiplier(m); } function setWeiPerCent(uint wpc) owner_or(minorEditsAddr) external { weiPerCent = wpc; emit SetExchangeRate(wpc); } function setFreeExtension(bytes32 democHash, bool hasFreeExt) owner_or(minorEditsAddr) external { freeExtension[democHash] = hasFreeExt; emit SetFreeExtension(democHash, hasFreeExt); } function setDenyPremium(bytes32 democHash, bool isPremiumDenied) owner_or(minorEditsAddr) external { denyPremium[democHash] = isPremiumDenied; emit SetDenyPremium(democHash, isPremiumDenied); } function setMinWeiForDInit(uint amount) owner_or(minorEditsAddr) external { minWeiForDInit = amount; emit SetMinWeiForDInit(amount); } /* global getters */ function getBasicCentsPricePer30Days() external view returns (uint) { return basicCentsPricePer30Days; } function getBasicExtraBallotFeeWei() external view returns (uint) { return centsToWei(basicCentsPricePer30Days / basicBallotsPer30Days); } function getBasicBallotsPer30Days() external view returns (uint) { return basicBallotsPer30Days; } function getPremiumMultiplier() external view returns (uint8) { return premiumMultiplier; } function getPremiumCentsPricePer30Days() external view returns (uint) { return _premiumPricePer30Days(); } function _premiumPricePer30Days() internal view returns (uint) { return uint(premiumMultiplier) * basicCentsPricePer30Days; } function getWeiPerCent() external view returns (uint) { return weiPerCent; } function getUsdEthExchangeRate() external view returns (uint) { // this returns cents per ether return 1 ether / weiPerCent; } function getMinWeiForDInit() external view returns (uint) { return minWeiForDInit; } /* payments stuff */ function getPaymentLogN() external view returns (uint) { return payments.length; } function getPaymentLog(uint n) external view returns (bool _external, bytes32 _democHash, uint _seconds, uint _ethValue) { _external = payments[n]._external; _democHash = payments[n]._democHash; _seconds = payments[n]._seconds; _ethValue = payments[n]._ethValue; } } interface SvEnsIface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns (bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } interface ENSIface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } ENSIface ens; mapping (bytes32 => Record) records; modifier only_owner(bytes32 node) { require(ens.owner(node) == msg.sender); _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ constructor(ENSIface ensAddr) public { ens = ensAddr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) public only_owner(node) { records[node].addr = addr; emit AddrChanged(node, addr); } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) public only_owner(node) { records[node].content = hash; emit ContentChanged(node, hash); } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) public only_owner(node) { records[node].name = name; emit NameChanged(node, name); } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); records[node].abis[contentType] = data; emit ABIChanged(node, contentType); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) { records[node].pubkey = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) public only_owner(node) { records[node].text[key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public view returns (string) { return records[node].text[key]; } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) { Record storage record = records[node]; for (contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public view returns (string) { return records[node].name; } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public view returns (bytes32) { return records[node].content; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address) { return records[node].addr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } } library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes _bytes, uint _start, uint _length) internal pure returns (bytes) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } }
we are certain that the first 8 bytes are for index use only. truncating extraData like this means we can occasionally save on gas. we need to use uint192 first because that will take the _last_ 24 bytes of extraData.
bytes24(uint192(extraData)));
296,403
[ 1, 4625, 348, 7953, 560, 30, 225, 732, 854, 8626, 716, 326, 1122, 1725, 1731, 854, 364, 770, 999, 1338, 18, 6956, 1776, 2870, 751, 3007, 333, 4696, 732, 848, 9145, 345, 285, 1230, 1923, 603, 16189, 18, 732, 1608, 358, 999, 2254, 15561, 1122, 2724, 716, 903, 4862, 326, 389, 2722, 67, 4248, 1731, 434, 2870, 751, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1731, 3247, 12, 11890, 15561, 12, 7763, 751, 3719, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-09-18 */ /** *Submitted for verification at Etherscan.io on 2020-09-18 */ // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol pragma solidity 0.5.7; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: nexusmutual-contracts/contracts/NXMToken.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address to, uint256 value) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function _transferFrom( address from, address to, uint256 value ) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns(uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMaster { function getLatestAddress(bytes2 _module) public view returns(address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: nexusmutual-contracts/contracts/INXMMaster.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } // File: nexusmutual-contracts/contracts/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } // File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol pragma solidity ^0.5.7; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } // File: nexusmutual-contracts/contracts/TokenFunctions.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenFunctions is Iupgradable { using SafeMath for uint; MCR internal m1; MemberRoles internal mr; NXMToken public tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; PoolData internal pd; IPooledStaking pooledStaking; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev Rewards stakers on purchase of cover on smart contract. * @param _contractAddress smart contract address. * @param _coverPriceNXM cover price in NXM. */ function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal { uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100); pooledStaking.accumulateReward(_contractAddress, rewardValue); } /** * @dev Deprecated in favor of burnStakedTokens */ function burnStakerLockedToken(uint, bytes4, uint) external { // noop } /** * @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed. * @param coverId cover id * @param coverCurrency cover currency * @param sumAssured amount of $curr to burn */ function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal { (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = m1.calculateTokenPrice(coverCurrency); uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); } /** * @dev Gets the total staked NXM tokens against * Smart contract by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function deprecated_getTotalStakedTokensOnSmartContract( address _stakedContractAddress ) external view returns(uint) { uint stakedAmount = 0; address stakerAddress; uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress); for (uint i = 0; i < staketLen; i++) { stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i); uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress, _stakedContractAddress, stakerIndex); stakedAmount = stakedAmount.add(currentlyStaked); } return stakedAmount; } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) { return _getUserLockedCNTokens(_of, _coverId); } /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns(uint amount) { for (uint i = 0; i < qd.getUserCoverLength(_of); i++) { amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i])); } } /** * @dev Returns amount of NXM Tokens locked as Cover Note against given coverId. * @param _coverId coverId of the cover. */ function getLockedCNAgainstCover(uint _coverId) external view returns(uint) { return _getLockedCNAgainstCover(_coverId); } /** * @dev Returns total amount of staked NXM Tokens on all smart contracts. * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) { uint stakedAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i); stakedAmount = stakedAmount.add(currentlyStaked); } amount = stakedAmount; } /** * @dev Returns total unlockable amount of staked NXM Tokens on all smart contract . * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllUnlockableStakedTokens( address _stakerAddress ) external view returns (uint amount) { uint unlockableAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = unlockableAmount.add( _deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress, scIndex)); } amount = unlockableAmount; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /** * @dev Gets the Token price in a given currency * @param curr Currency name. * @return price Token Price. */ function getTokenPrice(bytes4 curr) public view returns(uint price) { price = m1.calculateTokenPrice(curr); } /** * @dev Set the flag to check if cover note is deposited against the cover id * @param coverId Cover Id. */ function depositCN(uint coverId) public onlyInternal returns (bool success) { require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available"); td.setDepositCN(coverId, true); success = true; } /** * @param _of address of Member * @param _coverId Cover Id * @param _lockTime Pending Time + Cover Period 7*1 days */ function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal { uint timeStamp = now.add(_lockTime); uint coverValidUntil = qd.getValidityOfCover(_coverId); if (timeStamp >= coverValidUntil) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); tc.extendLockOf(_of, reason, timeStamp); } } /** * @dev to burn the deposited cover tokens * @param coverId is id of cover whose tokens have to be burned * @return the status of the successful burning */ function burnDepositCN(uint coverId) public onlyInternal returns (bool success) { address _of = qd.getCoverMemberAddress(coverId); uint amount; (amount, ) = td.depositedCN(coverId); amount = (amount.mul(50)).div(100); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); tc.burnLockedTokens(_of, reason, amount); success = true; } /** * @dev Unlocks covernote locked against a given cover * @param coverId id of cover */ function unlockCN(uint coverId) public onlyInternal { (, bool isDeposited) = td.depositedCN(coverId); require(!isDeposited,"Cover note is deposited and can not be released"); uint lockedCN = _getLockedCNAgainstCover(coverId); if (lockedCN != 0) { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) public { require(ms.checkIsAuthToGoverned(msg.sender)); tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to lock cover note tokens * @param coverNoteAmount is number of tokens to be locked * @param coverPeriod is cover period in concern * @param coverId is the cover id of cover in concern * @param _of address whose tokens are to be locked */ function lockCN( uint coverNoteAmount, uint coverPeriod, uint coverId, address _of ) public onlyInternal { uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp()); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); td.setDepositCNAmount(coverId, coverNoteAmount); tc.lockOf(_of, reason, coverNoteAmount, validity); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns(bool) { return now < tk.isLockedForMV(_of); } /** * @dev Internal function to gets amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress, _stakedContractAddress, _stakedContractIndex); } /** * @dev Function to gets unlockable amount of locked NXM * tokens, staked against smartcontract by index * @param stakerAddress address of staker * @param stakedContractAddress staked contract address * @param stakerIndex index of staking */ function deprecated_getStakerUnlockableTokensOnSmartContract ( address stakerAddress, address stakedContractAddress, uint stakerIndex ) public view returns (uint) { return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress, td.getStakerStakedContractIndex(stakerAddress, stakerIndex)); } /** * @dev releases unlockable staked tokens to staker */ function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause { uint unlockableAmount; address scAddress; bytes32 reason; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract( _stakerAddress, scAddress, scIndex); td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0); td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount); reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex)); tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount); } } /** * @dev to get tokens of staker locked before burning that are allowed to burn * @param stakerAdd is the address of the staker * @param stakedAdd is the address of staked contract in concern * @param stakerIndex is the staker index in concern * @return amount of unlockable tokens * @return amount of tokens that can burn */ function _deprecated_unlockableBeforeBurningAndCanBurn( address stakerAdd, address stakedAdd, uint stakerIndex ) public view returns (uint amount, uint canBurn) { uint dateAdd; uint initialStake; uint totalBurnt; uint ub; (, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex); canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays()); // Can't use SafeMaths for int. int v = int(initialStake - (canBurn) - (totalBurnt) - ( td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub)); uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract( stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex)); if (v < 0) { v = 0; } amount = uint(v); if (canBurn > currentLockedTokens.sub(amount).sub(ub)) { canBurn = currentLockedTokens.sub(amount).sub(ub); } } /** * @dev to get tokens of staker that are unlockable * @param _stakerAddress is the address of the staker * @param _stakedContractAddress is the address of staked contract in concern * @param _stakedContractIndex is the staked contract index in concern * @return amount of unlockable tokens */ function _deprecated_getStakerUnlockableTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { uint initialStake; uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); uint burnt; (, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex); uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex); uint currentStakedTokens; (, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, _stakedContractAddress, stakerIndex); amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt); } /** * @dev Internal function to get the amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function _deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) internal view returns (uint amount) { bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); amount = tc.tokensLocked(_stakerAddress, reason); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _coverId coverId of the cover. */ function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) { address coverHolder = qd.getCoverMemberAddress(_coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId)); return tc.tokensLockedAtTime(coverHolder, reason, now); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); return tc.tokensLockedAtTime(_of, reason, now); } /** * @dev Internal function to gets remaining amount of staked NXM tokens, * against smartcontract by index * @param _stakeAmount address of user * @param _stakeDays staked contract address * @param _validDays index of staking */ function _deprecated_calculateStakedTokens( uint _stakeAmount, uint _stakeDays, uint _validDays ) internal pure returns (uint amount) { if (_validDays > _stakeDays) { uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays); amount = (rf.mul(_stakeAmount)).div(100000); } else { amount = 0; } } /** * @dev Gets the total staked NXM tokens against Smart contract * by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function _deprecated_burnStakerTokenLockedAgainstSmartContract( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _amount ) internal { uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount); bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); tc.burnLockedTokens(_stakerAddress, reason, _amount); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMemberRoles { event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public; /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(address _memberAddress, uint _roleId, bool _active) public; /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _authorized New authorized address against role id function changeAuthorized(uint _roleId, address _authorized) public; /// @dev Return number of member roles function totalRoles() public view returns(uint256); /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress); /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberAddress.length Member length function numberOfMembers(uint _memberRoleId) public view returns(uint); /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address); /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory assignedRoles); /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool); } // File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol pragma solidity 0.5.7; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: nexusmutual-contracts/contracts/TokenController.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } } // File: nexusmutual-contracts/contracts/ClaimsData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } // File: nexusmutual-contracts/contracts/PoolData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract DSValue { function peek() public view returns (bytes32, bool); function read() public view returns (bytes32); } contract PoolData is Iupgradable { using SafeMath for uint; struct ApiId { bytes4 typeOf; bytes4 currency; uint id; uint64 dateAdd; uint64 dateUpd; } struct CurrencyAssets { address currAddress; uint baseMin; uint varMin; } struct InvestmentAssets { address currAddress; bool status; uint64 minHoldingPercX100; uint64 maxHoldingPercX100; uint8 decimals; } struct IARankDetails { bytes4 maxIACurr; uint64 maxRate; bytes4 minIACurr; uint64 minRate; } struct McrData { uint mcrPercx100; uint mcrEther; uint vFull; //Pool funds uint64 date; } IARankDetails[] internal allIARankDetails; McrData[] public allMCRData; bytes4[] internal allInvestmentCurrencies; bytes4[] internal allCurrencies; bytes32[] public allAPIcall; mapping(bytes32 => ApiId) public allAPIid; mapping(uint64 => uint) internal datewiseId; mapping(bytes16 => uint) internal currencyLastIndex; mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets; mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets; mapping(bytes4 => uint) internal caAvgRate; mapping(bytes4 => uint) internal iaAvgRate; address public notariseMCR; address public daiFeedAddress; uint private constant DECIMAL1E18 = uint(10) ** 18; uint public uniswapDeadline; uint public liquidityTradeCallbackTime; uint public lastLiquidityTradeTrigger; uint64 internal lastDate; uint public variationPercX100; uint public iaRatesTime; uint public minCap; uint public mcrTime; uint public a; uint public shockParameter; uint public c; uint public mcrFailTime; uint public ethVolumeLimit; uint public capReached; uint public capacityLimit; constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public { notariseMCR = _notariseAdd; daiFeedAddress = _daiFeedAdd; c = 5800000; a = 1028; mcrTime = 24 hours; mcrFailTime = 6 hours; allMCRData.push(McrData(0, 0, 0, 0)); minCap = 12000 * DECIMAL1E18; shockParameter = 50; variationPercX100 = 100; //1% iaRatesTime = 24 hours; //24 hours in seconds uniswapDeadline = 20 minutes; liquidityTradeCallbackTime = 4 hours; ethVolumeLimit = 4; capacityLimit = 10; allCurrencies.push("ETH"); allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0); allCurrencies.push("DAI"); allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0); allInvestmentCurrencies.push("ETH"); allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18); allInvestmentCurrencies.push("DAI"); allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18); } /** * @dev to set the maximum cap allowed * @param val is the new value */ function setCapReached(uint val) external onlyInternal { capReached = val; } /// @dev Updates the 3 day average rate of a IA currency. /// To be replaced by MakerDao's on chain rates /// @param curr IA Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal { iaAvgRate[curr] = rate; } /// @dev Updates the 3 day average rate of a CA currency. /// To be replaced by MakerDao's on chain rates /// @param curr Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal { caAvgRate[curr] = rate; } /// @dev Adds details of (Minimum Capital Requirement)MCR. /// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456) /// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model. function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal { allMCRData.push(McrData(mcrp, mcre, vf, time)); } /** * @dev Updates the Timestamp at which result of oracalize call is received. */ function updateDateUpdOfAPI(bytes32 myid) external onlyInternal { allAPIid[myid].dateUpd = uint64(now); } /** * @dev Saves the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal,quote,cover etc. for which oraclize call is made */ function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal { allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now)); } /** * @dev Stores the id return by the oraclize query. * Maintains record of all the Ids return by oraclize query. * @param myid Id return by the oraclize query. */ function addInAllApiCall(bytes32 myid) external onlyInternal { allAPIcall.push(myid); } /** * @dev Saves investment asset rank details. * @param maxIACurr Maximum ranked investment asset currency. * @param maxRate Maximum ranked investment asset rate. * @param minIACurr Minimum ranked investment asset currency. * @param minRate Minimum ranked investment asset rate. * @param date in yyyymmdd. */ function saveIARankDetails( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate, uint64 date ) external onlyInternal { allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate)); datewiseId[date] = allIARankDetails.length.sub(1); } /** * @dev to get the time for the laste liquidity trade trigger */ function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; } /** * @dev Updates Last Date. */ function updatelastDate(uint64 newDate) external onlyInternal { lastDate = newDate; } /** * @dev Adds currency asset currency. * @param curr currency of the asset * @param currAddress address of the currency * @param baseMin base minimum in 10^18. */ function addCurrencyAssetCurrency( bytes4 curr, address currAddress, uint baseMin ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencies.push(curr); allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0); } /** * @dev Adds investment asset. */ function addInvestmentAssetCurrency( bytes4 curr, address currAddress, bool status, uint64 minHoldingPercX100, uint64 maxHoldingPercX100, uint8 decimals ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentCurrencies.push(curr); allInvestmentAssets[curr] = InvestmentAssets(currAddress, status, minHoldingPercX100, maxHoldingPercX100, decimals); } /** * @dev Changes base minimum of a given currency asset. */ function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].baseMin = baseMin; } /** * @dev changes variable minimum of a given currency asset. */ function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal { allCurrencyAssets[curr].varMin = varMin; } /** * @dev Changes the investment asset status. */ function changeInvestmentAssetStatus(bytes4 curr, bool status) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].status = status; } /** * @dev Changes the investment asset Holding percentage of a given currency. */ function changeInvestmentAssetHoldingPerc( bytes4 curr, uint64 minPercX100, uint64 maxPercX100 ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].minHoldingPercX100 = minPercX100; allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100; } /** * @dev Gets Currency asset token address. */ function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].currAddress = currAdd; } /** * @dev Changes Investment asset token address. */ function changeInvestmentAssetAddressAndDecimal( bytes4 curr, address currAdd, uint8 newDecimal ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].currAddress = currAdd; allInvestmentAssets[curr].decimals = newDecimal; } /// @dev Changes address allowed to post MCR. function changeNotariseAddress(address _add) external onlyInternal { notariseMCR = _add; } /// @dev updates daiFeedAddress address. /// @param _add address of DAI feed. function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "MCRTIM") { val = mcrTime / (1 hours); } else if (code == "MCRFTIM") { val = mcrFailTime / (1 hours); } else if (code == "MCRMIN") { val = minCap; } else if (code == "MCRSHOCK") { val = shockParameter; } else if (code == "MCRCAPL") { val = capacityLimit; } else if (code == "IMZ") { val = variationPercX100; } else if (code == "IMRATET") { val = iaRatesTime / (1 hours); } else if (code == "IMUNIDL") { val = uniswapDeadline / (1 minutes); } else if (code == "IMLIQT") { val = liquidityTradeCallbackTime / (1 hours); } else if (code == "IMETHVL") { val = ethVolumeLimit; } else if (code == "C") { val = c; } else if (code == "A") { val = a; } } /// @dev Checks whether a given address can notaise MCR data or not. /// @param _add Address. /// @return res Returns 0 if address is not authorized, else 1. function isnotarise(address _add) external view returns(bool res) { res = false; if (_add == notariseMCR) res = true; } /// @dev Gets the details of last added MCR. /// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100). /// @return vFull Total Pool fund value in Ether used in the last full daily calculation. function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) { uint index = allMCRData.length.sub(1); return ( allMCRData[index].mcrPercx100, allMCRData[index].mcrEther, allMCRData[index].vFull, allMCRData[index].date ); } /// @dev Gets last Minimum Capital Requirement percentage of Capital Model /// @return val MCR% value,multiplied by 100. function getLastMCRPerc() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrPercx100; } /// @dev Gets last Ether price of Capital Model /// @return val ether value,multiplied by 100. function getLastMCREther() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrEther; } /// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model. function getLastVfull() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].vFull; } /// @dev Gets last Minimum Capital Requirement in Ether. /// @return date of MCR. function getLastMCRDate() external view returns(uint64 date) { date = allMCRData[allMCRData.length.sub(1)].date; } /// @dev Gets details for token price calculation. function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) { _a = a; _c = c; rate = _getAvgRate(curr, false); } /// @dev Gets the total number of times MCR calculation has been made. function getMCRDataLength() external view returns(uint len) { len = allMCRData.length; } /** * @dev Gets investment asset rank details by given date. */ function getIARankDetailsByDate( uint64 date ) external view returns( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate ) { uint index = datewiseId[date]; return ( allIARankDetails[index].maxIACurr, allIARankDetails[index].maxRate, allIARankDetails[index].minIACurr, allIARankDetails[index].minRate ); } /** * @dev Gets Last Date. */ function getLastDate() external view returns(uint64 date) { return lastDate; } /** * @dev Gets investment currency for a given index. */ function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) { return allInvestmentCurrencies[index]; } /** * @dev Gets count of investment currency. */ function getInvestmentCurrencyLen() external view returns(uint len) { return allInvestmentCurrencies.length; } /** * @dev Gets all the investment currencies. */ function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) { return allInvestmentCurrencies; } /** * @dev Gets All currency for a given index. */ function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) { return allCurrencies[index]; } /** * @dev Gets count of All currency. */ function getAllCurrenciesLen() external view returns(uint len) { return allCurrencies.length; } /** * @dev Gets all currencies */ function getAllCurrencies() external view returns(bytes4[] memory currencies) { return allCurrencies; } /** * @dev Gets currency asset details for a given currency. */ function getCurrencyAssetVarBase( bytes4 curr ) external view returns( bytes4 currency, uint baseMin, uint varMin ) { return ( curr, allCurrencyAssets[curr].baseMin, allCurrencyAssets[curr].varMin ); } /** * @dev Gets minimum variable value for currency asset. */ function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) { return allCurrencyAssets[curr].varMin; } /** * @dev Gets base minimum of a given currency asset. */ function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) { return allCurrencyAssets[curr].baseMin; } /** * @dev Gets investment asset maximum and minimum holding percentage of a given currency. */ function getInvestmentAssetHoldingPerc( bytes4 curr ) external view returns( uint64 minHoldingPercX100, uint64 maxHoldingPercX100 ) { return ( allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100 ); } /** * @dev Gets investment asset decimals. */ function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) { return allInvestmentAssets[curr].decimals; } /** * @dev Gets investment asset maximum holding percentage of a given currency. */ function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) { return allInvestmentAssets[curr].maxHoldingPercX100; } /** * @dev Gets investment asset minimum holding percentage of a given currency. */ function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) { return allInvestmentAssets[curr].minHoldingPercX100; } /** * @dev Gets investment asset details of a given currency */ function getInvestmentAssetDetails( bytes4 curr ) external view returns( bytes4 currency, address currAddress, bool status, uint64 minHoldingPerc, uint64 maxHoldingPerc, uint8 decimals ) { return ( curr, allInvestmentAssets[curr].currAddress, allInvestmentAssets[curr].status, allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100, allInvestmentAssets[curr].decimals ); } /** * @dev Gets Currency asset token address. */ function getCurrencyAssetAddress(bytes4 curr) external view returns(address) { return allCurrencyAssets[curr].currAddress; } /** * @dev Gets investment asset token address. */ function getInvestmentAssetAddress(bytes4 curr) external view returns(address) { return allInvestmentAssets[curr].currAddress; } /** * @dev Gets investment asset active Status of a given currency. */ function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; } /** * @dev Gets type of oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return _typeof It could be of type "quote","quotation","cover","claim" etc. */ function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].typeOf; } /** * @dev Gets ID associated to oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return id1 It could be the ID of "proposal","quotation","cover","claim" etc. */ function getIdOfApiId(bytes32 myid) external view returns(uint) { return allAPIid[myid].id; } /** * @dev Gets the Timestamp of a oracalize call. */ function getDateAddOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateAdd; } /** * @dev Gets the Timestamp at which result of oracalize call is received. */ function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateUpd; } /** * @dev Gets currency by oracalize id. */ function getCurrOfApiId(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].currency; } /** * @dev Gets ID return by the oraclize query of a given index. * @param index Index. * @return myid ID return by the oraclize query. */ function getApiCallIndex(uint index) external view returns(bytes32 myid) { myid = allAPIcall[index]; } /** * @dev Gets Length of API call. */ function getApilCallLength() external view returns(uint) { return allAPIcall.length; } /** * @dev Get Details of Oraclize API when given Oraclize Id. * @param myid ID return by the oraclize query. * @return _typeof ype of the query for which oraclize * call is made.("proposal","quote","quotation" etc.) */ function getApiCallDetails( bytes32 myid ) external view returns( bytes4 _typeof, bytes4 curr, uint id, uint64 dateAdd, uint64 dateUpd ) { return ( allAPIid[myid].typeOf, allAPIid[myid].currency, allAPIid[myid].id, allAPIid[myid].dateAdd, allAPIid[myid].dateUpd ); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MCRTIM") { _changeMCRTime(val * 1 hours); } else if (code == "MCRFTIM") { _changeMCRFailTime(val * 1 hours); } else if (code == "MCRMIN") { _changeMinCap(val); } else if (code == "MCRSHOCK") { _changeShockParameter(val); } else if (code == "MCRCAPL") { _changeCapacityLimit(val); } else if (code == "IMZ") { _changeVariationPercX100(val); } else if (code == "IMRATET") { _changeIARatesTime(val * 1 hours); } else if (code == "IMUNIDL") { _changeUniswapDeadlineTime(val * 1 minutes); } else if (code == "IMLIQT") { _changeliquidityTradeCallbackTime(val * 1 hours); } else if (code == "IMETHVL") { _setEthVolumeLimit(val); } else if (code == "C") { _changeC(val); } else if (code == "A") { _changeA(val); } else { revert("Invalid param code"); } } /** * @dev to get the average rate of currency rate * @param curr is the currency in concern * @return required rate */ function getCAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, false); } /** * @dev to get the average rate of investment rate * @param curr is the investment in concern * @return required rate */ function getIAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, true); } function changeDependentContractAddress() public onlyInternal {} /// @dev Gets the average rate of a CA currency. /// @param curr Currency Name. /// @return rate Average rate X 100(of last 3 days). function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) { if (curr == "DAI") { DSValue ds = DSValue(daiFeedAddress); rate = uint(ds.read()).div(uint(10) ** 16); } else if (isIA) { rate = iaAvgRate[curr]; } else { rate = caAvgRate[curr]; } } /** * @dev to set the ethereum volume limit * @param val is the new limit value */ function _setEthVolumeLimit(uint val) internal { ethVolumeLimit = val; } /// @dev Sets minimum Cap. function _changeMinCap(uint newCap) internal { minCap = newCap; } /// @dev Sets Shock Parameter. function _changeShockParameter(uint newParam) internal { shockParameter = newParam; } /// @dev Changes time period for obtaining new MCR data from external oracle query. function _changeMCRTime(uint _time) internal { mcrTime = _time; } /// @dev Sets MCR Fail time. function _changeMCRFailTime(uint _time) internal { mcrFailTime = _time; } /** * @dev to change the uniswap deadline time * @param newDeadline is the value */ function _changeUniswapDeadlineTime(uint newDeadline) internal { uniswapDeadline = newDeadline; } /** * @dev to change the liquidity trade call back time * @param newTime is the new value to be set */ function _changeliquidityTradeCallbackTime(uint newTime) internal { liquidityTradeCallbackTime = newTime; } /** * @dev Changes time after which investment asset rates need to be fed. */ function _changeIARatesTime(uint _newTime) internal { iaRatesTime = _newTime; } /** * @dev Changes the variation range percentage. */ function _changeVariationPercX100(uint newPercX100) internal { variationPercX100 = newPercX100; } /// @dev Changes Growth Step function _changeC(uint newC) internal { c = newC; } /// @dev Changes scaling factor. function _changeA(uint val) internal { a = val; } /** * @dev to change the capacity limit * @param val is the new value */ function _changeCapacityLimit(uint val) internal { capacityLimit = val; } } // File: nexusmutual-contracts/contracts/QuotationData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover } enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested } struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns(uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns(address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns(uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns(uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns(uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns(uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns(uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns(uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns(address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } // File: nexusmutual-contracts/contracts/TokenData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public { //solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns(uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns(uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns(bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } // File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 _myid, string memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(0, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(_timestamp, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ // File: nexusmutual-contracts/contracts/Quotation.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Quotation is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; TokenController internal tc; TokenData internal td; Pool1 internal p1; PoolData internal pd; QuotationData internal qd; MCR internal m1; MemberRoles internal mr; bool internal locked; event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); mr = MemberRoles(ms.getLatestAddress("MR")); } function sendEther() public payable { } /** * @dev Expires a cover after a set period of time. * Changes the status of the Cover and reduces the current * sum assured of all areas in which the quotation lies * Unlocks the CN tokens of the cover. Updates the Total Sum Assured value. * @param _cid Cover Id. */ function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); } /** * @dev Checks if a cover should get expired/closed or not. * @param _cid Cover Index. * @return expire true if the Cover's time has expired, false otherwise. */ function checkCoverExpired(uint _cid) public view returns(bool expire) { expire = qd.getValidityOfCover(_cid) < uint64(now); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal { _removeSAFromCSA(_cid, _amount); } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] memory coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) public isMemberAndcheckPause { tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev to get the status of recently holded coverID * @param userAdd is the user address in concern * @return the status of the concerned coverId */ function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } } /** * @dev to initiate the membership and the cover * @param smartCAdd is the smart contract address to make cover on * @param coverCurr is the currency used to make cover * @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM * @param coverPeriod is cover period for which cover is being bought * @param _v argument from vrs hash * @param _r argument from vrs hash * @param _s argument from vrs hash */ function initiateMembershipAndCover( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable checkPause { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(!ms.isMember(msg.sender)); require(qd.refundEligible(msg.sender) == false); uint joinFee = td.joiningFee(); uint totalFee = joinFee; if (coverCurr == "ETH") { totalFee = joinFee.add(coverDetails[1]); } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1])); } require(msg.value == totalFee); require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s)); qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod); qd.setRefundEligible(msg.sender, true); } /** * @dev to get the verdict of kyc process * @param status is the kyc status * @param _add is the address of member */ function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); } /** * @dev transfering Ethers to newly created quotation contract. */ function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy { uint amount = address(this).balance; IERC20 erc20; if (amount > 0) { // newAdd.transfer(amount); Quotation newQT = Quotation(newAdd); newQT.sendEther.value(amount)(); } uint currAssetLen = pd.getAllCurrenciesLen(); for (uint64 i = 1; i < currAssetLen; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); address currAddr = pd.getCurrencyAssetAddress(currName); erc20 = IERC20(currAddr); //solhint-disable-line if (erc20.balanceOf(address(this)) > 0) { require(erc20.transfer(newAdd, erc20.balanceOf(address(this)))); } } } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover ( //solhint-disable-line address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod ) internal { uint cid = qd.getCoverLength(); qd.addCover(coverPeriod, coverDetails[0], from, coverCurr, scAddress, coverDetails[1], coverDetails[2]); // if cover period of quote is less than 60 days. if (coverPeriod <= 60) { p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days))); } uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100); tc.mint(from, coverNoteAmount); tf.lockCN(coverNoteAmount, coverPeriod, cid, from); qd.addInTotalSumAssured(coverCurr, coverDetails[0]); qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]); tf.pushStakerRewards(scAddress, coverDetails[2]); } /** * @dev Makes a vover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) internal { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s)); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause { address _add; bytes4 coverCurr; (, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid); qd.subFromTotalSumAssured(coverCurr, _amount); qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount); } /** * @dev to trigger the kyc process * @param status is the kyc status * @param _add is the address of member */ function _kycTrigger(bool status, address _add) internal { uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1); uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen); address payable userAdd; address scAddress; bytes4 coverCurr; uint16 coverPeriod; uint[] memory coverDetails = new uint[](4); IERC20 erc20; (, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID); (, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID); require(qd.refundEligible(userAdd)); qd.setRefundEligible(userAdd, false); require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending)); uint joinFee = td.joiningFee(); if (status) { mr.payJoiningFee.value(joinFee)(userAdd); if (coverDetails[3] > now) { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass)); address poolAdd = ms.getLatestAddress("P1"); if (coverCurr == "ETH") { p1.sendEther.value(coverDetails[1])(); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(poolAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed"); _makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod); } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover)); if (coverCurr == "ETH") { userAdd.transfer(coverDetails[1]); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed"); } } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); uint totalRefund = joinFee; if (coverCurr == "ETH") { totalRefund = coverDetails[1].add(joinFee); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } userAdd.transfer(totalRefund); emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed"); } } } // File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol pragma solidity 0.5.7; contract Factory { function getExchange(address token) public view returns (address); function getToken(address exchange) public view returns (address); } contract Exchange { function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256); function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256); function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient) public payable returns (uint256); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) public payable returns (uint256); function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient) public payable returns (uint256); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddress ) public returns (uint256); function tokenToTokenTransferInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, address tokenAddress ) public returns (uint256); } // File: nexusmutual-contracts/contracts/Pool2.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool2 is Iupgradable { using SafeMath for uint; MCR internal m1; Pool1 internal p1; PoolData internal pd; Factory internal factory; address public uniswapFactoryAddress; uint internal constant DECIMAL1E18 = uint(10) ** 18; bool internal locked; constructor(address _uniswapFactoryAdd) public { uniswapFactoryAddress = _uniswapFactoryAdd; factory = Factory(_uniswapFactoryAdd); } function() external payable {} event Liquidity(bytes16 typeOf, bytes16 functionName); event Rebalancing(bytes4 iaCurr, uint tokenAmount); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev to change the uniswap factory address * @param newFactoryAddress is the new factory address in concern * @return the status of the concerned coverId */ function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal { // require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender)); uniswapFactoryAddress = newFactoryAddress; factory = Factory(uniswapFactoryAddress); } /** * @dev On upgrade transfer all investment assets and ether to new Investment Pool * @param newPoolAddress New Investment Assest Pool address */ function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy { uint len = pd.getInvestmentCurrencyLen(); for (uint64 i = 1; i < len; i++) { bytes4 iaName = pd.getInvestmentCurrencyByIndex(i); _upgradeInvestmentPool(iaName, newPoolAddress); } if (address(this).balance > 0) { Pool2 newP2 = Pool2(newPoolAddress); newP2.sendEther.value(address(this).balance)(); } } /** * @dev Internal Swap of assets between Capital * and Investment Sub pool for excess or insufficient * liquidity conditions of a given currency. */ function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy { uint caBalance; uint baseMin; uint varMin; (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { _internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance); } else if (caBalance < uint(baseMin).add(varMin)) { _internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance); } } /** * @dev Saves a given investment asset details. To be called daily. * @param curr array of Investment asset name. * @param rate array of investment asset exchange rate. * @param date current date in yyyymmdd. */ function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit) external checkPause noReentrancy { bytes4 maxCurr; bytes4 minCurr; uint64 maxRate; uint64 minRate; //ONLY NOTARZIE ADDRESS CAN POST require(pd.isnotarise(msg.sender)); (maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate); pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date); pd.updatelastDate(date); uint len = curr.length; for (uint i = 0; i < len; i++) { pd.updateIAAvgRate(curr[i], rate[i]); } if (bit) //for testing purpose _rebalancingLiquidityTrading(maxCurr, maxRate); p1.saveIADetailsOracalise(pd.iaRatesTime()); } /** * @dev External Trade for excess or insufficient * liquidity conditions of a given currency. */ function externalLiquidityTrade() external onlyInternal { bool triggerTrade; bytes4 curr; bytes4 minIACurr; bytes4 maxIACurr; uint amount; uint minIARate; uint maxIARate; uint baseMin; uint varMin; uint caBalance; (maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate()); uint len = pd.getAllCurrenciesLen(); for (uint64 i = 0; i < len; i++) { curr = pd.getCurrenciesByIndex(i); (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18; triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount); } else if (caBalance < uint(baseMin).add(varMin)) { // insufficient amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance); triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount); } if (triggerTrade) { p1.triggerExternalLiquidityTrade(); } } } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); pd = PoolData(ms.getLatestAddress("PD")); p1 = Pool1(ms.getLatestAddress("P1")); } function sendEther() public payable { } /** * @dev Gets currency asset balance for a given currency name. */ function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) { if (_curr == "ETH") { caBalance = address(p1).balance; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); caBalance = erc20.balanceOf(address(p1)); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _transferInvestmentAsset( bytes4 _curr, address _transferTo, uint _amount ) internal { if (_curr == "ETH") { if (_amount > address(this).balance) _amount = address(this).balance; p1.sendEther.value(_amount)(); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (_amount > erc20.balanceOf(address(this))) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(_transferTo, _amount)); } } /** * @dev to perform rebalancing * @param iaCurr is the investment asset currency * @param iaRate is the investment asset rate */ function _rebalancingLiquidityTrading( bytes4 iaCurr, uint64 iaRate ) internal checkPause { uint amountToSell; uint totalRiskBal = pd.getLastVfull(); uint intermediaryEth; uint ethVol = pd.ethVolumeLimit(); totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18); Exchange exchange; if (totalRiskBal > 0) { amountToSell = ((totalRiskBal.mul(2).mul( iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000); amountToSell = (amountToSell.mul( 10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr))); intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000); } IERC20 erc20; erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr)); erc20.approve(address(exchange), amountToSell); exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice( amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { _transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell); } emit Rebalancing(iaCurr, amountToSell); } } /** * @dev Checks whether trading is required for a * given investment asset at a given exchange rate. */ function _checkTradeConditions( bytes4 curr, uint64 iaRate, uint totalRiskBal ) internal view returns(bool check) { if (iaRate > 0) { uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18); if (iaBalance > 0 && totalRiskBal > 0) { uint iaMax; uint iaMin; uint checkNumber; uint z; (iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr); z = pd.variationPercX100(); checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate)); if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) || (checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100))) check = true; //eligibleIA } } } /** * @dev Gets the investment asset rank. */ function _getIARank( bytes4 curr, uint64 rateX100, uint totalRiskPoolBalance ) internal view returns (int rhsh, int rhsl) //internal function { uint currentIAmaxHolding; uint currentIAminHolding; uint iaBalance = _getInvestmentAssetBalance(curr); (currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr); if (rateX100 > 0) { uint rhsf; rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100)); rhsh = int(rhsf - currentIAmaxHolding); rhsl = int(rhsf - currentIAminHolding); } } /** * @dev Calculates the investment asset rank. */ function _calculateIARank( bytes4[] memory curr, uint64[] memory rate ) internal view returns( bytes4 maxCurr, uint64 maxRate, bytes4 minCurr, uint64 minRate ) { int max = 0; int min = -1; int rhsh; int rhsl; uint totalRiskPoolBalance; (totalRiskPoolBalance, ) = m1.calVtpAndMCRtp(); uint len = curr.length; for (uint i = 0; i < len; i++) { rhsl = 0; rhsh = 0; if (pd.getInvestmentAssetStatus(curr[i])) { (rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance); if (rhsh > max || i == 0) { max = rhsh; maxCurr = curr[i]; maxRate = rate[i]; } if (rhsl < min || rhsl == 0 || i == 0) { min = rhsl; minCurr = curr[i]; minRate = rate[i]; } } } } /** * @dev to get balance of an investment asset * @param _curr is the investment asset in concern * @return the balance */ function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) { if (_curr == "ETH") { balance = address(this).balance; } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); balance = erc20.balanceOf(address(this)); } } /** * @dev Creates Excess liquidity trading order for a given currency and a given balance. */ function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { // require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender)); bytes4 minIACurr; // uint amount; (, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == minIACurr) { // amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18; p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2))); } else { p1.triggerExternalLiquidityTrade(); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. */ function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { bytes4 maxIACurr; uint amount; (maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == maxIACurr) { amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance); _transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); if ((maxIACurr == "ETH" && address(this).balance > 0) || (maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0)) p1.triggerExternalLiquidityTrade(); } } /** * @dev Creates External excess liquidity trading * order for a given currency and a given balance. * @param curr Currency Asset to Sell * @param minIACurr Investment Asset to Buy * @param amount Amount of Currency Asset to Sell */ function _externalExcessLiquiditySwap( bytes4 curr, bytes4 minIACurr, uint256 amount ) internal returns (bool trigger) { uint intermediaryEth; Exchange exchange; IERC20 erc20; uint ethVol = pd.ethVolumeLimit(); if (curr == minIACurr) { p1.transferCurrencyAsset(curr, amount); } else if (curr == "ETH" && minIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr))); if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit amount = (address(exchange).balance.mul(ethVol)).div(100); trigger = true; } p1.transferCurrencyAsset(curr, amount); exchange.ethToTokenSwapInput.value(amount) (exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now)); } else if (curr != "ETH" && minIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getTokenToEthInputPrice(amount); trigger = true; } p1.transferCurrencyAsset(curr, amount); // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } Exchange tmp = Exchange(factory.getExchange( pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) { intermediaryEth = address(tmp).balance.mul(ethVol).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } p1.transferCurrencyAsset(curr, amount); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); erc20.approve(address(exchange), amount); exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr)); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. * @param curr Currency Asset to buy * @param maxIACurr Investment Asset to sell * @param amount Amount of Investment Asset to sell */ function _externalInsufficientLiquiditySwap( bytes4 curr, bytes4 maxIACurr, uint256 amount ) internal returns (bool trigger) { Exchange exchange; IERC20 erc20; uint intermediaryEth; // uint ethVol = pd.ethVolumeLimit(); if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); intermediaryEth = exchange.getEthToTokenInputPrice(amount); if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getEthToTokenInputPrice(amount); trigger = true; } erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr)); if (intermediaryEth > erc20.balanceOf(address(this))) { intermediaryEth = erc20.balanceOf(address(this)); } // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), intermediaryEth); exchange.tokenToEthTransferInput(intermediaryEth, ( exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else if (curr != "ETH" && maxIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > address(this).balance) intermediaryEth = address(this).balance; if (intermediaryEth > (address(exchange).balance.mul (pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else { address currAdd = pd.getCurrencyAssetAddress(curr); exchange = Exchange(factory.getExchange(currAdd)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) { intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth); erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); uint maxIABal = erc20.balanceOf(address(this)); if (maxIAToSell > maxIABal) { maxIAToSell = maxIABal; intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); } amount = exchange.getEthToTokenInputPrice(intermediaryEth); erc20.approve(address(tmp), maxIAToSell); tmp.tokenToTokenTransferInput(maxIAToSell, ( amount.mul(995)).div(1000), ( intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _upgradeInvestmentPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } } // File: nexusmutual-contracts/contracts/Pool1.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool1 is usingOraclize, Iupgradable { using SafeMath for uint; Quotation internal q2; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "ETH" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat( "http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 caName = pd.getCurrenciesByIndex(i); _upgradeCapitalPool(caName, newPoolAddress); } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = NXMToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase NXM at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); success = true; } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000); _saveApiDetails(myid, "ULT", 0); } } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param _amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "ETH") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } /** * @dev oraclize query * @param paramCount is number of paramters passed * @param timestamp is the current timestamp * @param datasource in concern * @param arg in concern * @param gasLimit required for query * @return id of oraclize query */ function _oraclizeQuery( uint paramCount, uint timestamp, string memory datasource, string memory arg, uint gasLimit ) internal returns (bytes32 id) { if (paramCount == 4) { id = oraclize_query(timestamp, datasource, arg, gasLimit); } else if (paramCount == 3) { id = oraclize_query(timestamp, datasource, arg); } else { id = oraclize_query(datasource, arg); } } } // File: nexusmutual-contracts/contracts/MCR.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MCR is Iupgradable { using SafeMath for uint; Pool1 internal p1; PoolData internal pd; NXMToken internal tk; QuotationData internal qd; MemberRoles internal mr; TokenData internal td; ProposalCategory internal proposalCategory; uint private constant DECIMAL1E18 = uint(10) ** 18; uint private constant DECIMAL1E05 = uint(10) ** 5; uint private constant DECIMAL1E19 = uint(10) ** 19; uint private constant minCapFactor = uint(10) ** 21; uint public variableMincap; uint public dynamicMincapThresholdx100 = 13000; uint public dynamicMincapIncrementx100 = 100; event MCREvent( uint indexed date, uint blockNumber, bytes4[] allCurr, uint[] allCurrRates, uint mcrEtherx100, uint mcrPercx100, uint vFull ); /** * @dev Adds new MCR data. * @param mcrP Minimum Capital Requirement in percentage. * @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model. * @param onlyDate Date(yyyymmdd) at which MCR details are getting added. */ function addMCRData( uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate ) external checkPause { require(proposalCategory.constructorCheck()); require(pd.isnotarise(msg.sender)); if (mr.launched() && pd.capReached() != 1) { if (mcrP >= 10000) pd.setCapReached(1); } uint len = pd.getMCRDataLength(); _addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg); } /** * @dev Adds MCR Data for last failed attempt. */ function addLastMCRData(uint64 date) external checkPause onlyInternal { uint64 lastdate = uint64(pd.getLastMCRDate()); uint64 failedDate = uint64(date); if (failedDate >= lastdate) { uint mcrP; uint mcrE; uint vF; (mcrP, mcrE, vF, ) = pd.getLastMCR(); uint len = pd.getAllCurrenciesLen(); pd.pushMCRData(mcrP, mcrE, vF, date); for (uint j = 0; j < len; j++) { bytes4 currName = pd.getCurrenciesByIndex(j); pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName)); } emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF); // Oraclize call for next MCR calculation _callOracliseForMCR(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); tk = NXMToken(ms.tokenAddress()); mr = MemberRoles(ms.getLatestAddress("MR")); td = TokenData(ms.getLatestAddress("TD")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Gets total sum assured(in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns(uint amount) { uint len = pd.getAllCurrenciesLen(); for (uint i = 0; i < len; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); if (currName == "ETH") { amount = amount.add(qd.getTotalSumAssured(currName)); } else { if (pd.getCAAvgRate(currName) > 0) amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName))); } } } /** * @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether * and MCR% used in the Token Price Calculation. * @return vtp Pool Fund Value in Ether used for the Token Price Model * @return mcrtp MCR% used in the Token Price Model. */ function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { vtp = 0; IERC20 erc20; uint currTokens = 0; uint i; for (i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 currency = pd.getCurrenciesByIndex(i); erc20 = IERC20(pd.getCurrencyAssetAddress(currency)); currTokens = erc20.balanceOf(address(p1)); if (pd.getCAAvgRate(currency) > 0) vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency))); } vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance()); uint mcrFullperc; uint vFull; (mcrFullperc, , vFull, ) = pd.getLastMCR(); if (vFull > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); } } /** * @dev Calculates the Token Price of NXM in a given currency. * @param curr Currency name. */ function calculateStepTokenPrice( bytes4 curr, uint mcrtp ) public view onlyInternal returns(uint tokenPrice) { return _calculateTokenPrice(curr, mcrtp); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param curr Currency name. */ function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) { uint mcrtp; (, mcrtp) = _calVtpAndMCRtp(address(p1).balance); return _calculateTokenPrice(curr, mcrtp); } function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(address(p1).balance); } function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(poolBalance); } function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold) { minCap = (minCap.mul(minCapFactor)).add(variableMincap); uint lower = 0; if (vtp >= vF) { upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap } else { upperThreshold = vF.mul(120).mul(100).div((minCap)); } if (vtp > 0) { lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100); if(lower < minCap.mul(11).div(10)) lower = minCap.mul(11).div(10); } if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100 lowerThreshold = vtp.mul(100).mul(100).div(lower); } } /** * @dev Gets max numbers of tokens that can be sold at the moment. */ function getMaxSellTokens() public view returns(uint maxTokens) { uint baseMin = pd.getCurrencyAssetBaseMin("ETH"); uint maxTokensAccPoolBal; if (address(p1).balance > baseMin.mul(50).div(100)) { maxTokensAccPoolBal = address(p1).balance.sub( (baseMin.mul(50)).div(100)); } maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div( (calculateTokenPrice("ETH").mul(975)).div(1000)); uint lastMCRPerc = pd.getLastMCRPerc(); if (lastMCRPerc > 10000) maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000); if (maxTokens > maxTokensAccPoolBal) maxTokens = maxTokensAccPoolBal; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "DMCT") { val = dynamicMincapThresholdx100; } else if (code == "DMCI") { val = dynamicMincapIncrementx100; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { dynamicMincapThresholdx100 = val; } else if (code == "DMCI") { dynamicMincapIncrementx100 = val; } else { revert("Invalid param code"); } } /** * @dev Calls oraclize query to calculate MCR details after 24 hours. */ function _callOracliseForMCR() internal { p1.mcrOraclise(pd.mcrTime()); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param _curr Currency name. * @return tokenPrice Token price. */ function _calculateTokenPrice( bytes4 _curr, uint mcrtp ) internal view returns(uint tokenPrice) { uint getA; uint getC; uint getCAAvgRate; uint tokenExponentValue = td.tokenExponent(); // uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp)); uint max = mcrtp ** tokenExponentValue; uint dividingFactor = tokenExponentValue.mul(4); (getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr); uint mcrEth = pd.getLastMCREther(); getC = getC.mul(DECIMAL1E18); tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor); tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05)); tokenPrice = tokenPrice.mul(getCAAvgRate * 10); tokenPrice = (tokenPrice).div(10**3); } /** * @dev Adds MCR Data. Checks if MCR is within valid * thresholds in order to rule out any incorrect calculations */ function _addMCRData( uint len, uint64 newMCRDate, bytes4[] memory curr, uint mcrE, uint mcrP, uint vF, uint[] memory _threeDayAvg ) internal { uint vtp = 0; uint lowerThreshold = 0; uint upperThreshold = 0; if (len > 1) { (vtp, ) = _calVtpAndMCRtp(address(p1).balance); (lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap()); } if(mcrP > dynamicMincapThresholdx100) variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000); // Explanation for above formula :- // actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100 // Implemented formula is simplified form of actual formula. // Let consider above formula as b = b + (a+b)*c/100 // here, dynamicMincapIncrement is in x100 format. // so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000. // It can further simplify to (b.(10000+cx100) + a.cx100)/10000. if (len == 1 || (mcrP) >= lowerThreshold && (mcrP) <= upperThreshold) { vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable pd.pushMCRData(mcrP, mcrE, vF, newMCRDate); for (uint i = 0; i < curr.length; i++) { pd.updateCAAvgRate(curr[i], _threeDayAvg[i]); } emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF); // Oraclize call for next MCR calculation if (vtp < newMCRDate) { _callOracliseForMCR(); } } else { p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime()); } } } // File: nexusmutual-contracts/contracts/Claims.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Claims is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; NXMToken internal tk; TokenController internal tc; ClaimsReward internal cr; Pool1 internal p1; ClaimsData internal cd; TokenData internal td; PoolData internal pd; Pool2 internal p2; QuotationData internal qd; MCR internal m1; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Gets claim details of claim id = pending claim start + given index */ function getClaimFromNewStart( uint index ) external view returns ( uint coverId, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { (coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender); // status = rewardStatus[statusnumber].claimStatusDesc; } /** * @dev Gets details of a claim submitted by the calling user, at a given index */ function getUserClaimByIndex( uint index ) external view returns( uint status, uint coverId, uint claimId ) { uint statusno; (statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender); status = statusno; } /** * @dev Gets details of a given claim id. * @param _claimId Claim Id. * @return status Current status of claim id * @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial * @return claimOwner Address through which claim is submitted * @return coverId Coverid associated with the claim id */ function getClaimbyIndex(uint _claimId) external view returns ( uint claimId, uint status, int8 finalVerdict, address claimOwner, uint coverId ) { uint stat; claimId = _claimId; (, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId); claimOwner = qd.getCoverMemberAddress(coverId); status = stat; } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns(uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function changePendingClaimStart() public onlyInternal { uint origstat; uint state12Count; uint pendingClaimStart = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = pendingClaimStart; i < actualClaimLength; i++) { (, , , origstat, , state12Count) = cd.getClaim(i); if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60))) cd.setpendingClaimStart(i); else break; } } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) public { address qadd = qd.getCoverMemberAddress(coverId); require(qadd == msg.sender); uint8 cStatus; (, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId); require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted"); require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired"); if (ms.isPause() == false) { _addClaim(coverId, now, qadd); } else { cd.setClaimAtEmergencyPause(coverId, now, false); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested)); } } /** * @dev Submits the Claims queued once the emergency pause is switched off. */ function submitClaimAfterEPOff() public onlyInternal { uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP(); uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP(); uint coverId; uint dateUpd; bool submit; address qadd; for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) { (coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i); require(submit == false); qadd = qd.getCoverMemberAddress(coverId); _addClaim(coverId, dateUpd, qadd); cd.setClaimSubmittedAtEPTrue(i, true); } cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP); } /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Pause Voting of All Pending Claims when Emergency Pause Start. */ function pauseAllPendingClaimsVoting() public onlyInternal { uint firstIndex = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = firstIndex; i < actualClaimLength; i++) { if (checkVoteClosing(i) == 0) { uint dateUpd = cd.getClaimDateUpd(i); cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false); } } } /** * @dev Resume the voting phase of all Claims paused due to an emergency pause. */ function startAllPendingClaimsVoting() public onlyInternal { uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP(); uint i; uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause(); for (i = firstIndx; i < lengthOfClaimVotingPause; i++) { uint pendingTime; uint claimID; (claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i); uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime); cd.setClaimdateUpd(claimID, pTime); cd.setPendingClaimVoteStatus(i, true); uint coverid; (, coverid) = cd.getClaimCoverId(claimID); address qadd = qd.getCoverMemberAddress(coverid); tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime())); p1.closeClaimsOraclise(claimID, uint64(pTime)); } cd.setFirstClaimIndexToStartVotingAfterEP(i); } /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns(int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = -1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } uint time = now; cd.setClaimdateUpd(claimId, time); if (stat >= 2 && stat <= 5) { p1.closeClaimsOraclise(claimId, cd.maxVotingTime()); } if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) { p1.closeClaimsOraclise(claimId, cd.payoutRetryTime()); } else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) { uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now)); p1.closeClaimsOraclise(claimId, timeLeft); } } /** * @dev Submits a claim for a given cover note. * Set deposits flag against cover. */ function _addClaim(uint coverId, uint time, address add) internal { tf.depositCN(coverId); uint len = cd.actualClaimLength(); cd.addClaim(len, coverId, add, now); cd.callClaimEvent(coverId, add, len, time); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); bytes4 curr = qd.getCurrencyOfCover(coverId); uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured)); p2.internalLiquiditySwap(curr); p1.closeClaimsOraclise(len, cd.maxVotingTime()); } } // File: nexusmutual-contracts/contracts/ClaimsReward.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity 0.5.7; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool1 internal p1; Pool2 internal p2; PoolData internal pd; Governance internal gv; IPooledStaking internal pooledStaking; uint private constant DECIMAL1E18 = uint(10) ** 18; function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { uint coverid; (, coverid) = cd.getClaimCoverId(claimid); uint status; (, status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) { // when current status is "Claim Accepted Payout Pending" uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); address payable coverHolder = qd.getCoverMemberAddress(coverid); bytes4 coverCurrency = qd.getCurrencyOfCover(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency); if (success) { tf.burnStakedTokens(coverid, coverCurrency, sumAssured); c1.setClaimStatus(claimid, 14); } } c1.changePendingClaimStart(); } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenCA(claimId); } else { (, , totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenMV(claimId); }else { (, , totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns(uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } (reward, , , ) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); bytes4 curr = qd.getCurrencyOfCover(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); td.setDepositCN(coverid, false); // Unset flag tf.burnDepositCN(coverid); // burn Deposited CN pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured)); p2.internalLiquiditySwap(curr); } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); td.setDepositCN(coverid, false); // Unset flag tf.unlockCN(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr); if (success) { tf.burnStakedTokens(coverid, curr, sumAssured); } } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, -1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, -1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex, ) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc, , ) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total=0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); //solhint-disable-line } } // File: nexusmutual-contracts/contracts/MemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MemberRoles is IMemberRoles, Governed, Iupgradable { TokenController public dAppToken; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember ( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner ( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); dAppToken = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate (address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole( //solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole( //solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i=0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); dAppToken.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); dAppToken.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); //solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); //solhint-disable-line } } /** * @dev Called by existed member if wish to Withdraw membership. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist } /** * @dev Called by existed member if wish to switch membership to other address. * @param _add address of user to forward membership. */ function switchMembership(address _add) external { require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.addToWhitelist(_add); _updateRole(_add, uint(Role.Member), true); tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); emit switchedMembership(msg.sender, _add, now); } /// @dev Return number of member roles function totalRoles() public view returns(uint256) { //solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns(bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } // File: nexusmutual-contracts/contracts/ProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping (uint => CategoryAction) internal categoryActionData; mapping (uint => uint) public categoryABReq; mapping (uint => uint) public isSpecialResolution; mapping (uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Restricts calls to deprecated functions */ modifier deprecated() { revert("Function deprecated"); _; } /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external deprecated { } /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external deprecated { //solhint-disable-line } /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns(uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) { return( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) { return( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public deprecated { } /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns(uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Initiates add solution /// @param _solutionHash Solution hash having required data against adding solution function addSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Opens proposal for voting function openProposalForVoting(uint _proposalId) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function pauseProposal(uint _proposalId) public; function resumeProposal(uint _proposalId) public; function allowedToCatgorize() public view returns(uint roleId); } // File: nexusmutual-contracts/contracts/Governance.sol // /* Copyright (C) 2017 GovBlocks.io // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint=>uint) memberVoteValue; mapping(uint=>uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping (address => mapping(uint => uint)) public memberProposalVote; mapping (address => uint) public followerDelegation; mapping (address => uint) internal followerCount; mapping (address => uint[]) internal leaderDelegation; mapping (uint => VoteTally) public proposalVoteTally; mapping (address => bool) public isOpenForDelegation; mapping (address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Initiates add solution * To implement the governance interface */ function addSolution(uint, string calldata, bytes calldata) external { } /** * @dev Opens proposal for voting * To implement the governance interface */ function openProposalForVoting(uint) external { } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) { return( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns(uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns(uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns(bool check) { if (category == 0) return true; uint[] memory mrAllowed; (, , , , mrAllowed, , ) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns(bool delegated) { for (uint i=0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Pauses a proposal * To implement govblocks interface */ function pauseProposal(uint) public { } /** * @dev Resumes a proposal * To implement govblocks interface */ function resumeProposal(uint) public { } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns(uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns(uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime, ) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10**18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10**18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns(uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns(bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } (bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (, , majorityVote, , , , ) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (, , _majorityVote, , , , ) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } }
@dev updates daiFeedAddress address. @param _add address of DAI feed.
function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; }
7,286,822
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 4533, 5248, 77, 8141, 1887, 1758, 18, 632, 891, 389, 1289, 1758, 434, 463, 18194, 4746, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9793, 2047, 73, 329, 1887, 12, 2867, 389, 1289, 13, 3903, 1338, 3061, 288, 203, 3639, 5248, 77, 8141, 1887, 273, 389, 1289, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x59aa7D92e88A456e66F90374abd1d4C125e7CEBc/sources/src/universal/Proxy.sol
@title Proxy @notice Proxy is a transparent proxy that passes through the call if the caller is the owner or if the caller is address(0), meaning that the call originated from an off-chain simulation.
contract Proxy { event Upgraded(address indexed implementation); event AdminChanged(address previousAdmin, address newAdmin); pragma solidity 0.8.15; import { Constants } from "../libraries/Constants.sol"; modifier proxyCallIfNotAdmin() { if (msg.sender == _getAdmin() || msg.sender == address(0)) { _; _doProxyCall(); } } modifier proxyCallIfNotAdmin() { if (msg.sender == _getAdmin() || msg.sender == address(0)) { _; _doProxyCall(); } } } else { constructor(address _admin) { _changeAdmin(_admin); } receive() external payable { _doProxyCall(); } fallback() external payable { _doProxyCall(); } function upgradeTo(address _implementation) public virtual proxyCallIfNotAdmin { _setImplementation(_implementation); } function upgradeToAndCall( address _implementation, bytes calldata _data ) public payable virtual proxyCallIfNotAdmin returns (bytes memory) { _setImplementation(_implementation); (bool success, bytes memory returndata) = _implementation.delegatecall(_data); require(success, "Proxy: delegatecall to new implementation contract failed"); return returndata; } function changeAdmin(address _admin) public virtual proxyCallIfNotAdmin { _changeAdmin(_admin); } function admin() public virtual proxyCallIfNotAdmin returns (address) { return _getAdmin(); } function implementation() public virtual proxyCallIfNotAdmin returns (address) { return _getImplementation(); } function _setImplementation(address _implementation) internal { bytes32 proxyImplementation = Constants.PROXY_IMPLEMENTATION_ADDRESS; assembly { sstore(proxyImplementation, _implementation) } emit Upgraded(_implementation); } function _setImplementation(address _implementation) internal { bytes32 proxyImplementation = Constants.PROXY_IMPLEMENTATION_ADDRESS; assembly { sstore(proxyImplementation, _implementation) } emit Upgraded(_implementation); } function _changeAdmin(address _admin) internal { address previous = _getAdmin(); bytes32 proxyOwner = Constants.PROXY_OWNER_ADDRESS; assembly { sstore(proxyOwner, _admin) } emit AdminChanged(previous, _admin); } function _changeAdmin(address _admin) internal { address previous = _getAdmin(); bytes32 proxyOwner = Constants.PROXY_OWNER_ADDRESS; assembly { sstore(proxyOwner, _admin) } emit AdminChanged(previous, _admin); } function _doProxyCall() internal { address impl = _getImplementation(); require(impl != address(0), "Proxy: implementation not initialized"); assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0) returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } function _doProxyCall() internal { address impl = _getImplementation(); require(impl != address(0), "Proxy: implementation not initialized"); assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0) returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } if iszero(success) { revert(0x0, returndatasize()) } function _getImplementation() internal view returns (address) { address impl; bytes32 proxyImplementation = Constants.PROXY_IMPLEMENTATION_ADDRESS; assembly { impl := sload(proxyImplementation) } return impl; } function _getImplementation() internal view returns (address) { address impl; bytes32 proxyImplementation = Constants.PROXY_IMPLEMENTATION_ADDRESS; assembly { impl := sload(proxyImplementation) } return impl; } function _getAdmin() internal view returns (address) { address owner; bytes32 proxyOwner = Constants.PROXY_OWNER_ADDRESS; assembly { owner := sload(proxyOwner) } return owner; } function _getAdmin() internal view returns (address) { address owner; bytes32 proxyOwner = Constants.PROXY_OWNER_ADDRESS; assembly { owner := sload(proxyOwner) } return owner; } }
15,776,577
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 2649, 7659, 632, 20392, 7659, 353, 279, 17270, 2889, 716, 11656, 3059, 326, 745, 309, 326, 4894, 353, 326, 3410, 578, 540, 309, 326, 4894, 353, 1758, 12, 20, 3631, 12256, 716, 326, 745, 4026, 690, 628, 392, 3397, 17, 5639, 540, 14754, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7659, 288, 203, 565, 871, 1948, 19305, 12, 2867, 8808, 4471, 1769, 203, 203, 565, 871, 7807, 5033, 12, 2867, 2416, 4446, 16, 1758, 394, 4446, 1769, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3600, 31, 203, 5666, 288, 5245, 289, 628, 315, 6216, 31417, 19, 2918, 18, 18281, 14432, 203, 565, 9606, 2889, 1477, 10288, 4446, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 389, 588, 4446, 1435, 747, 1234, 18, 15330, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 31, 203, 5411, 389, 2896, 3886, 1477, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 9606, 2889, 1477, 10288, 4446, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 422, 389, 588, 4446, 1435, 747, 1234, 18, 15330, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 31, 203, 5411, 389, 2896, 3886, 1477, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 3885, 12, 2867, 389, 3666, 13, 288, 203, 3639, 389, 3427, 4446, 24899, 3666, 1769, 203, 565, 289, 203, 203, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 389, 2896, 3886, 1477, 5621, 203, 565, 289, 203, 203, 565, 5922, 1435, 3903, 8843, 429, 288, 203, 3639, 389, 2896, 3886, 1477, 5621, 203, 565, 289, 203, 203, 565, 445, 8400, 774, 12, 2867, 389, 30810, 13, 1071, 5024, 2889, 1477, 10288, 4446, 288, 203, 3639, 389, 542, 13621, 24899, 30810, 1769, 203, 565, 289, 203, 203, 565, 445, 8400, 774, 1876, 1477, 12, 203, 3639, 1758, 389, 30810, 16, 203, 3639, 1731, 745, 892, 389, 892, 203, 565, 262, 203, 3639, 1071, 203, 3639, 8843, 429, 203, 3639, 5024, 203, 3639, 2889, 1477, 10288, 4446, 203, 3639, 1135, 261, 3890, 3778, 13, 203, 565, 288, 203, 3639, 389, 542, 13621, 24899, 30810, 1769, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 389, 30810, 18, 22216, 1991, 24899, 892, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 3886, 30, 7152, 1991, 358, 394, 4471, 6835, 2535, 8863, 203, 3639, 327, 327, 892, 31, 203, 565, 289, 203, 203, 565, 445, 2549, 4446, 12, 2867, 389, 3666, 13, 1071, 5024, 2889, 1477, 10288, 4446, 288, 203, 3639, 389, 3427, 4446, 24899, 3666, 1769, 203, 565, 289, 203, 203, 565, 445, 3981, 1435, 1071, 5024, 2889, 1477, 10288, 4446, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 588, 4446, 5621, 203, 565, 289, 203, 203, 565, 445, 4471, 1435, 1071, 5024, 2889, 1477, 10288, 4446, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 588, 13621, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 542, 13621, 12, 2867, 389, 30810, 13, 2713, 288, 203, 3639, 1731, 1578, 2889, 13621, 273, 5245, 18, 16085, 67, 9883, 7618, 2689, 67, 15140, 31, 203, 3639, 19931, 288, 203, 5411, 272, 2233, 12, 5656, 13621, 16, 389, 30810, 13, 203, 3639, 289, 203, 3639, 3626, 1948, 19305, 24899, 30810, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 542, 13621, 12, 2867, 389, 30810, 13, 2713, 288, 203, 3639, 1731, 1578, 2889, 13621, 273, 5245, 18, 16085, 67, 9883, 7618, 2689, 67, 15140, 31, 203, 3639, 19931, 288, 203, 5411, 272, 2233, 12, 5656, 13621, 16, 389, 30810, 13, 203, 3639, 289, 203, 3639, 3626, 1948, 19305, 24899, 30810, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 3427, 4446, 12, 2867, 389, 3666, 13, 2713, 288, 203, 3639, 1758, 2416, 273, 389, 588, 4446, 5621, 203, 3639, 1731, 1578, 2889, 5541, 273, 5245, 18, 16085, 67, 29602, 67, 15140, 31, 203, 3639, 19931, 288, 203, 5411, 272, 2233, 12, 5656, 5541, 16, 389, 3666, 13, 203, 3639, 289, 203, 3639, 3626, 7807, 5033, 12, 11515, 16, 389, 3666, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 3427, 4446, 12, 2867, 389, 3666, 13, 2713, 288, 203, 3639, 1758, 2416, 273, 389, 588, 4446, 5621, 203, 3639, 1731, 1578, 2889, 5541, 273, 5245, 18, 16085, 67, 29602, 67, 15140, 31, 203, 3639, 19931, 288, 203, 5411, 272, 2233, 12, 5656, 5541, 16, 389, 3666, 13, 203, 3639, 289, 203, 3639, 3626, 7807, 5033, 12, 11515, 16, 389, 3666, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 2896, 3886, 1477, 1435, 2713, 288, 203, 3639, 1758, 9380, 273, 389, 588, 13621, 5621, 203, 3639, 2583, 12, 11299, 480, 1758, 12, 20, 3631, 315, 3886, 30, 4471, 486, 6454, 8863, 203, 203, 3639, 19931, 288, 203, 5411, 745, 892, 3530, 12, 20, 92, 20, 16, 374, 92, 20, 16, 745, 13178, 554, 10756, 203, 203, 5411, 2231, 2216, 519, 7152, 1991, 12, 31604, 9334, 9380, 16, 374, 92, 20, 16, 745, 13178, 554, 9334, 374, 92, 20, 16, 374, 92, 20, 13, 203, 203, 5411, 327, 892, 3530, 12, 20, 92, 20, 16, 374, 92, 20, 16, 327, 13178, 554, 10756, 203, 203, 203, 5411, 327, 12, 20, 92, 20, 16, 327, 13178, 554, 10756, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 2896, 3886, 1477, 1435, 2713, 288, 203, 3639, 1758, 9380, 273, 389, 588, 13621, 5621, 203, 3639, 2583, 12, 11299, 480, 1758, 12, 20, 3631, 315, 3886, 30, 4471, 486, 6454, 8863, 203, 203, 3639, 19931, 288, 203, 5411, 745, 892, 3530, 12, 20, 92, 20, 16, 374, 92, 20, 16, 745, 13178, 554, 10756, 203, 203, 5411, 2231, 2216, 519, 7152, 1991, 12, 31604, 9334, 9380, 16, 374, 92, 20, 16, 745, 13178, 554, 9334, 374, 92, 20, 16, 374, 92, 20, 13, 203, 203, 5411, 327, 892, 3530, 12, 20, 92, 20, 16, 374, 92, 20, 16, 327, 13178, 554, 10756, 203, 203, 203, 5411, 327, 12, 20, 92, 20, 16, 327, 13178, 554, 10756, 203, 3639, 289, 203, 565, 289, 203, 203, 5411, 309, 353, 7124, 12, 4768, 13, 288, 15226, 12, 20, 92, 20, 16, 327, 13178, 554, 10756, 289, 203, 565, 445, 389, 588, 13621, 1435, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 9380, 31, 203, 3639, 1731, 1578, 2889, 13621, 273, 5245, 18, 16085, 67, 9883, 7618, 2689, 67, 15140, 31, 203, 3639, 19931, 288, 203, 5411, 9380, 519, 272, 945, 12, 5656, 13621, 13, 203, 3639, 289, 2 ]
pragma solidity ^0.4.24; /** * @title ERC20 interface * */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title OwnableWithAdmin * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableWithAdmin { address public owner; address public adminOwner; 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; adminOwner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(msg.sender == adminOwner); _; } /** * @dev Throws if called by any account other than the owner or admin. */ modifier onlyOwnerOrAdmin() { require(msg.sender == adminOwner || msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current adminOwner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferAdminOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(adminOwner, newOwner); adminOwner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } } /** * @title LockedPrivatesale * @notice Contract is not payable. * Owner or admin can allocate tokens. * Tokens will be released in 3 steps / dates. * * */ contract LockedPrivatesale is OwnableWithAdmin { using SafeMath for uint256; uint256 private constant DECIMALFACTOR = 10**uint256(18); event FundsBooked(address backer, uint256 amount, bool isContribution); event LogTokenClaimed(address indexed _recipient, uint256 _amountClaimed, uint256 _totalAllocated, uint256 _grandTotalClaimed); event LogNewAllocation(address indexed _recipient, uint256 _totalAllocated); event LogRemoveAllocation(address indexed _recipient, uint256 _tokenAmountRemoved); event LogOwnerAllocation(address indexed _recipient, uint256 _totalAllocated); // Amount of tokens claimed uint256 public grandTotalClaimed = 0; // The token being sold ERC20 public token; // Amount of tokens Raised uint256 public tokensTotal = 0; // Max token amount uint256 public hardCap = 0; //Tokens will be released in 3 steps/dates uint256 public step1; uint256 public step2; uint256 public step3; // Buyers total allocation mapping (address => uint256) public allocationsTotal; // User total Claimed mapping (address => uint256) public totalClaimed; // List of allocation step 1 mapping (address => uint256) public allocations1; // List of allocation step 2 mapping (address => uint256) public allocations2; // List of allocation step 3 mapping (address => uint256) public allocations3; //Buyers mapping(address => bool) public buyers; //Buyers who received all there tokens mapping(address => bool) public buyersReceived; //List of all addresses address[] public addresses; constructor(uint256 _step1, uint256 _step2, uint256 _step3, ERC20 _token) public { require(_token != address(0)); require(_step1 >= now); require(_step2 >= _step1); require(_step3 >= _step2); step1 = _step1; step2 = _step2; step3 = _step3; token = _token; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () public { //Not payable } /** * @dev Set allocation buy admin * @param _recipient Users wallet * @param _tokenAmount Amount Allocated tokens + 18 decimals */ function setAllocation (address _recipient, uint256 _tokenAmount) onlyOwnerOrAdmin public{ require(_tokenAmount > 0); require(_recipient != address(0)); //Check hardCap require(_validateHardCap(_tokenAmount)); //Allocate tokens _setAllocation(_recipient, _tokenAmount); //Increese token amount tokensTotal = tokensTotal.add(_tokenAmount); //Logg Allocation emit LogOwnerAllocation(_recipient, _tokenAmount); } /** * @dev Remove allocation * @param _recipient Users wallet * */ function removeAllocation (address _recipient) onlyOwner public{ require(_recipient != address(0)); require(totalClaimed[_recipient] == 0); //Check if user claimed tokens //_recipient total amount uint256 _tokenAmountRemoved = allocationsTotal[_recipient]; //Decreese token amount tokensTotal = tokensTotal.sub(_tokenAmountRemoved); //Reset allocations allocations1[_recipient] = 0; allocations2[_recipient] = 0; allocations3[_recipient] = 0; allocationsTotal[_recipient] = 0; // Remove //Set buyer to false buyers[_recipient] = false; emit LogRemoveAllocation(_recipient, _tokenAmountRemoved); } /** * @dev Set internal allocation * _buyer The adress of the buyer * _tokenAmount Amount Allocated tokens + 18 decimals */ function _setAllocation (address _buyer, uint256 _tokenAmount) internal{ if(!buyers[_buyer]){ //Add buyer to buyers list buyers[_buyer] = true; //Add _buyer to addresses list addresses.push(_buyer); //Reset buyer allocation allocationsTotal[_buyer] = 0; } //Add tokens to buyers allocation allocationsTotal[_buyer] = allocationsTotal[_buyer].add(_tokenAmount); //Spilt amount in 3 uint256 splitAmount = allocationsTotal[_buyer].div(3); uint256 diff = allocationsTotal[_buyer].sub(splitAmount+splitAmount+splitAmount); //Sale steps allocations1[_buyer] = splitAmount; // step 1 allocations2[_buyer] = splitAmount; // step 2 allocations3[_buyer] = splitAmount.add(diff); // step 3 + diff //Logg Allocation emit LogNewAllocation(_buyer, _tokenAmount); } /** * @dev Return address available allocation * @param _recipient which address is applicable */ function checkAvailableTokens (address _recipient) public view returns (uint256) { //Check if user have bought tokens require(buyers[_recipient]); uint256 _availableTokens = 0; if(now >= step1){ _availableTokens = _availableTokens.add(allocations1[_recipient]); } if(now >= step2){ _availableTokens = _availableTokens.add(allocations2[_recipient]); } if(now >= step3){ _availableTokens = _availableTokens.add(allocations3[_recipient]); } return _availableTokens; } /** * @dev Transfer a recipients available allocation to their address * @param _recipients Array of addresses to withdraw tokens for */ function distributeManyTokens(address[] _recipients) onlyOwnerOrAdmin public { for (uint256 i = 0; i < _recipients.length; i++) { //Check if address is buyer //And if the buyer is not already received all the tokens if(buyers[_recipients[i]] && !buyersReceived[_recipients[i]]){ distributeTokens( _recipients[i]); } } } /** * @dev Loop address and distribute tokens * */ function distributeAllTokens() onlyOwner public { for (uint256 i = 0; i < addresses.length; i++) { //Check if address is buyer //And if the buyer is not already received all the tokens if(buyers[addresses[i]] && !buyersReceived[addresses[i]]){ distributeTokens( addresses[i]); } } } /** * @notice Withdraw available tokens * */ function withdrawTokens() public { distributeTokens(msg.sender); } /** * @dev Transfer a recipients available allocation to _recipient * */ function distributeTokens(address _recipient) public { //Check date require(now >= step1); //Check have bought tokens require(buyers[_recipient]); // bool _lastWithdraw = false; uint256 _availableTokens = 0; if(now >= step1 && now >= step2 && now >= step3 ){ _availableTokens = _availableTokens.add(allocations3[_recipient]); _availableTokens = _availableTokens.add(allocations2[_recipient]); _availableTokens = _availableTokens.add(allocations1[_recipient]); //Reset all allocations allocations3[_recipient] = 0; allocations2[_recipient] = 0; allocations1[_recipient] = 0; //Step 3, all tokens should be received _lastWithdraw = true; } else if(now >= step1 && now >= step2 ){ _availableTokens = _availableTokens.add(allocations2[_recipient]); _availableTokens = _availableTokens.add(allocations1[_recipient]); //Reset step 1 & step 2 allocation allocations2[_recipient] = 0; allocations1[_recipient] = 0; }else if(now >= step1){ _availableTokens = allocations1[_recipient]; //Reset step 1 allocation allocations1[_recipient] = 0; } require(_availableTokens>0); //Check if contract has tokens require(token.balanceOf(this)>=_availableTokens); //Transfer tokens require(token.transfer(_recipient, _availableTokens)); //Add claimed tokens to totalClaimed totalClaimed[_recipient] = totalClaimed[_recipient].add(_availableTokens); //Add claimed tokens to grandTotalClaimed grandTotalClaimed = grandTotalClaimed.add(_availableTokens); emit LogTokenClaimed(_recipient, _availableTokens, allocationsTotal[_recipient], grandTotalClaimed); //If all tokens are received, add _recipient to buyersReceived //To prevent the loop to fail if user allready used the withdrawTokens if(_lastWithdraw){ buyersReceived[_recipient] = true; } } function _validateHardCap(uint256 _tokenAmount) internal view returns (bool) { return tokensTotal.add(_tokenAmount) <= hardCap; } function getListOfAddresses() public view returns (address[]) { return addresses; } // Allow transfer of tokens back to owner or reserve wallet function returnTokens() public onlyOwner { uint256 balance = token.balanceOf(this); require(token.transfer(owner, balance)); } // Owner can transfer tokens that are sent here by mistake function refundTokens(address _recipient, ERC20 _token) public onlyOwner { uint256 balance = _token.balanceOf(this); require(_token.transfer(_recipient, balance)); } } /** * @title EDPrivateSale * @dev Only owner or admin can allocate tokens. Tokens can be booked in advanced without the token contract. * Tokens will be released in 3 steps / dates. * A token needs to be attached to this contract and this contract needs to have balance to be able to send tokens to collector * No whitelist in contract is requierd * */ contract EDPrivateSale is LockedPrivatesale { constructor( uint256 _step1, uint256 _step2, uint256 _step3, ERC20 _token ) public LockedPrivatesale(_step1, _step2, _step3, _token) { // 50,000,000 tokens hardCap = 50000000 * (10**uint256(18)); } }
* @title EDPrivateSale @dev Only owner or admin can allocate tokens. Tokens can be booked in advanced without the token contract. Tokens will be released in 3 steps / dates. A token needs to be attached to this contract and this contract needs to have balance to be able to send tokens to collector No whitelist in contract is requierd/
contract EDPrivateSale is LockedPrivatesale { constructor( uint256 _step1, uint256 _step2, uint256 _step3, ERC20 _token ) public LockedPrivatesale(_step1, _step2, _step3, _token) { hardCap = 50000000 * (10**uint256(18)); } }
1,798,386
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 15585, 6014, 30746, 632, 5206, 5098, 3410, 578, 3981, 848, 10101, 2430, 18, 13899, 848, 506, 6978, 329, 316, 16111, 2887, 326, 1147, 6835, 18, 13899, 903, 506, 15976, 316, 890, 6075, 342, 7811, 18, 432, 1147, 4260, 358, 506, 7495, 358, 333, 6835, 471, 333, 6835, 4260, 358, 1240, 11013, 358, 506, 7752, 358, 1366, 2430, 358, 8543, 2631, 10734, 316, 6835, 353, 10780, 2453, 72, 19, 2, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 15585, 6014, 30746, 353, 3488, 329, 15475, 815, 5349, 288, 203, 225, 3885, 12, 203, 565, 2254, 5034, 389, 4119, 21, 16, 7010, 565, 2254, 5034, 389, 4119, 22, 16, 7010, 565, 2254, 5034, 389, 4119, 23, 16, 377, 203, 565, 4232, 39, 3462, 389, 2316, 203, 225, 262, 1071, 3488, 329, 15475, 815, 5349, 24899, 4119, 21, 16, 389, 4119, 22, 16, 389, 4119, 23, 16, 389, 2316, 13, 288, 203, 203, 565, 7877, 4664, 273, 1381, 17877, 380, 261, 2163, 636, 11890, 5034, 12, 2643, 10019, 7010, 203, 225, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x751d136E0E203c27de76F5AF2AE1bDeb6862626F/sources/XBaseBridge.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("XBaseBridge", "$XBB") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 25; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 60; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(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);
3,628,853
[ 1, 4625, 348, 7953, 560, 30, 225, 4433, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 60, 2171, 13691, 3113, 4662, 60, 9676, 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, 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, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 6969, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 374, 31, 203, 203, 3639, 2254, 5034, 389, 87, 1165, 3882, 21747, 14667, 273, 4752, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 8870, 14667, 273, 374, 31, 203, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 404, 67, 3784, 67, 3784, 67, 3784, 67, 3784, 380, 404, 73, 2643, 31, 203, 203, 203, 3639, 30143, 3882, 21747, 14667, 273, 389, 70, 9835, 3882, 21747, 14667, 31, 203, 3639, 30143, 48, 18988, 24237, 14667, 273, 389, 70, 9835, 48, 18988, 24237, 14667, 31, 203, 3639, 30143, 8870, 14667, 273, 389, 70, 9835, 8870, 14667, 31, 203, 3639, 30143, 5269, 2954, 281, 273, 30143, 3882, 21747, 14667, 397, 30143, 48, 18988, 24237, 14667, 397, 30143, 8870, 14667, 31, 203, 203, 3639, 357, 80, 3882, 21747, 14667, 273, 389, 87, 1165, 3882, 21747, 14667, 31, 203, 3639, 357, 80, 48, 18988, 24237, 14667, 273, 389, 87, 1165, 48, 18988, 24237, 14667, 31, 203, 3639, 357, 80, 8870, 14667, 273, 389, 87, 1165, 8870, 14667, 31, 203, 3639, 357, 80, 5269, 2954, 281, 273, 357, 80, 3882, 21747, 14667, 397, 357, 80, 48, 18988, 24237, 14667, 397, 357, 80, 8870, 14667, 31, 203, 203, 203, 3639, 4433, 1265, 2954, 281, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 20, 92, 22097, 3631, 638, 1769, 203, 203, 203, 5411, 389, 81, 474, 353, 392, 2713, 445, 316, 4232, 39, 3462, 18, 18281, 716, 353, 1338, 2566, 2674, 16, 203, 5411, 471, 385, 16791, 506, 2566, 14103, 3382, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2078, 3088, 1283, 1769, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUtil { /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } interface IStakingProxy { function getBalance() external view returns(uint256); function withdraw(uint256 _amount) external; function stake() external; function distribute() external; } interface IRewardStaking { function stakeFor(address, uint256) external; function stake( uint256) external; function withdraw(uint256 amount, bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function earned(address account) external view returns (uint256); function getReward() external; function getReward(address _account, bool _claimExtras) external; function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 _pid) external view returns (address); function rewardToken() external view returns (address); function balanceOf(address _account) external view returns (uint256); } /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint32 a, uint32 b) internal pure returns (uint32 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112. library BoringMath112 { function add(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint112 a, uint112 b) internal pure returns (uint112 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint112 a, uint112 b) internal pure returns (uint112) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224. library BoringMath224 { function add(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint224 a, uint224 b) internal pure returns (uint224 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint224 a, uint224 b) internal pure returns (uint224) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } interface IGac { function paused() external view returns (bool); function transferFromDisabled() external view returns (bool); function unpause() external; function pause() external; function enableTransferFrom() external; function disableTransferFrom() external; function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } /** * @title Global Access Control Managed - Base Class * @notice allows inheriting contracts to leverage global access control permissions conveniently, as well as granting contract-specific pausing functionality */ contract GlobalAccessControlManaged is PausableUpgradeable { IGac public gac; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); /// ======================= /// ===== Initializer ===== /// ======================= /** * @notice Initializer * @dev this is assumed to be used in the initializer of the inhereiting contract * @param _globalAccessControl global access control which is pinged to allow / deny access to permissioned calls by role */ function __GlobalAccessControlManaged_init(address _globalAccessControl) public initializer { __Pausable_init_unchained(); gac = IGac(_globalAccessControl); } /// ===================== /// ===== Modifiers ===== /// ===================== // @dev only holders of the given role on the GAC can call modifier onlyRole(bytes32 role) { require(gac.hasRole(role, msg.sender), "GAC: invalid-caller-role"); _; } // @dev only holders of any of the given set of roles on the GAC can call modifier onlyRoles(bytes32[] memory roles) { bool validRoleFound = false; for (uint256 i = 0; i < roles.length; i++) { bytes32 role = roles[i]; if (gac.hasRole(role, msg.sender)) { validRoleFound = true; break; } } require(validRoleFound, "GAC: invalid-caller-role"); _; } // @dev only holders of the given role on the GAC can call, or a specified address // @dev used to faciliate extra contract-specific permissioned accounts modifier onlyRoleOrAddress(bytes32 role, address account) { require( gac.hasRole(role, msg.sender) || msg.sender == account, "GAC: invalid-caller-role-or-address" ); _; } /// @dev can be pausable by GAC or local flag modifier gacPausable() { require(!gac.paused(), "global-paused"); require(!paused(), "local-paused"); _; } /// ================================ /// ===== Permissioned actions ===== /// ================================ function pause() external { require(gac.hasRole(PAUSER_ROLE, msg.sender)); _pause(); } function unpause() external { require(gac.hasRole(UNPAUSER_ROLE, msg.sender)); _unpause(); } } /* Citadel locking contract Adapted from CvxLockerV2.sol (https://github.com/convex-eth/platform/blob/4a51cf7e411db27fa8fc2244137013f9fbdebb38/contracts/contracts/CvxLockerV2.sol). Changes: - Upgradeability - Removed staking */ contract StakedCitadelLocker is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable, GlobalAccessControlManaged { using BoringMath for uint256; using BoringMath224 for uint224; using BoringMath112 for uint112; using BoringMath32 for uint32; using SafeERC20Upgradeable for IERC20Upgradeable; /* ========== STATE VARIABLES ========== */ struct Reward { bool useBoost; uint40 periodFinish; uint208 rewardRate; uint40 lastUpdateTime; uint208 rewardPerTokenStored; } struct Balances { uint112 locked; uint112 boosted; uint32 nextUnlockIndex; } struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } struct EarnedData { address token; uint256 amount; } struct Epoch { uint224 supply; //epoch boosted supply uint32 date; //epoch start date } //token constants IERC20Upgradeable public stakingToken; // xCTDL token //rewards address[] public rewardTokens; mapping(address => Reward) public rewardData; // Duration that rewards are streamed over uint256 public constant rewardsDuration = 86400; // 1 day // Duration of lock/earned penalty period uint256 public constant lockDuration = rewardsDuration * 7 * 21; // 21 weeks // reward token -> distributor -> is approved to add rewards mapping(address => mapping(address => bool)) public rewardDistributors; // user -> reward token -> amount mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; mapping(address => mapping(address => uint256)) public rewards; //supplies and epochs uint256 public lockedSupply; uint256 public boostedSupply; Epoch[] public epochs; //mappings for balance data mapping(address => Balances) public balances; mapping(address => LockedBalance[]) public userLocks; // ========== Not used ========== //boost address public boostPayment = address(0); uint256 public maximumBoostPayment = 0; uint256 public boostRate = 10000; uint256 public nextMaximumBoostPayment = 0; uint256 public nextBoostRate = 10000; uint256 public constant denominator = 10000; // ============================== //staking uint256 public minimumStake = 10000; uint256 public maximumStake = 10000; address public stakingProxy = address(0); uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing //management uint256 public kickRewardPerEpoch = 100; uint256 public kickRewardEpochDelay = 4; //shutdown bool public isShutdown = false; //erc20-like interface string private _name; string private _symbol; uint8 private _decimals; /* ========== CONSTRUCTOR ========== */ function initialize( address _stakingToken, address _gac, string calldata name, string calldata symbol ) public initializer { require(_stakingToken != address(0)); // dev: _stakingToken address should not be zero stakingToken = IERC20Upgradeable(_stakingToken); _name = name; _symbol = symbol; _decimals = 18; uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)})); __Ownable_init(); __ReentrancyGuard_init(); __GlobalAccessControlManaged_init(_gac); } function decimals() public view returns (uint8) { return _decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function version() public view returns (uint256) { return 2; } /* ========== ADMIN CONFIGURATION ========== */ // Add a new reward token to be distributed to stakers function addReward( address _rewardsToken, address _distributor, bool _useBoost ) public onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime == 0); // require(_rewardsToken != address(stakingToken)); rewardTokens.push(_rewardsToken); rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp); rewardData[_rewardsToken].periodFinish = uint40(block.timestamp); rewardData[_rewardsToken].useBoost = _useBoost; rewardDistributors[_rewardsToken][_distributor] = true; } // Modify approval for an address to call notifyRewardAmount function approveRewardDistributor( address _rewardsToken, address _distributor, bool _approved ) external onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime > 0); rewardDistributors[_rewardsToken][_distributor] = _approved; } //Set the staking contract for the underlying cvx function setStakingContract(address _staking) external onlyOwner gacPausable { require(stakingProxy == address(0), "!assign"); stakingProxy = _staking; } //set staking limits. will stake the mean of the two once either ratio is crossed function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner gacPausable { require(_minimum <= denominator, "min range"); require(_maximum <= denominator, "max range"); require(_minimum <= _maximum, "min range"); minimumStake = _minimum; maximumStake = _maximum; updateStakeRatio(0); } //set boost parameters function setBoost( uint256 _max, uint256 _rate, address _receivingAddress ) external onlyOwner gacPausable { require(_max < 1500, "over max payment"); //max 15% require(_rate < 30000, "over max rate"); //max 3x require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid nextMaximumBoostPayment = _max; nextBoostRate = _rate; boostPayment = _receivingAddress; } //set kick incentive function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner gacPausable { require(_rate <= 500, "over max rate"); //max 5% per epoch require(_delay >= 2, "min delay"); //minimum 2 epochs of grace kickRewardPerEpoch = _rate; kickRewardEpochDelay = _delay; } //shutdown the contract. unstake all tokens. release all locks function shutdown() external onlyOwner { isShutdown = true; } /* ========== VIEWS ========== */ function getRewardTokens() external view returns (address[] memory) { uint256 numTokens = rewardTokens.length; address[] memory tokens = new address[](numTokens); for (uint256 i = 0; i < numTokens; i++) { tokens[i] = rewardTokens[i]; } return tokens; } function _rewardPerToken(address _rewardsToken) internal view returns (uint256) { if (boostedSupply == 0) { return rewardData[_rewardsToken].rewardPerTokenStored; } return uint256(rewardData[_rewardsToken].rewardPerTokenStored).add( _lastTimeRewardApplicable( rewardData[_rewardsToken].periodFinish ) .sub(rewardData[_rewardsToken].lastUpdateTime) .mul(rewardData[_rewardsToken].rewardRate) .mul(1e18) .div( rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply ) ); } function _earned( address _user, address _rewardsToken, uint256 _balance ) internal view returns (uint256) { return _balance .mul( _rewardPerToken(_rewardsToken).sub( userRewardPerTokenPaid[_user][_rewardsToken] ) ) .div(1e18) .add(rewards[_user][_rewardsToken]); } function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) { return MathUpgradeable.min(block.timestamp, _finishTime); } function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) { return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish); } function rewardPerToken(address _rewardsToken) external view returns (uint256) { return _rewardPerToken(_rewardsToken); } function getRewardForDuration(address _rewardsToken) external view returns (uint256) { return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration); } // Address and claimable amount of all reward tokens for the given account function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) { userRewards = new EarnedData[](rewardTokens.length); Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < userRewards.length; i++) { address token = rewardTokens[i]; userRewards[i].token = token; userRewards[i].amount = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); } return userRewards; } // Total BOOSTED balance of an account, including unlocked but not withdrawn tokens function rewardWeightOf(address _user) external view returns (uint256 amount) { return balances[_user].boosted; } // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount) { return balances[_user].locked; } //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; //start with current boosted amount amount = balances[_user].boosted; uint256 locksLength = locks.length; //remove old records only (will be better gas-wise than adding up) for (uint256 i = nextUnlockIndex; i < locksLength; i++) { if (locks[i].unlockTime <= block.timestamp) { amount = amount.sub(locks[i].boosted); } else { //stop now as no futher checks are needed break; } } //also remove amount locked in the next epoch uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { amount = amount.sub(locks[locksLength - 1].boosted); } return amount; } //BOOSTED balance of an account which only includes properly locked tokens at the given epoch function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get timestamp of given epoch index uint256 epochTime = epochs[_epoch].date; //get timestamp of first non-inclusive epoch uint256 cutoffEpoch = epochTime.sub(lockDuration); //need to add up since the range could be in the middle somewhere //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //lock epoch must be less or equal to the epoch we're basing from. if (lockEpoch <= epochTime) { if (lockEpoch > cutoffEpoch) { amount = amount.add(locks[i].boosted); } else { //stop now as no futher checks matter break; } } } return amount; } //return currently locked but not active balance function pendingLockOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; uint256 locksLength = locks.length; //return amount if latest lock is in the future uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { return locks[locksLength - 1].boosted; } return 0; } function pendingLockAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get next epoch from the given epoch index uint256 nextEpoch = uint256(epochs[_epoch].date).add(rewardsDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //return the next epoch balance if (lockEpoch == nextEpoch) { return locks[i].boosted; } else if (lockEpoch < nextEpoch) { //no need to check anymore break; } } return 0; } //supply of all properly locked BOOSTED balances at most recent eligible epoch function totalSupply() external view returns (uint256 supply) { uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); uint256 cutoffEpoch = currentEpoch.sub(lockDuration); uint256 epochindex = epochs.length; //do not include next epoch's supply if (uint256(epochs[epochindex - 1].date) > currentEpoch) { epochindex--; } //traverse inversely to make more current queries more gas efficient for (uint256 i = epochindex - 1; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(e.supply); } return supply; } //supply of all properly locked BOOSTED balances at the given epoch function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) { uint256 epochStart = uint256(epochs[_epoch].date) .div(rewardsDuration) .mul(rewardsDuration); uint256 cutoffEpoch = epochStart.sub(lockDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = _epoch; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(epochs[i].supply); } return supply; } //find an epoch index based on timestamp function findEpochId(uint256 _time) external view returns (uint256 epoch) { uint256 max = epochs.length - 1; uint256 min = 0; //convert to start point _time = _time.div(rewardsDuration).mul(rewardsDuration); for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min + max + 1) / 2; uint256 midEpochBlock = epochs[mid].date; if (midEpochBlock == _time) { //found return mid; } else if (midEpochBlock < _time) { min = mid; } else { max = mid - 1; } } return min; } // Information on a user's locked balances function lockedBalances(address _user) external view returns ( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; uint256 idx; for (uint256 i = nextUnlockIndex; i < locks.length; i++) { if (locks[i].unlockTime > block.timestamp) { if (idx == 0) { lockData = new LockedBalance[](locks.length - i); } lockData[idx] = locks[i]; idx++; locked = locked.add(locks[i].amount); } else { unlockable = unlockable.add(locks[i].amount); } } return (userBalance.locked, unlockable, locked, lockData); } //number of epochs function epochCount() external view returns (uint256) { return epochs.length; } /* ========== MUTATIVE FUNCTIONS ========== */ function checkpointEpoch() external { _checkpointEpoch(); } //insert a new epoch if needed. fill in any gaps function _checkpointEpoch() internal { //create new epoch in the future where new non-active locks will lock to uint256 nextEpoch = block .timestamp .div(rewardsDuration) .mul(rewardsDuration) .add(rewardsDuration); uint256 epochindex = epochs.length; //first epoch add in constructor, no need to check 0 length //check to add if (epochs[epochindex - 1].date < nextEpoch) { //fill any epoch gaps while (epochs[epochs.length - 1].date != nextEpoch) { uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date) .add(rewardsDuration); epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)})); } //update boost parameters on a new epoch if (boostRate != nextBoostRate) { boostRate = nextBoostRate; } if (maximumBoostPayment != nextMaximumBoostPayment) { maximumBoostPayment = nextMaximumBoostPayment; } } } // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards function lock( address _account, uint256 _amount, uint256 _spendRatio ) external nonReentrant gacPausable updateReward(_account) { //pull tokens stakingToken.safeTransferFrom(msg.sender, address(this), _amount); //lock _lock(_account, _amount, _spendRatio, false); } //lock tokens function _lock( address _account, uint256 _amount, uint256 _spendRatio, bool _isRelock ) internal { require(_amount > 0, "Cannot stake 0"); require(_spendRatio <= maximumBoostPayment, "over max spend"); require(!isShutdown, "shutdown"); Balances storage bal = balances[_account]; //must try check pointing epoch first _checkpointEpoch(); //calc lock and boosted amount uint256 spendAmount = _amount.mul(_spendRatio).div(denominator); uint256 boostRatio = boostRate.mul(_spendRatio).div( maximumBoostPayment == 0 ? 1 : maximumBoostPayment ); uint112 lockAmount = _amount.sub(spendAmount).to112(); uint112 boostedAmount = _amount .add(_amount.mul(boostRatio).div(denominator)) .to112(); //add user balances bal.locked = bal.locked.add(lockAmount); bal.boosted = bal.boosted.add(boostedAmount); //add to total supplies lockedSupply = lockedSupply.add(lockAmount); boostedSupply = boostedSupply.add(boostedAmount); //add user lock records or add to current uint256 lockEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); //if a fresh lock, add on an extra duration period if (!_isRelock) { lockEpoch = lockEpoch.add(rewardsDuration); } uint256 unlockTime = lockEpoch.add(lockDuration); uint256 idx = userLocks[_account].length; //if the latest user lock is smaller than this lock, always just add new entry to the end of the list if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) { userLocks[_account].push( LockedBalance({ amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime) }) ); } else { //else add to a current lock //if latest lock is further in the future, lower index //this can only happen if relocking an expired lock after creating a new lock if (userLocks[_account][idx - 1].unlockTime > unlockTime) { idx--; } //if idx points to the epoch when same unlock time, update //(this is always true with a normal lock but maybe not with relock) if (userLocks[_account][idx - 1].unlockTime == unlockTime) { LockedBalance storage userL = userLocks[_account][idx - 1]; userL.amount = userL.amount.add(lockAmount); userL.boosted = userL.boosted.add(boostedAmount); } else { //can only enter here if a relock is made after a lock and there's no lock entry //for the current epoch. //ex a list of locks such as "[...][older][current*][next]" but without a "current" lock //length - 1 is the next epoch //length - 2 is a past epoch //thus need to insert an entry for current epoch at the 2nd to last entry //we will copy and insert the tail entry(next) and then overwrite length-2 entry //reset idx idx = userLocks[_account].length; //get current last item LockedBalance storage userL = userLocks[_account][idx - 1]; //add a copy to end of list userLocks[_account].push( LockedBalance({ amount: userL.amount, boosted: userL.boosted, unlockTime: userL.unlockTime }) ); //insert current epoch lock entry by overwriting the entry at length-2 userL.amount = lockAmount; userL.boosted = boostedAmount; userL.unlockTime = uint32(unlockTime); } } //update epoch supply, epoch checkpointed above so safe to add to latest uint256 eIndex = epochs.length - 1; //if relock, epoch should be current and not next, thus need to decrease index to length-2 if (_isRelock) { eIndex--; } Epoch storage e = epochs[eIndex]; e.supply = e.supply.add(uint224(boostedAmount)); //send boost payment if (spendAmount > 0) { stakingToken.safeTransfer(boostPayment, spendAmount); } emit Staked(_account, lockEpoch, _amount, lockAmount, boostedAmount); } // Withdraw all currently locked tokens where the unlock time has passed function _processExpiredLocks( address _account, bool _relock, uint256 _spendRatio, address _withdrawTo, address _rewardAddress, uint256 _checkDelay ) internal updateReward(_account) { LockedBalance[] storage locks = userLocks[_account]; Balances storage userBalance = balances[_account]; uint112 locked; uint112 boostedAmount; uint256 length = locks.length; uint256 reward = 0; if ( isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay) ) { //if time is beyond last lock, can just bundle everything together locked = userBalance.locked; boostedAmount = userBalance.boosted; //dont delete, just set next index userBalance.nextUnlockIndex = length.to32(); //check for kick reward //this wont have the exact reward rate that you would get if looped through //but this section is supposed to be for quick and easy low gas processing of all locks //we'll assume that if the reward was good enough someone would have processed at an earlier epoch if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[length - 1].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = uint256(locks[length - 1].amount).mul(rRate).div( denominator ); } } else { //use a processed index(nextUnlockIndex) to not loop as much //deleting does not change array length uint32 nextUnlockIndex = userBalance.nextUnlockIndex; for (uint256 i = nextUnlockIndex; i < length; i++) { //unlock time must be less or equal to time if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break; //add to cumulative amounts locked = locked.add(locks[i].amount); boostedAmount = boostedAmount.add(locks[i].boosted); //check for kick reward //each epoch over due increases reward if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[i].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator) ); } //set next unlock index nextUnlockIndex++; } //update next unlock index userBalance.nextUnlockIndex = nextUnlockIndex; } require(locked > 0, "no exp locks"); //update user balances and total supplies userBalance.locked = userBalance.locked.sub(locked); userBalance.boosted = userBalance.boosted.sub(boostedAmount); lockedSupply = lockedSupply.sub(locked); boostedSupply = boostedSupply.sub(boostedAmount); emit Withdrawn(_account, locked, _relock); //send process incentive if (reward > 0) { //if theres a reward(kicked), it will always be a withdraw only //preallocate enough cvx from stake contract to pay for both reward and withdraw allocateCVXForTransfer(uint256(locked)); //reduce return amount by the kick reward locked = locked.sub(reward.to112()); //transfer reward transferCVX(_rewardAddress, reward, false); emit KickReward(_rewardAddress, _account, reward); } else if (_spendRatio > 0) { //preallocate enough cvx to transfer the boost cost allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) ); } //relock or return to user if (_relock) { _lock(_withdrawTo, locked, _spendRatio, true); } else { transferCVX(_withdrawTo, locked, true); } } // withdraw expired locks to a different address function withdrawExpiredLocksTo(address _withdrawTo) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, false, 0, _withdrawTo, msg.sender, 0); } // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0); } function kickExpiredLocks(address _account) external nonReentrant gacPausable { //allow kick after grace period of 'kickRewardEpochDelay' _processExpiredLocks( _account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay) ); } //pull required amount of cvx from staking for an upcoming transfer // dev: no-op function allocateCVXForTransfer(uint256 _amount) internal { uint256 balance = stakingToken.balanceOf(address(this)); } //transfer helper: pull enough from staking, transfer, updating staking ratio function transferCVX( address _account, uint256 _amount, bool _updateStake ) internal { //allocate enough cvx from staking for the transfer allocateCVXForTransfer(_amount); //transfer stakingToken.safeTransfer(_account, _amount); } //calculate how much cvx should be staked. update if needed function updateStakeRatio(uint256 _offset) internal { if (isShutdown) return; //get balances uint256 local = stakingToken.balanceOf(address(this)); uint256 staked = IStakingProxy(stakingProxy).getBalance(); uint256 total = local.add(staked); if (total == 0) return; //current staked ratio uint256 ratio = staked.mul(denominator).div(total); //mean will be where we reset to if unbalanced uint256 mean = maximumStake.add(minimumStake).div(2); uint256 max = maximumStake.add(_offset); uint256 min = MathUpgradeable.min(minimumStake, minimumStake - _offset); if (ratio > max) { //remove uint256 remove = staked.sub(total.mul(mean).div(denominator)); IStakingProxy(stakingProxy).withdraw(remove); } else if (ratio < min) { //add uint256 increase = total.mul(mean).div(denominator).sub(staked); stakingToken.safeTransfer(stakingProxy, increase); IStakingProxy(stakingProxy).stake(); } } // Claim all pending rewards function getReward(address _account, bool _stake) public nonReentrant gacPausable updateReward(_account) { for (uint256 i; i < rewardTokens.length; i++) { address _rewardsToken = rewardTokens[i]; uint256 reward = rewards[_account][_rewardsToken]; if (reward > 0) { rewards[_account][_rewardsToken] = 0; IERC20Upgradeable(_rewardsToken).safeTransfer(_account, reward); emit RewardPaid(_account, _rewardsToken, reward); } } } // claim all pending rewards function getReward(address _account) external { getReward(_account, false); } /* ========== RESTRICTED FUNCTIONS ========== */ function _notifyReward(address _rewardsToken, uint256 _reward) internal { Reward storage rdata = rewardData[_rewardsToken]; if (block.timestamp >= rdata.periodFinish) { rdata.rewardRate = _reward.div(rewardsDuration).to208(); } else { uint256 remaining = uint256(rdata.periodFinish).sub( block.timestamp ); uint256 leftover = remaining.mul(rdata.rewardRate); rdata.rewardRate = _reward .add(leftover) .div(rewardsDuration) .to208(); } rdata.lastUpdateTime = block.timestamp.to40(); rdata.periodFinish = block.timestamp.add(rewardsDuration).to40(); } function notifyRewardAmount(address _rewardsToken, uint256 _reward) external gacPausable updateReward(address(0)) { require(rewardDistributors[_rewardsToken][msg.sender]); require(_reward > 0, "No reward"); _notifyReward(_rewardsToken, _reward); // handle the transfer of reward tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the _reward amount IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); emit RewardAdded(_rewardsToken, _reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner gacPausable { require( _tokenAddress != address(stakingToken), "Cannot withdraw staking token" ); require( rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token" ); IERC20Upgradeable(_tokenAddress).safeTransfer(owner(), _tokenAmount); emit Recovered(_tokenAddress, _tokenAmount); } /* ========== MODIFIERS ========== */ modifier updateReward(address _account) { { //stack too deep Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < rewardTokens.length; i++) { address token = rewardTokens[i]; rewardData[token].rewardPerTokenStored = _rewardPerToken(token) .to208(); rewardData[token].lastUpdateTime = _lastTimeRewardApplicable( rewardData[token].periodFinish ).to40(); if (_account != address(0)) { //check if reward is boostable or not. use boosted or locked balance accordingly rewards[_account][token] = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); userRewardPerTokenPaid[_account][token] = rewardData[token] .rewardPerTokenStored; } } } _; } /* ========== EVENTS ========== */ event RewardAdded(address indexed _token, uint256 _reward); event Staked( address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount ); event Withdrawn(address indexed _user, uint256 _amount, bool _relocked); event KickReward( address indexed _user, address indexed _kicked, uint256 _reward ); event RewardPaid( address indexed _user, address indexed _rewardsToken, uint256 _reward ); event Recovered(address _token, uint256 _amount); }
mappings for balance data
mapping(address => Balances) public balances;
1,374,681
[ 1, 4625, 348, 7953, 560, 30, 7990, 364, 11013, 501, 2, 0, 0, 0, 0, 0, 0, 0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, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x3e6d34F22878A10b8F49f4ba8B9d42cBc2fF0037/sources/EtherCollateralsUSD.sol
Get the loan from storage
function timeSinceInterestAccrualOnLoan(address _account, uint256 _loanID) external view returns (uint256) { PynthLoanStruct memory pynthLoan = _getLoanFromStorage(_account, _loanID); return _timeSinceInterestAccrual(pynthLoan); }
3,308,167
[ 1, 4625, 348, 7953, 560, 30, 225, 968, 326, 28183, 628, 2502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 813, 9673, 29281, 8973, 86, 1462, 1398, 1504, 304, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 383, 304, 734, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 453, 878, 451, 1504, 304, 3823, 3778, 293, 878, 451, 1504, 304, 273, 389, 588, 1504, 304, 1265, 3245, 24899, 4631, 16, 389, 383, 304, 734, 1769, 203, 203, 3639, 327, 389, 957, 9673, 29281, 8973, 86, 1462, 12, 84, 878, 451, 1504, 304, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x63ca16Ba5E3d1f3E427de27578A12C6429CE9c9a/sources/contracts/trove-factory.sol
* @dev returns fee from redeeming the amount/
function getRedemptionFeeRatio(address _trove) public view override returns (uint256) { return feeRecipient.getRedemptionFeeRatio(ITrove(_trove).collateralization(), ITrove(_trove).mcr()); }
5,672,515
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 1135, 14036, 628, 283, 24903, 310, 326, 3844, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5561, 19117, 375, 14667, 8541, 12, 2867, 389, 88, 303, 537, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 14036, 18241, 18, 588, 426, 19117, 375, 14667, 8541, 12, 1285, 303, 537, 24899, 88, 303, 537, 2934, 12910, 2045, 287, 1588, 9334, 24142, 303, 537, 24899, 88, 303, 537, 2934, 81, 3353, 10663, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.22; contract Voting { // Number of blocks to challenge this block (10 minutes, 5 blocks per minute) uint constant private NUM_BLOCKS_TO_LOCK = 10 * 5; struct Stake { address staker; uint256 stake; } struct Value { string value; uint totalStake; uint numStakes; mapping (address => uint) ids; // Sender address -> stakeId mapping (uint => Stake) stakes; // stakeId -> Sender address, total staked } struct MultiValue { uint startingBlockIndex; uint lockingBlockIndex; bool isLocked; uint topValueId; // Id of top value. uint numValues; mapping (string => uint) ids; // value to valueId mapping (uint => Value) values; } mapping (address => uint256) private fees; mapping (string => MultiValue) private store; function lockMultiValue(MultiValue storage multiValue) private { multiValue.isLocked = true; // TODO: Distribute stake } function getMultiValue(string _key) private returns (MultiValue storage) { MultiValue storage multiValue = store[_key]; if (multiValue.numValues == 0) { // new key return multiValue; } if (block.number >= multiValue.lockingBlockIndex) { lockMultiValue(multiValue); } return multiValue; } function put(string _key, string _value) public payable returns (bool) { require(msg.value > 0, "You need to stake money bro"); // require(_key.length > 0, "Key can't be empty string"); MultiValue storage multiValue = getMultiValue(_key); require(!multiValue.isLocked, "Can't use put on the locked key"); if (multiValue.numValues == 0) { // new key multiValue.startingBlockIndex = block.number; multiValue.lockingBlockIndex = block.number + NUM_BLOCKS_TO_LOCK; } uint valueId = multiValue.ids[_value]; if (valueId == 0) { // new value valueId = multiValue.numValues++; multiValue.ids[_value] = valueId; multiValue.values[valueId].value = _value; } Value storage value = multiValue.values[valueId]; value.totalStake += msg.value; uint stakeId = value.ids[msg.sender]; if (stakeId == 0) { stakeId = value.numStakes++; value.ids[msg.sender] = stakeId; value.stakes[stakeId].staker = msg.sender; } value.stakes[stakeId].stake += msg.value; if (value.totalStake > multiValue.values[multiValue.topValueId].totalStake) { multiValue.topValueId = valueId; } return true; } function get(string _key) public returns (string value, bool isLocked) { // TODO: Figure out fees split MultiValue storage multiValue = getMultiValue(_key); if (multiValue.numValues > 0) { value = multiValue.values[multiValue.topValueId].value; isLocked = multiValue.isLocked; } emit GetEvent(_key, value, isLocked); } event GetEvent(string key, string value, bool isLocked); }
Sender address -> stakeId
mapping (address => uint) ids;
5,409,297
[ 1, 4625, 348, 7953, 560, 30, 225, 15044, 1758, 317, 384, 911, 548, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 261, 2867, 516, 2254, 13, 3258, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; struct Purchase { uint256 buyAmount; uint256 transferredAmount; uint256 purchaseBlock; } mapping(address => uint256) balances; mapping(address => Purchase[]) public presaleInvestors; mapping(address => uint256) public mainSaleInvestors; uint256 totalSupply_; uint256 public secondsPerBlock = 147; // change to 14 uint256 public startLockUpSec = 3888000; // 45 days => 3888000 secs uint256 public secondsPerMonth = 2592000; // 30 days => 2592000 secs uint256 public percentagePerMonth = 10; function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; } else if (presaleInvestors[senderAdr][0].purchaseBlock > block.number.sub(startLockUpSec.div(secondsPerBlock).mul(10))) { canTransfer = 0; } else { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); } else { break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } } else { continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; } else { revert(); } } else { if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; } else { revert(); } } if (currentTokens != 0) { revert(); } } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0); require(_value <= balances[msg.sender]); require(_checkLockUp(msg.sender) >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); cleanTokensAmount(msg.sender, _value); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure require(_checkLockUp(_who) >= _value); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); cleanTokensAmount(_who, _value); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BurnableToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value > 0); require(_value <= allowed[_from][msg.sender]); require(_checkLockUp(_from) >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); cleanTokensAmount(_from, _value); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract WiredToken is MintableToken { string public constant name = "Wired Token"; string public constant symbol = "WRD"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 410000000000000000000; // 10^28 address public agent; uint256 public distributeAmount = 41000000000000000000; uint256 public mulbonus = 1000; uint256 public divbonus = 10000000000; bool public presalePart = true; modifier onlyAgent() { require(msg.sender == owner || msg.sender == agent); _; } function WiredToken() public { totalSupply_ = INITIAL_SUPPLY; balances[address(this)] = INITIAL_SUPPLY; mainSaleInvestors[address(this)] = INITIAL_SUPPLY; agent = msg.sender; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) external onlyAgent { require(amount > 0 && addresses.length > 0); uint256 amounts = amount.mul(100000000); uint256 totalAmount = amounts.mul(addresses.length); require(balances[address(this)] >= totalAmount); for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != 0x0); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); mainSaleInvestors[addresses[i]] = mainSaleInvestors[addresses[i]].add(amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function distributeAirdropMulti(address[] addresses, uint256[] amount) external onlyAgent { require(addresses.length > 0 && addresses.length == amount.length); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++) { require(amount[i] > 0 && addresses[i] != 0x0); uint256 amounts = amount[i].mul(100000000); totalAmount = totalAmount.add(amounts); require(balances[address(this)] >= totalAmount); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); mainSaleInvestors[addresses[i]] = mainSaleInvestors[addresses[i]].add(amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function distributeAirdropMultiPresale(address[] addresses, uint256[] amount, uint256[] blocks) external onlyAgent { require(addresses.length > 0 && addresses.length == amount.length); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++) { require(amount[i] > 0 && addresses[i] != 0x0); uint256 amounts = amount[i].mul(100000000); totalAmount = totalAmount.add(amounts); require(balances[address(this)] >= totalAmount); presaleInvestors[addresses[i]].push(Purchase(amounts, 0, blocks[i])); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function setDistributeAmount(uint256 _unitAmount) onlyOwner external { distributeAmount = _unitAmount; } function setMulBonus(uint256 _mulbonus) onlyOwner external { mulbonus = _mulbonus; } function setDivBonus(uint256 _divbonus) onlyOwner external { divbonus = _divbonus; } function setNewAgent(address _agent) external onlyOwner { require(agent != address(0)); agent = _agent; } function changeTime(uint256 _time) external onlyOwner { secondsPerBlock = _time; } function transferFund() external onlyOwner { owner.transfer(address(this).balance); } function transferTokens(uint256 amount) external onlyOwner { require(balances[address(this)] > 0); balances[msg.sender] = balances[msg.sender].add(amount.mul(100000000)); balances[address(this)] = balances[address(this)].sub(amount.mul(100000000)); emit Transfer(address(this), msg.sender, balances[address(this)]); mainSaleInvestors[msg.sender] = mainSaleInvestors[msg.sender].add(amount.mul(100000000)); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(amount.mul(100000000)); } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn&#39;t work */ function buy(address buyer) payable public { require(msg.value > 10000000000000 && distributeAmount > 0 && balances[address(this)] > distributeAmount); uint256 amount = msg.value.mul(mulbonus).div(divbonus); balances[buyer] = balances[buyer].add(amount); emit Transfer(address(this), buyer, amount); if (presalePart) { presaleInvestors[buyer].push(Purchase(amount, 0, block.number)); } else { mainSaleInvestors[buyer] = mainSaleInvestors[buyer].add(amount); } mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(amount); balances[address(this)] = balances[address(this)].sub(amount); distributeAmount = distributeAmount.sub(amount); } /** * @dev fallback function */ function() payable public { buy(msg.sender); } }
30 days => 2592000 secs
uint256 public secondsPerMonth = 2592000;
2,370,038
[ 1, 4625, 348, 7953, 560, 30, 225, 5196, 4681, 516, 576, 6162, 17172, 18043, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 3974, 2173, 5445, 273, 576, 6162, 17172, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xbF243A78aBa2A95674E7787029b2b16B15ca7d8E/sources/MatrixBot.sol
stable then open for swapping Anti-bot and anti-whale mappings and variables exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract MatrixBot is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public revShareWallet; address public teamWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public blacklistRenounced = false; mapping(address => bool) blacklisted; uint256 public buyTotalFees; uint256 public buyRevShareFee; uint256 public buyLiquidityFee; uint256 public buyTeamFee; uint256 public sellTotalFees; uint256 public sellRevShareFee; uint256 public sellLiquidityFee; uint256 public sellTeamFee; uint256 public tokensForRevShare; uint256 public tokensForLiquidity; uint256 public tokensForTeam; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event revShareWalletUpdated( address indexed newWallet, address indexed oldWallet ); event teamWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("MatrixBot", "MTXBOT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyRevShareFee = 2; uint256 _buyLiquidityFee = 1; uint256 _buyTeamFee = 2; uint256 _sellRevShareFee = 2; uint256 _sellLiquidityFee = 1; uint256 _sellTeamFee = 2; uint256 totalSupply = 100_000_000 * 1e18; buyRevShareFee = _buyRevShareFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee; sellRevShareFee = _sellRevShareFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.5%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 10) / 1000) / 1e18, "Cannot set maxWallet lower than 1.0%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _revShareFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { buyRevShareFee = _revShareFee; buyLiquidityFee = _liquidityFee; buyTeamFee = _teamFee; buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee; require(buyTotalFees <= 5, "Buy fees must be <= 5."); } function updateSellFees( uint256 _revShareFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { sellRevShareFee = _revShareFee; sellLiquidityFee = _liquidityFee; sellTeamFee = _teamFee; sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee; require(sellTotalFees <= 5, "Sell fees must be <= 5."); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateRevShareWallet(address newRevShareWallet) external onlyOwner { emit revShareWalletUpdated(newRevShareWallet, revShareWallet); revShareWallet = newRevShareWallet; } function updateTeamWallet(address newWallet) external onlyOwner { emit teamWalletUpdated(newWallet, teamWallet); teamWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function isBlacklisted(address account) public view returns (bool) { return blacklisted[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedMaxTransactionAmount[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max balance of wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, owner(), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam; tokensForLiquidity = 0; tokensForRevShare = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam; tokensForLiquidity = 0; tokensForRevShare = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam; tokensForLiquidity = 0; tokensForRevShare = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / (success, ) = address(teamWallet).call{value: ethForTeam}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2)); uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam; tokensForLiquidity = 0; tokensForRevShare = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } (success, ) = address(revShareWallet).call{value: address(this).balance}(""); function withdrawStuckMatrixBot() external onlyOwner { uint256 balance = IERC20(address(this)).balanceOf(address(this)); IERC20(address(this)).transfer(msg.sender, balance); payable(msg.sender).transfer(address(this).balance); } function withdrawStuckToken(address _token, address _to) external onlyOwner { require(_token != address(0), "_token address cannot be 0"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); IERC20(_token).transfer(_to, _contractBalance); } function withdrawStuckEth(address toAddr) external onlyOwner { (bool success, ) = toAddr.call{ value: address(this).balance } (""); require(success); } function withdrawStuckEth(address toAddr) external onlyOwner { (bool success, ) = toAddr.call{ value: address(this).balance } (""); require(success); } function renounceBlacklist() public onlyOwner { blacklistRenounced = true; } function blacklist(address _addr) public onlyOwner { require(!blacklistRenounced, "Team has revoked blacklist rights"); require( _addr != address(uniswapV2Pair) && _addr != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "Cannot blacklist token's v2 router or v2 pool." ); blacklisted[_addr] = true; } function blacklistLiquidityPool(address lpAddress) public onlyOwner { require(!blacklistRenounced, "Team has revoked blacklist rights"); require( lpAddress != address(uniswapV2Pair) && lpAddress != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "Cannot blacklist token's v2 router or v2 pool." ); blacklisted[lpAddress] = true; } function unblacklist(address _addr) public onlyOwner { blacklisted[_addr] = false; } }
3,886,506
[ 1, 4625, 348, 7953, 560, 30, 225, 14114, 1508, 1696, 364, 7720, 1382, 18830, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 380, 869, 14, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7298, 6522, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 377, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 5588, 9535, 16936, 31, 203, 565, 1758, 1071, 5927, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 203, 565, 1426, 1071, 11709, 16290, 27373, 273, 629, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 25350, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 10070, 9535, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8689, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 10070, 9535, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 8689, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 2430, 1290, 10070, 9535, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 48, 18988, 24237, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 8689, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2954, 281, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 291, 16461, 2747, 3342, 6275, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 18472, 690, 3882, 278, 12373, 10409, 31, 203, 203, 565, 871, 2315, 984, 291, 91, 438, 58, 22, 8259, 12, 203, 3639, 1758, 8808, 394, 1887, 16, 203, 3639, 1758, 8808, 1592, 1887, 203, 565, 11272, 203, 203, 565, 871, 20760, 1265, 2954, 281, 12, 2867, 8808, 2236, 16, 1426, 353, 16461, 1769, 203, 203, 565, 871, 1000, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 8808, 3082, 16, 1426, 8808, 460, 1769, 203, 203, 565, 871, 5588, 9535, 16936, 7381, 12, 203, 3639, 1758, 8808, 394, 16936, 16, 203, 3639, 1758, 8808, 1592, 16936, 203, 565, 11272, 203, 203, 565, 871, 5927, 16936, 7381, 12, 203, 3639, 1758, 8808, 394, 16936, 16, 203, 3639, 1758, 8808, 1592, 16936, 203, 565, 11272, 203, 203, 565, 871, 12738, 1876, 48, 18988, 1164, 12, 203, 3639, 2254, 5034, 2430, 12521, 1845, 16, 203, 3639, 2254, 5034, 13750, 8872, 16, 203, 3639, 2254, 5034, 2430, 5952, 48, 18988, 24237, 203, 565, 11272, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 4635, 6522, 3113, 315, 6152, 60, 38, 1974, 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, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 10070, 9535, 14667, 273, 576, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 404, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8689, 14667, 273, 576, 31, 203, 203, 3639, 2254, 5034, 389, 87, 1165, 10070, 9535, 14667, 273, 576, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 404, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 8689, 14667, 273, 576, 31, 203, 540, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 2130, 67, 3784, 67, 3784, 380, 404, 73, 2643, 31, 203, 203, 203, 3639, 30143, 10070, 9535, 14667, 273, 389, 70, 9835, 10070, 9535, 14667, 31, 203, 3639, 30143, 48, 18988, 24237, 14667, 273, 389, 70, 9835, 48, 18988, 24237, 14667, 31, 203, 3639, 30143, 8689, 14667, 273, 389, 70, 9835, 8689, 14667, 31, 203, 3639, 30143, 5269, 2954, 281, 273, 30143, 10070, 9535, 14667, 397, 30143, 48, 18988, 24237, 14667, 397, 30143, 8689, 14667, 31, 203, 203, 3639, 357, 80, 10070, 9535, 14667, 273, 389, 87, 1165, 10070, 9535, 14667, 31, 203, 3639, 357, 80, 48, 18988, 24237, 14667, 273, 389, 87, 1165, 48, 18988, 24237, 14667, 31, 203, 3639, 357, 80, 8689, 14667, 273, 389, 87, 1165, 8689, 14667, 31, 203, 3639, 357, 80, 5269, 2954, 281, 273, 357, 80, 10070, 9535, 14667, 397, 357, 80, 48, 18988, 24237, 14667, 397, 357, 80, 8689, 14667, 31, 203, 203, 203, 3639, 4433, 1265, 2954, 281, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 20, 92, 22097, 3631, 638, 1769, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../../BdStable/BDStable.sol"; import "../../Oracle/ICryptoPairOracle.sol"; import "./BdPoolLibrary.sol"; import "../../Utils/IWETH.sol"; contract BdStablePool is OwnableUpgradeable { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 private BDX; IWETH private NativeTokenWrapper; IERC20 public collateral_token; BDStable public BDSTABLE; ICryptoPairOracle public collatWEthOracle; bool public is_collateral_wrapping_native_token; uint256 private missing_decimals; // Number of decimals needed to get to 18 address private weth_address; mapping(address => uint256) public redeemBDXBalances; mapping(address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; mapping(address => uint256) public lastRedeemed; // AccessControl state variables bool public mintPaused; bool public redeemPaused; bool public recollateralizePaused; bool public buyBackPaused; bool public collateralPricePaused; bool public recollateralizeOnlyForOwner; bool public buybackOnlyForOwner; uint256 public minting_fee; //d12 uint256 public redemption_fee; //d12 uint256 public buyback_fee; //d12 uint256 public recollat_fee; //d12 // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling; // d18 // Stores price of the collateral, if price is paused uint256 public pausedPrice; // Bonus rate on BDX minted during recollateralizeBdStable(); 12 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate; // d12 // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay; /* ========== MODIFIERS ========== */ modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ function initialize( address _bdstable_contract_address, address _bdx_contract_address, address _collateral_address, uint256 _collateral_decimals, bool _is_collateral_wrapping_native_token ) external initializer { require(_bdstable_contract_address != address(0), "BdStable address cannot be 0"); require(_bdx_contract_address != address(0), "BDX address cannot be 0"); require(_collateral_address != address(0), "Collateral address cannot be 0"); __Ownable_init(); BDSTABLE = BDStable(_bdstable_contract_address); BDX = IERC20(_bdx_contract_address); if (_is_collateral_wrapping_native_token) { NativeTokenWrapper = IWETH(_collateral_address); } collateral_token = IERC20(_collateral_address); missing_decimals = uint256(18) - _collateral_decimals; is_collateral_wrapping_native_token = _is_collateral_wrapping_native_token; pool_ceiling = 1e36; // d18 bonus_rate = 7500000000; // d12 0.75% redemption_delay = 1; minting_fee = 3000000000; // d12 0.3% redemption_fee = 3000000000; // d12 0.3% recollateralizeOnlyForOwner = false; buybackOnlyForOwner = true; } /* ========== VIEWS ========== */ // Returns the price of the pool collateral in fiat function getCollateralPrice_d12() public view returns (uint256) { if (collateralPricePaused == true) { return pausedPrice; } else { uint256 eth_fiat_price_d12 = BDSTABLE.weth_fiat_price(); uint256 collat_eth_price = collatWEthOracle.consult(weth_address, BdPoolLibrary.PRICE_PRECISION); return (eth_fiat_price_d12 * BdPoolLibrary.PRICE_PRECISION) / collat_eth_price; } } // Returns fiat value of collateral held in this BdStable pool function collatFiatBalance() external view returns (uint256) { //Expressed in collateral token decimals if (collateralPricePaused == true) { return ((collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral) * (10**missing_decimals) * pausedPrice) / BdPoolLibrary.PRICE_PRECISION; } else { return ((collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral) * (10**missing_decimals) * getCollateralPrice_d12()) / BdPoolLibrary.PRICE_PRECISION; } } /* ========== PUBLIC FUNCTIONS ========== */ function updateOraclesIfNeeded() public { BDSTABLE.updateOraclesIfNeeded(); if (collatWEthOracle.shouldUpdateOracle()) { collatWEthOracle.updateOracle(); } } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalBdStable( uint256 collateral_amount_in_max, uint256 bdx_in_max, uint256 bdStable_out_min, bool useNativeToken ) external payable notMintPaused { if (useNativeToken) { require(is_collateral_wrapping_native_token, "Pool doesn't support native token"); require(msg.value == collateral_amount_in_max, "msg.value and collateral_amount_in_max do not match"); } updateOraclesIfNeeded(); uint256 bdx_price = BDSTABLE.BDX_price_d12(); uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12(); if (global_collateral_ratio_d12 == 0) { collateral_amount_in_max = 0; } else if (global_collateral_ratio_d12 == BdPoolLibrary.COLLATERAL_RATIO_MAX) { bdx_in_max = 0; } require( (collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral + collateral_amount_in_max) <= pool_ceiling, "Pool ceiling reached, no more BdStable can be minted with this collateral" ); uint256 collateral_amount_in_max_d18 = collateral_amount_in_max * (10**missing_decimals); uint256 mint_amount; uint256 bdx_needed; if (global_collateral_ratio_d12 == 0) { mint_amount = BdPoolLibrary.calcMintAlgorithmicBD(bdx_price, bdx_in_max); bdx_needed = bdx_in_max; } else if (global_collateral_ratio_d12 == 1) { mint_amount = BdPoolLibrary.calcMint1t1BD(getCollateralPrice_d12(), collateral_amount_in_max_d18); bdx_needed = 0; } else { (mint_amount, bdx_needed) = BdPoolLibrary.calcMintFractionalBD( bdx_price, getCollateralPrice_d12(), collateral_amount_in_max_d18, global_collateral_ratio_d12 ); } mint_amount = (mint_amount * (uint256(BdPoolLibrary.PRICE_PRECISION) - minting_fee)) / BdPoolLibrary.PRICE_PRECISION; require(bdStable_out_min <= mint_amount, "Slippage limit reached"); require(bdx_needed <= bdx_in_max, "Not enough BDX inputted"); BDSTABLE.refreshCollateralRatio(); if (bdx_needed > 0) { BDX.safeTransferFrom(msg.sender, address(BDSTABLE), bdx_needed); } if (collateral_amount_in_max > 0) { if (useNativeToken) { NativeTokenWrapper.deposit{value: collateral_amount_in_max}(); } else { collateral_token.safeTransferFrom(msg.sender, address(this), collateral_amount_in_max); } } BDSTABLE.pool_mint(msg.sender, mint_amount); } // Will fail if fully collateralized or algorithmic // Redeem BDSTABLE for collateral and BDX. > 0% and < 100% collateral-backed function redeemFractionalBdStable( uint256 BdStable_amount, uint256 BDX_out_min, uint256 COLLATERAL_out_min ) external notRedeemPaused { updateOraclesIfNeeded(); uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12(); uint256 effective_global_collateral_ratio_d12 = BDSTABLE.effective_global_collateral_ratio_d12(); uint256 cr_d12 = effective_global_collateral_ratio_d12 < global_collateral_ratio_d12 ? effective_global_collateral_ratio_d12 : global_collateral_ratio_d12; uint256 BdStable_amount_post_fee = (BdStable_amount * (uint256(BdPoolLibrary.PRICE_PRECISION) - redemption_fee)) / BdPoolLibrary.PRICE_PRECISION; uint256 bdx_fiat_value_d18 = BdStable_amount_post_fee - ((BdStable_amount_post_fee * cr_d12) / BdPoolLibrary.PRICE_PRECISION); uint256 bdx_amount = (bdx_fiat_value_d18 * BdPoolLibrary.PRICE_PRECISION) / BDSTABLE.BDX_price_d12(); uint256 bdx_coverage_ratio = BDSTABLE.get_effective_bdx_coverage_ratio(); bdx_amount = (bdx_amount * bdx_coverage_ratio) / BdPoolLibrary.COLLATERAL_RATIO_PRECISION; // Need to adjust for decimals of collateral uint256 BdStable_amount_precision = BdStable_amount_post_fee / (10**missing_decimals); uint256 collateral_fiat_value = (BdStable_amount_precision * cr_d12) / BdPoolLibrary.PRICE_PRECISION; uint256 collateral_needed = (collateral_fiat_value * BdPoolLibrary.PRICE_PRECISION) / getCollateralPrice_d12(); require(collateral_needed <= collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral, "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached [collateral]"); require(BDX_out_min <= bdx_amount, "Slippage limit reached [BDX]"); require(BDSTABLE.canLegallyRedeem(msg.sender), "Cannot legally redeem"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender] + collateral_needed; unclaimedPoolCollateral = unclaimedPoolCollateral + collateral_needed; BDSTABLE.refreshCollateralRatio(); if (bdx_amount > 0) { require(BDSTABLE.canLegallyRedeem(msg.sender), "Cannot legally redeem"); redeemBDXBalances[msg.sender] = redeemBDXBalances[msg.sender] + bdx_amount; BDSTABLE.pool_claim_bdx(bdx_amount); } lastRedeemed[msg.sender] = block.number; // Move all external functions to the end BDSTABLE.pool_burn_from(msg.sender, BdStable_amount); } // After a redemption happens, transfer the newly minted BDX and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out BdStable/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption(bool useNativeToken) external { require((lastRedeemed[msg.sender] + redemption_delay) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendBDX = false; bool sendCollateral = false; uint256 BDXAmount; uint256 CollateralAmount; // Use Checks-Effects-Interactions pattern if (redeemBDXBalances[msg.sender] > 0) { BDXAmount = redeemBDXBalances[msg.sender]; redeemBDXBalances[msg.sender] = 0; sendBDX = true; } if (redeemCollateralBalances[msg.sender] > 0) { CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral - CollateralAmount; sendCollateral = true; } if (sendBDX == true) { BDSTABLE.pool_transfer_claimed_bdx(msg.sender, BDXAmount); } if (sendCollateral == true) { if (useNativeToken) { NativeTokenWrapper.withdraw(CollateralAmount); safeTransferETH(msg.sender, CollateralAmount); } else { collateral_token.safeTransfer(msg.sender, CollateralAmount); } } } // When the protocol is recollateralizing, we need to give a discount of BDX to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get BDX for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of BDX + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra BDX value from the bonus rate as an arb opportunity function recollateralizeBdStable( uint256 collateral_amount, uint256 BDX_out_min, bool useNativeToken ) external payable { require(recollateralizePaused == false, "Recollateralize is paused"); if (recollateralizeOnlyForOwner) { require(msg.sender == owner(), "Currently only owner can recollateralize"); } if (useNativeToken) { require(is_collateral_wrapping_native_token, "Pool doesn't support native token"); require(msg.value == collateral_amount, "msg.value and collateral_amount do not match"); } updateOraclesIfNeeded(); uint256 collateral_amount_d18 = collateral_amount * (10**missing_decimals); uint256 bdx_price = BDSTABLE.BDX_price_d12(); uint256 bdStable_total_supply = BDSTABLE.totalSupply(); uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12(); uint256 global_collat_value = BDSTABLE.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = BdPoolLibrary.calcRecollateralizeBdStableInner( collateral_amount_d18, getCollateralPrice_d12(), global_collat_value, bdStable_total_supply, global_collateral_ratio_d12 ); uint256 collateral_units_precision = collateral_units / (10**missing_decimals); uint256 bdx_paid_back = (amount_to_recollat * (uint256(BdPoolLibrary.PRICE_PRECISION) + bonus_rate - recollat_fee)) / bdx_price; uint256 bdx_coverage_ratio = BDSTABLE.get_effective_bdx_coverage_ratio(); bdx_paid_back = (bdx_paid_back * bdx_coverage_ratio) / BdPoolLibrary.COLLATERAL_RATIO_PRECISION; require(BDX_out_min <= bdx_paid_back, "Slippage limit reached"); BDSTABLE.refreshCollateralRatio(); if (useNativeToken) { // no need to check collateral_units_precision, it's <= then collateral_amount NativeTokenWrapper.deposit{value: collateral_units_precision}(); // refund remaining native token, if any left if (msg.value > collateral_units_precision) { safeTransferETH(msg.sender, msg.value - collateral_units_precision); } } else { collateral_token.safeTransferFrom(msg.sender, address(this), collateral_units_precision); } if (bdx_paid_back > 0) { BDSTABLE.transfer_bdx(msg.sender, bdx_paid_back); } emit Recollateralized(collateral_units_precision, bdx_paid_back); } // Function can be called by an BDX holder to have the protocol buy back BDX with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackBDX( uint256 BDX_amount, uint256 COLLATERAL_out_min, bool useNativeToken ) external { require(buyBackPaused == false, "Buyback is paused"); if (buybackOnlyForOwner) { require(msg.sender == owner(), "Currently only owner can buyback"); } updateOraclesIfNeeded(); uint256 bdx_price = BDSTABLE.BDX_price_d12(); uint256 collateral_equivalent_d18 = (BdPoolLibrary.calcBuyBackBDX( BDSTABLE.availableExcessCollatDV(), bdx_price, getCollateralPrice_d12(), BDX_amount ) * (uint256(BdPoolLibrary.PRICE_PRECISION) - buyback_fee)) / BdPoolLibrary.PRICE_PRECISION; uint256 collateral_precision = collateral_equivalent_d18 / (10**missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Take bdx from sender BDX.safeTransferFrom(msg.sender, address(BDSTABLE), BDX_amount); if (useNativeToken) { // Give the sender their desired collateral NativeTokenWrapper.withdraw(collateral_precision); safeTransferETH(msg.sender, collateral_precision); } else { // Give the sender their desired collateral collateral_token.safeTransfer(msg.sender, collateral_precision); } emit BoughtBack(BDX_amount, collateral_precision); } receive() external payable { require(msg.sender == address(NativeTokenWrapper), "Only native token wrapper allowed to send native token"); } /* ========== RESTRICTED FUNCTIONS ========== */ function setCollatWETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyOwner { require(_collateral_weth_oracle_address != address(0), "Oracle cannot be set to the zero address"); require(_weth_address != address(0), "WETH cannot be set to the zero address"); collatWEthOracle = ICryptoPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; emit CollateralWethOracleSet(_collateral_weth_oracle_address, _weth_address); } function toggleMintingPaused() external onlyOwner { mintPaused = !mintPaused; emit MintingPausedToggled(mintPaused); } function toggleRedeemingPaused() external onlyOwner { redeemPaused = !redeemPaused; emit RedeemingPausedToggled(redeemPaused); } function toggleRecollateralizePaused() external onlyOwner { recollateralizePaused = !recollateralizePaused; emit RecollateralizePausedToggled(recollateralizePaused); } function toggleBuybackPaused() external onlyOwner { buyBackPaused = !buyBackPaused; emit BuybackPausedToggled(buyBackPaused); } function toggleBuybackOnlyForOwner() external onlyOwner { buybackOnlyForOwner = !buybackOnlyForOwner; emit BuybackOnlyForOwnerToggled(buybackOnlyForOwner); } function toggleRecollateralizeOnlyForOwner() external onlyOwner { recollateralizeOnlyForOwner = !recollateralizeOnlyForOwner; emit RecollateralizeOnlyForOwnerToggled(recollateralizeOnlyForOwner); } function toggleCollateralPricePaused(uint256 _new_price) external onlyOwner { // If pausing, set paused price; else if unpausing, clear pausedPrice if (collateralPricePaused == false) { pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; emit CollateralPriceToggled(collateralPricePaused); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters( uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee ) external onlyOwner { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "ETH transfer failed"); } /* ========== EVENTS ========== */ event PoolParametersSet( uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee ); event MintingPausedToggled(bool toggled); event RedeemingPausedToggled(bool toggled); event RecollateralizePausedToggled(bool toggled); event BuybackPausedToggled(bool toggled); event CollateralPriceToggled(bool toggled); event CollateralWethOracleSet(address indexed collateral_weth_oracle_address, address indexed weth_address); event RecollateralizeOnlyForOwnerToggled(bool recollateralizeOnlyForOwner); event BuybackOnlyForOwnerToggled(bool buybackOnlyForOwner); event Recollateralized(uint256 indexed collateral_amount_paid, uint256 indexed bdx_paid_back); event BoughtBack(uint256 indexed bdx_amount_paid, uint256 indexed collateral_paid_back); }
After a redemption happens, transfer the newly minted BDX and owed collateral from this pool contract to the user. Redemption is split into two functions to prevent flash loans from being able to take out BdStable/collateral from the system, use an AMM to trade the new price, and then mint back into the system. Use Checks-Effects-Interactions pattern
function collectRedemption(bool useNativeToken) external { require((lastRedeemed[msg.sender] + redemption_delay) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendBDX = false; bool sendCollateral = false; uint256 BDXAmount; uint256 CollateralAmount; if (redeemBDXBalances[msg.sender] > 0) { BDXAmount = redeemBDXBalances[msg.sender]; redeemBDXBalances[msg.sender] = 0; sendBDX = true; } if (redeemCollateralBalances[msg.sender] > 0) { CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral - CollateralAmount; sendCollateral = true; } if (sendBDX == true) { BDSTABLE.pool_transfer_claimed_bdx(msg.sender, BDXAmount); } if (sendCollateral == true) { if (useNativeToken) { NativeTokenWrapper.withdraw(CollateralAmount); safeTransferETH(msg.sender, CollateralAmount); collateral_token.safeTransfer(msg.sender, CollateralAmount); } } }
13,085,549
[ 1, 4625, 348, 7953, 560, 30, 225, 7360, 279, 283, 19117, 375, 10555, 16, 7412, 326, 10894, 312, 474, 329, 605, 28826, 471, 2523, 329, 4508, 2045, 287, 628, 333, 2845, 6835, 358, 326, 729, 18, 868, 19117, 375, 353, 1416, 1368, 2795, 4186, 358, 5309, 9563, 437, 634, 628, 3832, 7752, 358, 4862, 596, 605, 72, 30915, 19, 12910, 2045, 287, 628, 326, 2619, 16, 999, 392, 432, 8206, 358, 18542, 326, 394, 6205, 16, 471, 1508, 312, 474, 1473, 1368, 326, 2619, 18, 2672, 13074, 17, 29013, 17, 2465, 4905, 1936, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 426, 19117, 375, 12, 6430, 999, 9220, 1345, 13, 3903, 288, 203, 3639, 2583, 12443, 2722, 426, 24903, 329, 63, 3576, 18, 15330, 65, 397, 283, 19117, 375, 67, 10790, 13, 1648, 1203, 18, 2696, 16, 315, 10136, 2529, 364, 283, 19117, 375, 67, 10790, 4398, 1865, 30160, 283, 19117, 375, 8863, 203, 3639, 1426, 1366, 18096, 60, 273, 629, 31, 203, 3639, 1426, 1366, 13535, 2045, 287, 273, 629, 31, 203, 3639, 2254, 5034, 605, 28826, 6275, 31, 203, 3639, 2254, 5034, 17596, 2045, 287, 6275, 31, 203, 203, 3639, 309, 261, 266, 24903, 18096, 60, 38, 26488, 63, 3576, 18, 15330, 65, 405, 374, 13, 288, 203, 5411, 605, 28826, 6275, 273, 283, 24903, 18096, 60, 38, 26488, 63, 3576, 18, 15330, 15533, 203, 5411, 283, 24903, 18096, 60, 38, 26488, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 203, 5411, 1366, 18096, 60, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 266, 24903, 13535, 2045, 287, 38, 26488, 63, 3576, 18, 15330, 65, 405, 374, 13, 288, 203, 5411, 17596, 2045, 287, 6275, 273, 283, 24903, 13535, 2045, 287, 38, 26488, 63, 3576, 18, 15330, 15533, 203, 5411, 283, 24903, 13535, 2045, 287, 38, 26488, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 5411, 6301, 80, 4581, 329, 2864, 13535, 2045, 287, 273, 6301, 80, 4581, 329, 2864, 13535, 2045, 287, 300, 17596, 2045, 287, 6275, 31, 203, 203, 5411, 1366, 13535, 2045, 287, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 4661, 18096, 60, 422, 638, 13, 288, 203, 5411, 605, 40, 882, 2782, 18, 6011, 67, 13866, 67, 14784, 329, 67, 70, 13437, 12, 3576, 18, 15330, 16, 605, 28826, 6275, 1769, 203, 3639, 289, 203, 3639, 309, 261, 4661, 13535, 2045, 287, 422, 638, 13, 288, 203, 5411, 309, 261, 1202, 9220, 1345, 13, 288, 203, 7734, 16717, 1345, 3611, 18, 1918, 9446, 12, 13535, 2045, 287, 6275, 1769, 203, 7734, 4183, 5912, 1584, 44, 12, 3576, 18, 15330, 16, 17596, 2045, 287, 6275, 1769, 203, 7734, 4508, 2045, 287, 67, 2316, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 17596, 2045, 287, 6275, 1769, 203, 5411, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; // version of solidity compiler // create contract and name it. contract SimpleStorage { //unsigned integer ( a int higher than 0) uint storeData; // declare a function // set: will change the state of the variable // public: keyword allowing function to be accessible outside the contract function set(uint x) public { storeData = x; } // getting the values of the function // create a function to do so. // view: keyword that declares the function data to only be viewed function get() public view returns (uint) { return storeData; } }
getting the values of the function create a function to do so. view: keyword that declares the function data to only be viewed
function get() public view returns (uint) { return storeData; }
12,662,815
[ 1, 4625, 348, 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, 0 ]
[ 1, 565, 445, 336, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 1707, 751, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-03-26 */ /* 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.5.7; /** * @title ICore * @author Set Protocol * * The ICore Contract defines all the functions exposed in the Core through its * various extensions and is a light weight way to interact with the contract. */ interface ICore { /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address); /** * Return vault address. * * @return address vault address */ function vault() external view returns (address); /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address); /* * Returns if valid set * * @return bool Returns true if Set created through Core and isn't disabled */ function validSets(address) external view returns (bool); /* * Returns if valid module * * @return bool Returns true if valid module */ function validModules(address) external view returns (bool); /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool); /** * Exchanges components for Set Tokens * * @param _set Address of set to issue * @param _quantity Quantity of set to issue */ function issue( address _set, uint256 _quantity ) external; /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external; /** * Converts user's components into Set Tokens held directly in Vault instead of user's account * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeem( address _set, uint256 _quantity ) external; /** * Redeem Set token and return components to specified recipient. The components * are left in the vault * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens held in vault into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeemInVault( address _set, uint256 _quantity ) external; /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external; /** * Deposit multiple tokens to the vault. Quantities should be in the * order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Withdraw multiple tokens from the vault. Quantities should be in the * order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Deposit any quantity of tokens into the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external; /** * Withdraw a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external; /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external; /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); /** * Exposes internal function that deposits a quantity of tokens to the vault and attributes * the tokens respectively, to system modules. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposit * @param _token Address of token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that withdraws a quantity of tokens from the vault and * deattributes the tokens respectively, to system modules. * * @param _from Address to decredit for withdraw * @param _to Address to transfer tokens to * @param _token Address of token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that deposits multiple tokens to the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _owner, address _recipient, address _set, uint256 _quantity ) external; /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external; /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external; /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: set-protocol-contracts/contracts/core/lib/RebalancingLibrary.sol /* 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.5.7; /** * @title RebalancingLibrary * @author Set Protocol * * The RebalancingLibrary contains functions for facilitating the rebalancing process for * Rebalancing Set Tokens. Removes the old calculation functions * */ library RebalancingLibrary { /* ============ Enums ============ */ enum State { Default, Proposal, Rebalance, Drawdown } /* ============ Structs ============ */ struct AuctionPriceParameters { uint256 auctionStartTime; uint256 auctionTimeToPivot; uint256 auctionStartPrice; uint256 auctionPivotPrice; } struct BiddingParameters { uint256 minimumBid; uint256 remainingCurrentSets; uint256[] combinedCurrentUnits; uint256[] combinedNextSetUnits; address[] combinedTokenArray; } } // File: set-protocol-contracts/contracts/core/interfaces/IFeeCalculator.sol /* Copyright 2019 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.5.7; /** * @title IFeeCalculator * @author Set Protocol * */ interface IFeeCalculator { /* ============ External Functions ============ */ function initialize( bytes calldata _feeCalculatorData ) external; function getFee() external view returns(uint256); function updateAndGetFee() external returns(uint256); function adjustFee( bytes calldata _newFeeData ) external; } // File: set-protocol-contracts/contracts/core/interfaces/ISetToken.sol /* 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.5.7; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * Transfer token for a specified address * * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer( address to, uint256 value ) external; } // File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetToken.sol /* 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.5.7; /** * @title IRebalancingSetToken * @author Set Protocol * * The IRebalancingSetToken interface provides a light-weight, structured way to interact with the * RebalancingSetToken contract from another contract. */ interface IRebalancingSetToken { /* * Get the auction library contract used for the current rebalance * * @return address Address of auction library used in the upcoming auction */ function auctionLibrary() external view returns (address); /* * Get totalSupply of Rebalancing Set * * @return totalSupply */ function totalSupply() external view returns (uint256); /* * Get proposalTimeStamp of Rebalancing Set * * @return proposalTimeStamp */ function proposalStartTime() external view returns (uint256); /* * Get lastRebalanceTimestamp of Rebalancing Set * * @return lastRebalanceTimestamp */ function lastRebalanceTimestamp() external view returns (uint256); /* * Get rebalanceInterval of Rebalancing Set * * @return rebalanceInterval */ function rebalanceInterval() external view returns (uint256); /* * Get rebalanceState of Rebalancing Set * * @return RebalancingLibrary.State Current rebalance state of the RebalancingSetToken */ function rebalanceState() external view returns (RebalancingLibrary.State); /* * Get the starting amount of current SetToken for the current auction * * @return rebalanceState */ function startingCurrentSetAmount() external view returns (uint256); /** * Gets the balance of the specified address. * * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf( address owner ) external view returns (uint256); /** * Function used to set the terms of the next rebalance and start the proposal period * * @param _nextSet The Set to rebalance into * @param _auctionLibrary The library used to calculate the Dutch Auction price * @param _auctionTimeToPivot The amount of time for the auction to go ffrom start to pivot price * @param _auctionStartPrice The price to start the auction at * @param _auctionPivotPrice The price at which the price curve switches from linear to exponential */ function propose( address _nextSet, address _auctionLibrary, uint256 _auctionTimeToPivot, uint256 _auctionStartPrice, uint256 _auctionPivotPrice ) external; /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /** * Returns the address of the current base SetToken with the current allocation * * @return A address representing the base SetToken */ function currentSet() external view returns (address); /** * Returns the address of the next base SetToken with the post auction allocation * * @return address Address representing the base SetToken */ function nextSet() external view returns (address); /* * Get the unit shares of the rebalancing Set * * @return unitShares Unit Shares of the base Set */ function unitShares() external view returns (uint256); /* * Burn set token for given address. * Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory); /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArrayLength() external view returns (uint256); /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArray() external view returns (address[] memory); /* * Get failedAuctionWithdrawComponents of Rebalancing Set * * @return failedAuctionWithdrawComponents */ function getFailedAuctionWithdrawComponents() external view returns (address[] memory); /* * Get auctionPriceParameters for current auction * * @return uint256[4] AuctionPriceParameters for current rebalance auction */ function getAuctionPriceParameters() external view returns (uint256[] memory); /* * Get biddingParameters for current auction * * @return uint256[2] BiddingParameters for current rebalance auction */ function getBiddingParameters() external view returns (uint256[] memory); /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) external view returns (uint256[] memory, uint256[] memory); } // File: set-protocol-contracts/contracts/core/lib/Rebalance.sol /* Copyright 2019 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.5.7; /** * @title Rebalance * @author Set Protocol * * Types and functions for Rebalance-related data. */ library Rebalance { struct TokenFlow { address[] addresses; uint256[] inflow; uint256[] outflow; } function composeTokenFlow( address[] memory _addresses, uint256[] memory _inflow, uint256[] memory _outflow ) internal pure returns(TokenFlow memory) { return TokenFlow({addresses: _addresses, inflow: _inflow, outflow: _outflow }); } function decomposeTokenFlow(TokenFlow memory _tokenFlow) internal pure returns (address[] memory, uint256[] memory, uint256[] memory) { return (_tokenFlow.addresses, _tokenFlow.inflow, _tokenFlow.outflow); } function decomposeTokenFlowToBidPrice(TokenFlow memory _tokenFlow) internal pure returns (uint256[] memory, uint256[] memory) { return (_tokenFlow.inflow, _tokenFlow.outflow); } /** * Get token flows array of addresses, inflows and outflows * * @param _rebalancingSetToken The rebalancing Set Token instance * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses * @return inflowArray Array of amount of tokens inserted into system in bid * @return outflowArray Array of amount of tokens returned from system in bid */ function getTokenFlows( IRebalancingSetToken _rebalancingSetToken, uint256 _quantity ) internal view returns (address[] memory, uint256[] memory, uint256[] memory) { // Get token addresses address[] memory combinedTokenArray = _rebalancingSetToken.getCombinedTokenArray(); // Get inflow and outflow arrays for the given bid quantity ( uint256[] memory inflowArray, uint256[] memory outflowArray ) = _rebalancingSetToken.getBidPrice(_quantity); return (combinedTokenArray, inflowArray, outflowArray); } } // File: set-protocol-contracts/contracts/core/interfaces/ILiquidator.sol /* Copyright 2019 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.5.7; /** * @title ILiquidator * @author Set Protocol * */ interface ILiquidator { /* ============ External Functions ============ */ function startRebalance( ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity, bytes calldata _liquidatorData ) external; function getBidPrice( address _set, uint256 _quantity ) external view returns (Rebalance.TokenFlow memory); function placeBid( uint256 _quantity ) external returns (Rebalance.TokenFlow memory); function settleRebalance() external; function endFailedRebalance() external; // ---------------------------------------------------------------------- // Auction Price // ---------------------------------------------------------------------- function auctionPriceParameters(address _set) external view returns (RebalancingLibrary.AuctionPriceParameters memory); // ---------------------------------------------------------------------- // Auction // ---------------------------------------------------------------------- function hasRebalanceFailed(address _set) external view returns (bool); function minimumBid(address _set) external view returns (uint256); function startingCurrentSets(address _set) external view returns (uint256); function remainingCurrentSets(address _set) external view returns (uint256); function getCombinedCurrentSetUnits(address _set) external view returns (uint256[] memory); function getCombinedNextSetUnits(address _set) external view returns (uint256[] memory); function getCombinedTokenArray(address _set) external view returns (address[] memory); } // File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV2.sol /* Copyright 2019 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.5.7; /** * @title IRebalancingSetTokenV2 * @author Set Protocol * * The IRebalancingSetTokenV2 interface provides a light-weight, structured way to interact with the * RebalancingSetTokenV2 contract from another contract. */ interface IRebalancingSetTokenV2 { /* * Get totalSupply of Rebalancing Set * * @return totalSupply */ function totalSupply() external view returns (uint256); /** * Returns liquidator instance * * @return ILiquidator Liquidator instance */ function liquidator() external view returns (ILiquidator); /* * Get lastRebalanceTimestamp of Rebalancing Set * * @return lastRebalanceTimestamp */ function lastRebalanceTimestamp() external view returns (uint256); /* * Get rebalanceStartTime of Rebalancing Set * * @return rebalanceStartTime */ function rebalanceStartTime() external view returns (uint256); /* * Get startingCurrentSets of RebalancingSetToken * * @return startingCurrentSets */ function startingCurrentSetAmount() external view returns (uint256); /* * Get rebalanceInterval of Rebalancing Set * * @return rebalanceInterval */ function rebalanceInterval() external view returns (uint256); /* * Get array returning [startTime, timeToPivot, startPrice, endPrice] * * @return AuctionPriceParameters */ function getAuctionPriceParameters() external view returns (uint256[] memory); /* * Get array returning [minimumBid, remainingCurrentSets] * * @return BiddingParameters */ function getBiddingParameters() external view returns (uint256[] memory); /* * Get rebalanceState of Rebalancing Set * * @return RebalancingLibrary.State Current rebalance state of the RebalancingSetTokenV2 */ function rebalanceState() external view returns (RebalancingLibrary.State); /** * Gets the balance of the specified address. * * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf( address owner ) external view returns (uint256); /* * Get manager of Rebalancing Set * * @return manager */ function manager() external view returns (address); /* * Get feeRecipient of Rebalancing Set * * @return feeRecipient */ function feeRecipient() external view returns (address); /* * Get entryFee of Rebalancing Set * * @return entryFee */ function entryFee() external view returns (uint256); /* * Retrieves the current expected fee from the fee calculator * Value is returned as a scale decimal figure. */ function rebalanceFee() external view returns (uint256); /* * Get calculator contract used to compute rebalance fees * * @return rebalanceFeeCalculator */ function rebalanceFeeCalculator() external view returns (IFeeCalculator); /* * Initializes the RebalancingSetToken. Typically called by the Factory during creation */ function initialize( bytes calldata _rebalanceFeeCalldata ) external; /* * Set new liquidator address. Only whitelisted addresses are valid. */ function setLiquidator( ILiquidator _newLiquidator ) external; /* * Set new fee recipient address. */ function setFeeRecipient( address _newFeeRecipient ) external; /* * Set new fee entry fee. */ function setEntryFee( uint256 _newEntryFee ) external; /* * Initiates the rebalance in coordination with the Liquidator contract. * In this step, we redeem the currentSet and pass relevant information * to the liquidator. * * @param _nextSet The Set to rebalance into * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments * * Can only be called if the rebalance interval has elapsed. * Can only be called by manager. */ function startRebalance( address _nextSet, bytes calldata _liquidatorData ) external; /* * After a successful rebalance, the new Set is issued. If there is a rebalance fee, * the fee is paid via inflation of the Rebalancing Set to the feeRecipient. * Full issuance functionality is now returned to set owners. * * Anyone can call this function. */ function settleRebalance() external; /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /** * Returns the address of the current base SetToken with the current allocation * * @return A address representing the base SetToken */ function currentSet() external view returns (ISetToken); /** * Returns the address of the next base SetToken with the post auction allocation * * @return address Address representing the base SetToken */ function nextSet() external view returns (ISetToken); /* * Get the unit shares of the rebalancing Set * * @return unitShares Unit Shares of the base Set */ function unitShares() external view returns (uint256); /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory); /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) external view returns (uint256[] memory, uint256[] memory); /* * Get name of Rebalancing Set * * @return name */ function name() external view returns (string memory); /* * Get symbol of Rebalancing Set * * @return symbol */ function symbol() external view returns (string memory); } // File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV3.sol /* 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. */ pragma solidity 0.5.7; /** * @title IRebalancingSetTokenV2 * @author Set Protocol * * The IRebalancingSetTokenV3 interface provides a light-weight, structured way to interact with the * RebalancingSetTokenV3 contract from another contract. */ interface IRebalancingSetTokenV3 { /* * Get totalSupply of Rebalancing Set * * @return totalSupply */ function totalSupply() external view returns (uint256); /** * Returns liquidator instance * * @return ILiquidator Liquidator instance */ function liquidator() external view returns (ILiquidator); /* * Get lastRebalanceTimestamp of Rebalancing Set * * @return lastRebalanceTimestamp */ function lastRebalanceTimestamp() external view returns (uint256); /* * Get rebalanceStartTime of Rebalancing Set * * @return rebalanceStartTime */ function rebalanceStartTime() external view returns (uint256); /* * Get startingCurrentSets of RebalancingSetToken * * @return startingCurrentSets */ function startingCurrentSetAmount() external view returns (uint256); /* * Get rebalanceInterval of Rebalancing Set * * @return rebalanceInterval */ function rebalanceInterval() external view returns (uint256); /* * Get array returning [startTime, timeToPivot, startPrice, endPrice] * * @return AuctionPriceParameters */ function getAuctionPriceParameters() external view returns (uint256[] memory); /* * Get array returning [minimumBid, remainingCurrentSets] * * @return BiddingParameters */ function getBiddingParameters() external view returns (uint256[] memory); /* * Get rebalanceState of Rebalancing Set * * @return RebalancingLibrary.State Current rebalance state of the RebalancingSetTokenV3 */ function rebalanceState() external view returns (RebalancingLibrary.State); /** * Gets the balance of the specified address. * * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf( address owner ) external view returns (uint256); /* * Get manager of Rebalancing Set * * @return manager */ function manager() external view returns (address); /* * Get feeRecipient of Rebalancing Set * * @return feeRecipient */ function feeRecipient() external view returns (address); /* * Get entryFee of Rebalancing Set * * @return entryFee */ function entryFee() external view returns (uint256); /* * Retrieves the current expected fee from the fee calculator * Value is returned as a scale decimal figure. */ function rebalanceFee() external view returns (uint256); /* * Get calculator contract used to compute rebalance fees * * @return rebalanceFeeCalculator */ function rebalanceFeeCalculator() external view returns (IFeeCalculator); /* * Initializes the RebalancingSetToken. Typically called by the Factory during creation */ function initialize( bytes calldata _rebalanceFeeCalldata ) external; /* * Set new liquidator address. Only whitelisted addresses are valid. */ function setLiquidator( ILiquidator _newLiquidator ) external; /* * Set new fee recipient address. */ function setFeeRecipient( address _newFeeRecipient ) external; /* * Set new fee entry fee. */ function setEntryFee( uint256 _newEntryFee ) external; /* * Initiates the rebalance in coordination with the Liquidator contract. * In this step, we redeem the currentSet and pass relevant information * to the liquidator. * * @param _nextSet The Set to rebalance into * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments * * Can only be called if the rebalance interval has elapsed. * Can only be called by manager. */ function startRebalance( address _nextSet, bytes calldata _liquidatorData ) external; /* * After a successful rebalance, the new Set is issued. If there is a rebalance fee, * the fee is paid via inflation of the Rebalancing Set to the feeRecipient. * Full issuance functionality is now returned to set owners. * * Anyone can call this function. */ function settleRebalance() external; /* * During the Default stage, the incentive / rebalance Fee can be triggered. This will * retrieve the current inflation fee from the fee calulator and mint the according * inflation to the feeRecipient. The unit shares is then adjusted based on the new * supply. * * Anyone can call this function. */ function actualizeFee() external; /* * Validate then set new streaming fee. * * @param _newFeeData Fee type and new streaming fee encoded in bytes */ function adjustFee( bytes calldata _newFeeData ) external; /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /** * Returns the address of the current base SetToken with the current allocation * * @return A address representing the base SetToken */ function currentSet() external view returns (ISetToken); /** * Returns the address of the next base SetToken with the post auction allocation * * @return address Address representing the base SetToken */ function nextSet() external view returns (ISetToken); /* * Get the unit shares of the rebalancing Set * * @return unitShares Unit Shares of the base Set */ function unitShares() external view returns (uint256); /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory); /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) external view returns (uint256[] memory, uint256[] memory); /* * Get name of Rebalancing Set * * @return name */ function name() external view returns (string memory); /* * Get symbol of Rebalancing Set * * @return symbol */ function symbol() external view returns (string memory); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: set-protocol-contracts/contracts/lib/TimeLockUpgrade.sol /* 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.5.7; /** * @title TimeLockUpgrade * @author Set Protocol * * The TimeLockUpgrade contract contains a modifier for handling minimum time period updates */ contract TimeLockUpgrade is Ownable { using SafeMath for uint256; /* ============ State Variables ============ */ // Timelock Upgrade Period in seconds uint256 public timeLockPeriod; // Mapping of upgradable units and initialized timelock mapping(bytes32 => uint256) public timeLockedUpgrades; /* ============ Events ============ */ event UpgradeRegistered( bytes32 _upgradeHash, uint256 _timestamp ); /* ============ Modifiers ============ */ modifier timeLockUpgrade() { // If the time lock period is 0, then allow non-timebound upgrades. // This is useful for initialization of the protocol and for testing. if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS _; return; } // The upgrade hash is defined by the hash of the transaction call data, // which uniquely identifies the function as well as the passed in arguments. bytes32 upgradeHash = keccak256( abi.encodePacked( msg.data ) ); uint256 registrationTime = timeLockedUpgrades[upgradeHash]; // If the upgrade hasn't been registered, register with the current time. if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp ); return; } require( block.timestamp >= registrationTime.add(timeLockPeriod), "TimeLockUpgrade: Time lock period must have elapsed." ); // Reset the timestamp to 0 timeLockedUpgrades[upgradeHash] = 0; // Run the rest of the upgrades _; } /* ============ Function ============ */ /** * Change timeLockPeriod period. Generally called after initially settings have been set up. * * @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution */ function setTimeLockPeriod( uint256 _timeLockPeriod ) external onlyOwner { // Only allow setting of the timeLockPeriod if the period is greater than the existing require( _timeLockPeriod > timeLockPeriod, "TimeLockUpgrade: New period must be greater than existing" ); timeLockPeriod = _timeLockPeriod; } } // File: set-protocol-contracts/contracts/lib/UnrestrictedTimeLockUpgrade.sol /* 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. */ pragma solidity 0.5.7; /** * @title UnrestrictedTimeLockUpgrade * @author Set Protocol * * The UnrestrictedTimeLockUpgrade contract inherits a modifier for handling minimum time period updates not * limited to the owner of the contract. Also implements a removeTimeLockUpgrade internal function that can * be exposed by writing an external version into the contract it used in with the required modifiers to * restrict access. */ contract UnrestrictedTimeLockUpgrade is TimeLockUpgrade { /* ============ Events ============ */ event RemoveRegisteredUpgrade( bytes32 indexed _upgradeHash ); /* ============ Internal Function ============ */ /** * Removes an existing upgrade. * * @param _upgradeHash Keccack256 hash that uniquely identifies function called and arguments */ function removeRegisteredUpgradeInternal( bytes32 _upgradeHash ) internal { require( timeLockedUpgrades[_upgradeHash] != 0, "TimeLockUpgradeV2.removeRegisteredUpgrade: Upgrade hash must be registered" ); // Reset the timestamp to 0 timeLockedUpgrades[_upgradeHash] = 0; emit RemoveRegisteredUpgrade( _upgradeHash ); } } // File: set-protocol-contracts/contracts/lib/LimitOneUpgrade.sol /* 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. */ pragma solidity 0.5.7; /** * @title LimitOneUpgrade * @author Set Protocol * * For function that must be timelocked but could potentially have more than one upgrade at a time * this contract allows one to limit the amount of simultaneous upgrades. */ contract LimitOneUpgrade is UnrestrictedTimeLockUpgrade { /* ============ State Variables ============ */ mapping(address => bytes32) public upgradeIdentifier; /* ============ Modifier ============ */ /** * This modifier must be used in conjunction with timeLockUpgrade AND must be called before * timeLockUpgrade is called. UpgradeAddress must also be part of the msg.data. */ modifier limitOneUpgrade(address _upgradeAddress) { if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS // Get upgradeHash bytes32 upgradeHash = keccak256(msg.data); if (blockhash(block.number) != 0) { //injected CONTRACT AFFECTED BY MINERS // If upgrade hash has no record then revert since must be second upgrade require( upgradeIdentifier[_upgradeAddress] == upgradeHash, "Another update already in progress." ); upgradeIdentifier[_upgradeAddress] = 0; } else { upgradeIdentifier[_upgradeAddress] = upgradeHash; } } _; } /** * Verifies that upgrade address matches with hash of upgrade. Removes upgrade from timelockUpgrades * and sets upgradeIdentifier to 0 for passed upgradeAddress, allowing for another upgrade. * * @param _upgradeAddress The address of the trading pool being updated * @param _upgradeHash Keccack256 hash that uniquely identifies function called and arguments */ function removeRegisteredUpgradeInternal( address _upgradeAddress, bytes32 _upgradeHash ) internal { require( upgradeIdentifier[_upgradeAddress] == _upgradeHash, "Passed upgrade hash does not match upgrade address." ); UnrestrictedTimeLockUpgrade.removeRegisteredUpgradeInternal(_upgradeHash); upgradeIdentifier[_upgradeAddress] = 0; } } // File: set-protocol-contracts/contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; 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 (0, 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; (, isIn) = indexOf(A, a); return isIn; } /** * 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; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Removes specified index from array * Resulting ordering is not guaranteed * @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; 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]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } } // File: set-protocol-contracts/contracts/lib/WhiteList.sol /* 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.5.7; /** * @title Whitelist * @author Set Protocol * * Generic whitelist for addresses */ contract WhiteList is Ownable, TimeLockUpgrade { using AddressArrayUtils for address[]; /* ============ State Variables ============ */ address[] public addresses; mapping(address => bool) public whiteList; /* ============ Events ============ */ event AddressAdded( address _address ); event AddressRemoved( address _address ); /* ============ Constructor ============ */ /** * Constructor function for Whitelist * * Allow initial addresses to be passed in so a separate transaction is not required for each * * @param _initialAddresses Starting set of addresses to whitelist */ constructor( address[] memory _initialAddresses ) public { // Add each of initial addresses to state for (uint256 i = 0; i < _initialAddresses.length; i++) { address addressToAdd = _initialAddresses[i]; addresses.push(addressToAdd); whiteList[addressToAdd] = true; } } /* ============ External Functions ============ */ /** * Add an address to the whitelist * * @param _address Address to add to the whitelist */ function addAddress( address _address ) external onlyOwner timeLockUpgrade { require( !whiteList[_address], "WhiteList.addAddress: Address has already been whitelisted." ); addresses.push(_address); whiteList[_address] = true; emit AddressAdded( _address ); } /** * Remove an address from the whitelist * * @param _address Address to remove from the whitelist */ function removeAddress( address _address ) external onlyOwner { require( whiteList[_address], "WhiteList.removeAddress: Address is not current whitelisted." ); addresses = addresses.remove(_address); whiteList[_address] = false; emit AddressRemoved( _address ); } /** * Return array of all whitelisted addresses * * @return address[] Array of addresses */ function validAddresses() external view returns (address[] memory) { return addresses; } /** * Verifies an array of addresses against the whitelist * * @param _addresses Array of addresses to verify * @return bool Whether all addresses in the list are whitelsited */ function areValidAddresses( address[] calldata _addresses ) external view returns (bool) { for (uint256 i = 0; i < _addresses.length; i++) { if (!whiteList[_addresses[i]]) { return false; } } return true; } } // File: contracts/managers/allocators/ISocialAllocator.sol /* Copyright 2019 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.5.7; /** * @title ISocialAllocator * @author Set Protocol * * Interface for interacting with SocialAllocator contracts */ interface ISocialAllocator { /* * Determine the next allocation to rebalance into. * * @param _targetBaseAssetAllocation Target allocation of the base asset * @return ISetToken The address of the proposed nextSet */ function determineNewAllocation( uint256 _targetBaseAssetAllocation ) external returns (ISetToken); /* * Calculate value of passed collateral set. * * @param _collateralSet Instance of current set collateralizing RebalancingSetToken * @return uint256 USD value of passed Set */ function calculateCollateralSetValue( ISetToken _collateralSet ) external view returns(uint256); } // File: contracts/managers/lib/SocialTradingLibrary.sol /* Copyright 2019 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.5.7; /** * @title SocialTradingLibrary * @author Set Protocol * * Library for use in SocialTrading system. */ library SocialTradingLibrary { /* ============ Structs ============ */ struct PoolInfo { address trader; // Address allowed to make admin and allocation decisions ISocialAllocator allocator; // Allocator used to make collateral Sets, defines asset pair being used uint256 currentAllocation; // Current base asset allocation of tradingPool uint256 newEntryFee; // New fee percentage to change to after time lock passes, defaults to 0 uint256 feeUpdateTimestamp; // Timestamp when fee update process can be finalized, defaults to maxUint256 } } // File: contracts/managers/SocialTradingManager.sol /* Copyright 2019 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.5.7; /** * @title SocialTradingManager * @author Set Protocol * * Singleton manager contract through which all social trading sets are managed. Traders can choose a percentage * between 0 and 100 for each rebalance. The trading pair used for each trading pool is defined by the allocator * passed in on pool creation. Only compatible with RebalancingSetTokenV2 constracts. All permissioned functions * on the RebalancingSetTokenV2 must be called through the administrative functions exposed on this contract. * * CHANGELOG: As of version 1.1.31 the REBALANCING_SET_NATURAL_UNIT has been changed from 1e6 to 1e8. */ contract SocialTradingManager is WhiteList { using SafeMath for uint256; /* ============ Events ============ */ event TradingPoolCreated( address indexed trader, ISocialAllocator indexed allocator, address indexed tradingPool, uint256 startingAllocation ); event AllocationUpdate( address indexed tradingPool, uint256 oldAllocation, uint256 newAllocation ); event NewTrader( address indexed tradingPool, address indexed oldTrader, address indexed newTrader ); /* ============ Modifier ============ */ modifier onlyTrader(IRebalancingSetTokenV2 _tradingPool) { require( msg.sender == trader(_tradingPool), "Sender must be trader" ); _; } /* ============ Constants ============ */ uint256 public constant REBALANCING_SET_NATURAL_UNIT = 1e8; uint public constant ONE_PERCENT = 1e16; uint256 constant public MAXIMUM_ALLOCATION = 1e18; /* ============ State Variables ============ */ ICore public core; address public factory; mapping(address => SocialTradingLibrary.PoolInfo) public pools; uint256 public maxEntryFee; uint256 public feeUpdateTimelock; /* * SocialTradingManager constructor. * * @param _core The address of the Core contract * @param _factory Factory to use for RebalancingSetToken creation * @param _whiteListedAllocators List of allocator addresses to WhiteList * @param _maxEntryFee Max entry fee when updating fees in a scaled decimal value * (e.g. 1% = 1e16, 1bp = 1e14) * @param _feeUpdateTimelock Amount of time trader must wait between starting fee update * and finalizing fee update */ constructor( ICore _core, address _factory, address[] memory _whiteListedAllocators, uint256 _maxEntryFee, uint256 _feeUpdateTimelock ) public WhiteList(_whiteListedAllocators) { core = _core; factory = _factory; maxEntryFee = _maxEntryFee; feeUpdateTimelock = _feeUpdateTimelock; } /* ============ External ============ */ /* * Create a trading pool. Create or select new collateral and create RebalancingSetToken contract to * administer pool. Save relevant data to pool's entry in pools state variable under the Rebalancing * Set Token address. * * @param _tradingPairAllocator The address of the allocator the trader wishes to use * @param _startingBaseAssetAllocation Starting base asset allocation in a scaled decimal value * (e.g. 100% = 1e18, 1% = 1e16) * @param _startingUSDValue Starting value of one share of the trading pool to 18 decimals of precision * @param _name The name of the new RebalancingSetTokenV2 * @param _symbol The symbol of the new RebalancingSetTokenV2 * @param _rebalancingSetCallData Byte string containing additional call parameters to pass to factory */ function createTradingPool( ISocialAllocator _tradingPairAllocator, uint256 _startingBaseAssetAllocation, uint256 _startingUSDValue, bytes32 _name, bytes32 _symbol, bytes calldata _rebalancingSetCallData ) external { // Validate relevant params validateCreateTradingPool(_tradingPairAllocator, _startingBaseAssetAllocation, _rebalancingSetCallData); // Get collateral Set ISetToken collateralSet = _tradingPairAllocator.determineNewAllocation( _startingBaseAssetAllocation ); uint256[] memory unitShares = new uint256[](1); // Value collateral uint256 collateralValue = _tradingPairAllocator.calculateCollateralSetValue( collateralSet ); // unitShares is equal to _startingUSDValue divided by colalteral Value unitShares[0] = _startingUSDValue.mul(REBALANCING_SET_NATURAL_UNIT).div(collateralValue); address[] memory components = new address[](1); components[0] = address(collateralSet); // Create tradingPool address tradingPool = core.createSet( factory, components, unitShares, REBALANCING_SET_NATURAL_UNIT, _name, _symbol, _rebalancingSetCallData ); pools[tradingPool].trader = msg.sender; pools[tradingPool].allocator = _tradingPairAllocator; pools[tradingPool].currentAllocation = _startingBaseAssetAllocation; pools[tradingPool].feeUpdateTimestamp = 0; emit TradingPoolCreated( msg.sender, _tradingPairAllocator, tradingPool, _startingBaseAssetAllocation ); } /* * Update trading pool allocation. Issue new collateral Set and initiate rebalance on RebalancingSetTokenV2. * * @param _tradingPool The address of the trading pool being updated * @param _newAllocation New base asset allocation in a scaled decimal value * (e.g. 100% = 1e18, 1% = 1e16) * @param _liquidatorData Extra parameters passed to the liquidator */ function updateAllocation( IRebalancingSetTokenV2 _tradingPool, uint256 _newAllocation, bytes calldata _liquidatorData ) external onlyTrader(_tradingPool) { // Validate updateAllocation params validateAllocationUpdate(_tradingPool, _newAllocation); // Create nextSet collateral ISetToken nextSet = allocator(_tradingPool).determineNewAllocation( _newAllocation ); // Trigger start rebalance on RebalancingSetTokenV2 _tradingPool.startRebalance(address(nextSet), _liquidatorData); emit AllocationUpdate( address(_tradingPool), currentAllocation(_tradingPool), _newAllocation ); // Save new allocation pools[address(_tradingPool)].currentAllocation = _newAllocation; } /* * Start fee update process, set fee update timestamp and commit to new fee. * * @param _tradingPool The address of the trading pool being updated * @param _newEntryFee New entry fee in a scaled decimal value * (e.g. 100% = 1e18, 1% = 1e16) */ function initiateEntryFeeChange( IRebalancingSetTokenV2 _tradingPool, uint256 _newEntryFee ) external onlyTrader(_tradingPool) { // Validate new entry fee doesn't exceed max validateNewEntryFee(_newEntryFee); // Log new entryFee and timestamp to start timelock from pools[address(_tradingPool)].feeUpdateTimestamp = block.timestamp.add(feeUpdateTimelock); pools[address(_tradingPool)].newEntryFee = _newEntryFee; } /* * Finalize fee update, change fee on RebalancingSetTokenV2 if time lock period has elapsed. * * @param _tradingPool The address of the trading pool being updated */ function finalizeEntryFeeChange( IRebalancingSetTokenV2 _tradingPool ) external onlyTrader(_tradingPool) { // If feeUpdateTimestamp is equal to 0 indicates initiate wasn't called require( feeUpdateTimestamp(_tradingPool) != 0, "SocialTradingManager.finalizeSetFeeRecipient: Must initiate fee change first." ); // Current block timestamp must exceed feeUpdateTimestamp require( block.timestamp >= feeUpdateTimestamp(_tradingPool), "SocialTradingManager.finalizeSetFeeRecipient: Time lock period must elapse to update fees." ); // Reset timestamp to avoid reentrancy pools[address(_tradingPool)].feeUpdateTimestamp = 0; // Update fee on RebalancingSetTokenV2 _tradingPool.setEntryFee(newEntryFee(_tradingPool)); // Reset newEntryFee pools[address(_tradingPool)].newEntryFee = 0; } /* * Update trader allowed to manage trading pool. * * @param _tradingPool The address of the trading pool being updated * @param _newTrader Address of new traders */ function setTrader( IRebalancingSetTokenV2 _tradingPool, address _newTrader ) external onlyTrader(_tradingPool) { emit NewTrader( address(_tradingPool), trader(_tradingPool), _newTrader ); pools[address(_tradingPool)].trader = _newTrader; } /* * Update liquidator used by tradingPool. * * @param _tradingPool The address of the trading pool being updated * @param _newLiquidator Address of new Liquidator */ function setLiquidator( IRebalancingSetTokenV2 _tradingPool, ILiquidator _newLiquidator ) external onlyTrader(_tradingPool) { _tradingPool.setLiquidator(_newLiquidator); } /* * Update fee recipient of tradingPool. * * @param _tradingPool The address of the trading pool being updated * @param _newFeeRecipient Address of new fee recipient */ function setFeeRecipient( IRebalancingSetTokenV2 _tradingPool, address _newFeeRecipient ) external onlyTrader(_tradingPool) { _tradingPool.setFeeRecipient(_newFeeRecipient); } /* ============ Internal ============ */ /* * Validate trading pool creation. Make sure allocation is valid, allocator is white listed and * manager passed in rebalancingSetCallData is this address. * * @param _tradingPairAllocator The address of allocator being used in trading pool * @param _startingBaseAssetAllocation New base asset allocation in a scaled decimal value * (e.g. 100% = 1e18, 1% = 1e16) * @param _rebalancingSetCallData Byte string containing RebalancingSetTokenV2 call parameters */ function validateCreateTradingPool( ISocialAllocator _tradingPairAllocator, uint256 _startingBaseAssetAllocation, bytes memory _rebalancingSetCallData ) internal view { validateAllocationAmount(_startingBaseAssetAllocation); validateManagerAddress(_rebalancingSetCallData); require( whiteList[address(_tradingPairAllocator)], "SocialTradingManager.validateCreateTradingPool: Passed allocator is not valid." ); } /* * Validate trading pool allocation update. Make sure allocation is valid, * and RebalancingSet is in valid state. * * @param _tradingPool The address of the trading pool being updated * @param _newAllocation New base asset allocation in a scaled decimal value * (e.g. 100% = 1e18, 1% = 1e16) */ function validateAllocationUpdate( IRebalancingSetTokenV2 _tradingPool, uint256 _newAllocation ) internal view { validateAllocationAmount(_newAllocation); // If current allocation is 0/100%, cannot be the same allocation uint256 currentAllocationValue = currentAllocation(_tradingPool); require( !(currentAllocationValue == MAXIMUM_ALLOCATION && _newAllocation == MAXIMUM_ALLOCATION) && !(currentAllocationValue == 0 && _newAllocation == 0), "SocialTradingManager.validateAllocationUpdate: Invalid allocation" ); // Require that enough time has passed from last rebalance uint256 lastRebalanceTimestamp = _tradingPool.lastRebalanceTimestamp(); uint256 rebalanceInterval = _tradingPool.rebalanceInterval(); require( block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval), "SocialTradingManager.validateAllocationUpdate: Rebalance interval not elapsed" ); // Require that Rebalancing Set Token is in Default state, won't allow for re-proposals // because malicious actor could prevent token from ever rebalancing require( _tradingPool.rebalanceState() == RebalancingLibrary.State.Default, "SocialTradingManager.validateAllocationUpdate: State must be in Default" ); } /* * Validate passed allocation amount. * * @param _allocation New base asset allocation in a scaled decimal value * (e.g. 100% = 1e18, 1% = 1e16) */ function validateAllocationAmount( uint256 _allocation ) internal view { require( _allocation <= MAXIMUM_ALLOCATION, "Passed allocation must not exceed 100%." ); require( _allocation.mod(ONE_PERCENT) == 0, "Passed allocation must be multiple of 1%." ); } /* * Validate new entry fee. * * @param _entryFee New entry fee in a scaled decimal value * (e.g. 100% = 1e18, 1% = 1e16) */ function validateNewEntryFee( uint256 _entryFee ) internal view { require( _entryFee <= maxEntryFee, "SocialTradingManager.validateNewEntryFee: Passed entry fee must not exceed maxEntryFee." ); } /* * Validate passed manager in RebalancingSetToken bytes arg matches this address. * * @param _rebalancingSetCallData Byte string containing RebalancingSetTokenV2 call parameters */ function validateManagerAddress( bytes memory _rebalancingSetCallData ) internal view { address manager; assembly { manager := mload(add(_rebalancingSetCallData, 32)) // manager slot } require( manager == address(this), "SocialTradingManager.validateCallDataArgs: Passed manager address is not this address." ); } function allocator(IRebalancingSetTokenV2 _tradingPool) internal view returns (ISocialAllocator) { return pools[address(_tradingPool)].allocator; } function trader(IRebalancingSetTokenV2 _tradingPool) internal view returns (address) { return pools[address(_tradingPool)].trader; } function currentAllocation(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { return pools[address(_tradingPool)].currentAllocation; } function feeUpdateTimestamp(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { return pools[address(_tradingPool)].feeUpdateTimestamp; } function newEntryFee(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { return pools[address(_tradingPool)].newEntryFee; } } // File: contracts/managers/SocialTradingManagerV2.sol /* 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. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; /** * @title SocialTradingManagerV2 * @author Set Protocol * * Singleton manager contract through which all social trading v2 sets are managed. Inherits from SocialTradingManager * and adds functionality to adjust performance based fees. */ contract SocialTradingManagerV2 is SocialTradingManager, LimitOneUpgrade { /* * SocialTradingManager constructor. * * @param _core The address of the Core contract * @param _factory Factory to use for RebalancingSetToken creation * @param _whiteListedAllocators List of allocator addresses to WhiteList * @param _maxEntryFee Max entry fee when updating fees in a scaled decimal value * (e.g. 1% = 1e16, 1bp = 1e14) * @param _feeUpdateTimelock Amount of time trader must wait between starting fee update * and finalizing fee update */ constructor( ICore _core, address _factory, address[] memory _whiteListedAllocators, uint256 _maxEntryFee, uint256 _feeUpdateTimelock ) public SocialTradingManager( _core, _factory, _whiteListedAllocators, _maxEntryFee, _feeUpdateTimelock ) {} /* ============ External ============ */ /** * Allows traders to update fees on their Set. Only one fee update allowed at a time and timelocked. * * @param _tradingPool The address of the trading pool being updated * @param _newFeeCallData Bytestring representing feeData to pass to fee calculator */ function adjustFee( address _tradingPool, bytes calldata _newFeeCallData ) external onlyTrader(IRebalancingSetTokenV2(_tradingPool)) limitOneUpgrade(_tradingPool) timeLockUpgrade { IRebalancingSetTokenV3(_tradingPool).adjustFee(_newFeeCallData); } /** * External function to remove upgrade. Modifiers should be added to restrict usage. * * @param _tradingPool The address of the trading pool being updated * @param _upgradeHash Keccack256 hash that uniquely identifies function called and arguments */ function removeRegisteredUpgrade( address _tradingPool, bytes32 _upgradeHash ) external onlyTrader(IRebalancingSetTokenV2(_tradingPool)) { LimitOneUpgrade.removeRegisteredUpgradeInternal(_tradingPool, _upgradeHash); } }
If the upgrade hasn't been registered, register with the current time.
timeLockedUpgrades[upgradeHash] = block.timestamp;
968,937
[ 1, 4625, 348, 7953, 560, 30, 225, 971, 326, 8400, 13342, 1404, 2118, 4104, 16, 1744, 598, 326, 783, 813, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 813, 8966, 1211, 13088, 63, 15097, 2310, 65, 273, 1203, 18, 5508, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x741E47CFA0Ff046130CC9436D2bd2aB062f7546D/sources/FraxUnifiedFarm_ERC20_Other.sol
@notice Owner or governance can pause/unpause staking, withdrawals, rewards collection, and collectRewardsOnWithdrawal @param _stakingPaused Whether staking is paused @param _withdrawalsPaused Whether withdrawals are paused @param _rewardsCollectionPaused Whether rewards collection is paused @param _collectRewardsOnWithdrawalPaused Whether collectRewardsOnWithdrawal is paused
function setPauses( bool _stakingPaused, bool _withdrawalsPaused, bool _rewardsCollectionPaused, bool _collectRewardsOnWithdrawalPaused ) external onlyByOwnGov { stakingPaused = _stakingPaused; withdrawalsPaused = _withdrawalsPaused; rewardsCollectionPaused = _rewardsCollectionPaused; collectRewardsOnWithdrawalPaused = _collectRewardsOnWithdrawalPaused; }
2,658,906
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 16837, 578, 314, 1643, 82, 1359, 848, 11722, 19, 318, 19476, 384, 6159, 16, 598, 9446, 1031, 16, 283, 6397, 1849, 16, 471, 3274, 17631, 14727, 1398, 1190, 9446, 287, 632, 891, 389, 334, 6159, 28590, 17403, 384, 6159, 353, 17781, 632, 891, 389, 1918, 9446, 1031, 28590, 17403, 598, 9446, 1031, 854, 17781, 632, 891, 389, 266, 6397, 2532, 28590, 17403, 283, 6397, 1849, 353, 17781, 632, 891, 389, 14676, 17631, 14727, 1398, 1190, 9446, 287, 28590, 17403, 3274, 17631, 14727, 1398, 1190, 9446, 287, 353, 17781, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17004, 9608, 12, 203, 3639, 1426, 389, 334, 6159, 28590, 16, 203, 3639, 1426, 389, 1918, 9446, 1031, 28590, 16, 203, 3639, 1426, 389, 266, 6397, 2532, 28590, 16, 203, 3639, 1426, 389, 14676, 17631, 14727, 1398, 1190, 9446, 287, 28590, 203, 565, 262, 3903, 1338, 858, 5460, 43, 1527, 288, 203, 3639, 384, 6159, 28590, 273, 389, 334, 6159, 28590, 31, 203, 3639, 598, 9446, 1031, 28590, 273, 389, 1918, 9446, 1031, 28590, 31, 203, 3639, 283, 6397, 2532, 28590, 273, 389, 266, 6397, 2532, 28590, 31, 203, 3639, 3274, 17631, 14727, 1398, 1190, 9446, 287, 28590, 273, 389, 14676, 17631, 14727, 1398, 1190, 9446, 287, 28590, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-11-26 */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.3.2 (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); } // OpenZeppelin Contracts v4.3.2 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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; } } // OpenZeppelin Contracts v4.3.2 (utils/introspection/ERC165.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; } } // OpenZeppelin Contracts v4.3.2 (utils/Strings.sol) /** * @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); } } // OpenZeppelin Contracts v4.3.2 (access/IAccessControl.sol) /** * @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; } // OpenZeppelin Contracts v4.3.2 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/ERC721Enumerable.sol) // OpenZeppelin Contracts v4.3.2 (token/ERC721/ERC721.sol) // OpenZeppelin Contracts v4.3.2 (token/ERC721/IERC721Receiver.sol) /** * @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); } // OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/IERC721Metadata.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); } // OpenZeppelin Contracts v4.3.2 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. 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); } } } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/IERC721Enumerable.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @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(); } } // OpenZeppelin Contracts v4.3.2 (access/AccessControlEnumerable.sol) // OpenZeppelin Contracts v4.3.2 (access/IAccessControlEnumerable.sol) /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // OpenZeppelin Contracts v4.3.2 (access/AccessControl.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 revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // OpenZeppelin Contracts v4.3.2 (utils/structs/EnumerableSet.sol) /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // OpenZeppelin Contracts v4.3.2 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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); } } // OpenZeppelin Contracts v4.3.2 (utils/Counters.sol) /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } contract DoodledPizzas is Context, AccessControlEnumerable, ERC721, ERC721Enumerable, Ownable { using Counters for Counters.Counter; //string public notRevealedUri; string base_uri_head = "ipfs://QmZ7CSdZqimGv5WtuSRV17KnBwEmDTgZDb8r6dyyxxjBqg/"; string notRevealedUri = "ipfs://QmXzGD8K29huahBSE8ST8qbfpfhRSAVKFDZu9vzKc59mNv/hidden.json"; string base_uri_tail = ".json"; Counters.Counter private _tokenIdTracker; uint public pricePerNFT = 0.03 ether; uint constant public maxNFTPerCall = 20; uint constant public teamSupply = 0; uint constant public maxTotalSupply = 10000; uint constant public publicSupply = maxTotalSupply - teamSupply; bool public revealed = false; bool saleStarted = false; bool public teamTokensMinted = false; uint public tokensBurned = 0; mapping(address => bool) public giveAwayWhiteList; constructor() ERC721("Doodled Pizzas", "Doodled Pizzas") { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function setPrice(uint newPrice) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller cannot alter state"); pricePerNFT = newPrice; } function toggleSaleState() public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller cannot alter state"); saleStarted = !saleStarted; } function addToGiveAwayWhiteList(address[] memory users) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller cannot alter whiteList"); for(uint i=0; i<users.length; i++) { giveAwayWhiteList[users[i]] = true; } } function removeFromGiveAwayWhiteList(address[] memory users) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller cannot alter whiteList"); for(uint i=0; i<users.length; i++) { giveAwayWhiteList[users[i]] = false; } } function withdraw() public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller cannot withdraw"); payable(owner()).call{value: address(this).balance}(""); } function makeTeamMints() public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller cannot mint team tokens"); require(!teamTokensMinted, "Team tokens have already been minted"); for (uint i=0; i<teamSupply; i++) { _mint(owner(), _tokenIdTracker.current()); _tokenIdTracker.increment(); } teamTokensMinted = true; } function mint(uint _amount) public payable { require(_amount > 0, "Minting 0 tokens is quite useless"); require(_amount <= maxNFTPerCall, "Amount is higher than maximum per call"); require(saleIsActive(), "Sale is not active"); if (giveAwayWhiteList[_msgSender()]) { if (_amount >0 && _amount < 2 ) { for (uint i=0; i<_amount; i++) { _mint(_msgSender(), _tokenIdTracker.current()); _tokenIdTracker.increment(); } _amount = _amount -1; } if (_amount >= 2) { for (uint i=0; i < 2; i++) { _mint(_msgSender(), _tokenIdTracker.current()); _tokenIdTracker.increment(); } _amount = _amount -2; } giveAwayWhiteList[_msgSender()] = false; } uint bound; if (teamTokensMinted) { bound = maxTotalSupply; } else { bound = publicSupply; } if (_amount+_tokenIdTracker.current() > bound) { _amount = bound-_tokenIdTracker.current(); } uint amountToPay = _amount*pricePerNFT; require(amountToPay <= msg.value, "Provided not enough Ether for purchase"); for (uint i=0; i<_amount; i++) { _mint(_msgSender(), _tokenIdTracker.current()); _tokenIdTracker.increment(); } if (msg.value > amountToPay) { payable(_msgSender()).call{value: msg.value - amountToPay}(""); } } function burnMany(uint256[] calldata tokenIds) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller cannot alter state"); for (uint i; i<tokenIds.length; i++) { _burn(tokenIds[i]); } tokensBurned += tokenIds.length; } function tokensMinted() public view returns(uint) { return _tokenIdTracker.current(); } function saleIsActive() public view returns(bool){ if (teamTokensMinted) { return (saleStarted && _tokenIdTracker.current() < maxTotalSupply); } else { return (saleStarted && _tokenIdTracker.current() < publicSupply); } } function tokenURI(uint256 _tokenId) public view override returns (string memory) { if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = base_uri_head; return string(abi.encodePacked(currentBaseURI, Strings.toString(_tokenId+1), base_uri_tail)); //changed to tokenid+1 to match json file name } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable, AccessControlEnumerable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function reveal() public onlyOwner() { revealed = true; } }
* @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); }
1,699,993
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2860, 2856, 1375, 2316, 548, 68, 1704, 18, 13899, 848, 506, 7016, 635, 3675, 3410, 578, 20412, 9484, 3970, 288, 12908, 537, 97, 578, 288, 542, 23461, 1290, 1595, 5496, 13899, 787, 2062, 1347, 2898, 854, 312, 474, 329, 21863, 67, 81, 474, 68, 3631, 471, 2132, 2062, 1347, 2898, 854, 18305, 329, 21863, 67, 70, 321, 68, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1808, 12, 11890, 5034, 1147, 548, 13, 2713, 1476, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 995, 414, 63, 2316, 548, 65, 480, 1758, 12, 20, 1769, 203, 565, 289, 203, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: 0x1d688a985f56a48a022a98de59fd37b32e2c72f2 //Contract name: Beercoin //Balance: 0 Ether //Verification Date: 1/1/2018 //Transacion Count: 5 // CODE STARTS HERE pragma solidity ^0.4.16; contract ERC20Token { event Transfer(address indexed from, address indexed _to, uint256 _value); event Approval(address indexed owner, address indexed _spender, uint256 _value); mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0 && _to != address(this)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } } contract Owned { address public owner; /** * Construct the Owned contract and * make the sender the owner */ function Owned() public { owner = msg.sender; } /** * Restrict to the owner only */ modifier onlyOwner { require(msg.sender == owner); _; } /** * Transfer the ownership to another address * * @param newOwner the new owner's address */ function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } contract Beercoin is ERC20Token, Owned { event Produce(uint256 value, string caps); event Burn(uint256 value); string public name = "Beercoin"; string public symbol = "🍺"; uint8 public decimals = 18; uint256 public totalSupply = 15496000000 * 10 ** uint256(decimals); // In addition to the initial total supply of 15496000000 Beercoins, // more Beercoins will only be added by scanning bottle caps. // 20800000000 bottle caps will be eventually produced. // // Within 10000 bottle caps, // 1 (i.e. every 10000th cap in total) has a value of 10000 ("Diamond") Beercoins, // 9 (i.e. every 1000th cap in total) have a value of 100 ("Gold") Beercoins, // 990 (i.e. every 10th cap in total) have a value of 10 ("Silver") Beercoins, // 9000 (i.e. every remaining cap) have a value of 1 ("Bronze") Beercoin. // // Therefore one bottle cap has an average Beercoin value of // (1 * 10000 + 9 * 100 + 990 * 10 + 9000 * 1) / 10000 = 2.98. // // This means the Beercoin value of all bottle caps that // will be produced in total is 20800000000 * 2.98 = 61984000000. uint256 public unproducedCaps = 20800000000; uint256 public producedCaps = 0; // Stores whether users disallow the owner to // pull Beercoins for the use of redemption. mapping (address => bool) public redemptionLocked; /** * Construct the Beercoin contract and * assign the initial supply to the owner. */ function Beercoin() public { balanceOf[owner] = totalSupply; } /** * Lock or unlock the redemption functionality * * If a user doesn't want to redeem Beercoins on the owner's * website and doesn't trust the owner, the owner's capability * of pulling Beercoin from the user's account can be locked * * @param lock whether to lock the redemption capability or not */ function lockRedemption(bool lock) public returns (bool success) { redemptionLocked[msg.sender] = lock; return true; } /** * Generate a sequence of bottle cap values to be used * for production and send the respective total Beercoin * value to the contract for keeping until a scan is recognized * * We hereby declare that this function is called if and only if * we need to generate codes intended for beer bottle production * * @param numberOfCaps the number of bottle caps to be produced */ function produce(uint256 numberOfCaps) public onlyOwner returns (bool success) { require(numberOfCaps <= unproducedCaps); uint256 value = 0; bytes memory caps = bytes(new string(numberOfCaps)); for (uint256 i = 0; i < numberOfCaps; ++i) { uint256 currentCoin = producedCaps + i; if (currentCoin % 10000 == 0) { value += 10000; caps[i] = "D"; } else if (currentCoin % 1000 == 0) { value += 100; caps[i] = "G"; } else if (currentCoin % 10 == 0) { value += 10; caps[i] = "S"; } else { value += 1; caps[i] = "B"; } } unproducedCaps -= numberOfCaps; producedCaps += numberOfCaps; value = value * 10 ** uint256(decimals); totalSupply += value; balanceOf[this] += value; Produce(value, string(caps)); return true; } /** * Grant Beercoins to a user who scanned a bottle cap code * * We hereby declare that this function is called if and only if * our server registers a valid code scan by the given user * * @param user the address of the user who scanned a codes * @param cap a bottle cap value ("D", "G", "S", or "B") */ function scan(address user, byte cap) public onlyOwner returns (bool success) { if (cap == "D") { _transfer(this, user, 10000 * 10 ** uint256(decimals)); } else if (cap == "G") { _transfer(this, user, 100 * 10 ** uint256(decimals)); } else if (cap == "S") { _transfer(this, user, 10 * 10 ** uint256(decimals)); } else { _transfer(this, user, 1 * 10 ** uint256(decimals)); } return true; } /** * Grant Beercoins to users who scanned bottle cap codes * * We hereby declare that this function is called if and only if * our server registers valid code scans by the given users * * @param users the addresses of the users who scanned a codes * @param caps bottle cap values ("D", "G", "S", or "B") */ function scanMany(address[] users, byte[] caps) public onlyOwner returns (bool success) { require(users.length == caps.length); for (uint16 i = 0; i < users.length; ++i) { scan(users[i], caps[i]); } return true; } /** * Redeem tokens when the will to do so has been * stated within the user interface of a Beercoin * redemption system * * The owner calls this on behalf of the redeeming user * so the latter does not need to pay transaction fees * when redeeming * * We hereby declare that this function is called if and only if * a user deliberately wants to redeem Beercoins * * @param user the address of the user who wants to redeem * @param value the amount to redeem */ function redeem(address user, uint256 value) public onlyOwner returns (bool success) { require(redemptionLocked[user] == false); _transfer(user, owner, value); return true; } /** * Redeem tokens when the will to do so has been * stated within the user interface of a Beercoin * redemption system * * The owner calls this on behalf of the redeeming users * so the latter do not need to pay transaction fees * when redeeming * * We hereby declare that this function is called if and only if * users deliberately want to redeem Beercoins * * @param users the addresses of the users who want to redeem * @param values the amounts to redeem */ function redeemMany(address[] users, uint256[] values) public onlyOwner returns (bool success) { require(users.length == values.length); for (uint16 i = 0; i < users.length; ++i) { redeem(users[i], values[i]); } return true; } /** * Transfer Beercoins to multiple recipients * * @param recipients the addresses of the recipients * @param values the amounts to send */ function transferMany(address[] recipients, uint256[] values) public onlyOwner returns (bool success) { require(recipients.length == values.length); for (uint16 i = 0; i < recipients.length; ++i) { transfer(recipients[i], values[i]); } return true; } /** * Destroy Beercoins by removing them from the system irreversibly * * @param value the amount of Beercoins to burn */ function burn(uint256 value) public onlyOwner returns (bool success) { require(balanceOf[msg.sender] >= value); balanceOf[msg.sender] -= value; totalSupply -= value; Burn(value); return true; } }
* Internal transfer, only can be called by this contract/
function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0 && _to != address(this)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
5,480,418
[ 1, 4625, 348, 7953, 560, 30, 380, 3186, 7412, 16, 1338, 848, 506, 2566, 635, 333, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 597, 389, 869, 480, 1758, 12, 2211, 10019, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 405, 11013, 951, 63, 67, 869, 19226, 203, 3639, 2254, 2416, 38, 26488, 273, 11013, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 15533, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 3639, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 1815, 12, 12296, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 65, 422, 2416, 38, 26488, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity 0.4.26; /** * Math operations with safety checks */ import "../components/Halt.sol"; import "./QuotaStorage.sol"; import "../interfaces/IOracle.sol"; interface _ITokenManager { function getAncestorSymbol(uint id) external view returns (string symbol, uint8 decimals); } interface _IStoremanGroup { function getDeposit(bytes32 id) external view returns(uint deposit); } interface IDebtOracle { function isDebtClean(bytes32 storemanGroupId) external view returns (bool); } contract QuotaDelegate is QuotaStorage, Halt { modifier checkMinValue(uint tokenId, uint value) { if (fastCrossMinValue > 0) { string memory symbol; uint decimals; (symbol, decimals) = getTokenAncestorInfo(tokenId); uint price = getPrice(symbol); require(price > 0, "Price is zero"); uint count = fastCrossMinValue.mul(10**decimals).div(price); require(value >= count, "value too small"); } _; } /// @notice config params for owner /// @param _priceOracleAddr token price oracle contract address /// @param _htlcAddr HTLC contract address /// @param _depositOracleAddr deposit oracle address, storemanAdmin or oracle /// @param _depositRate deposit rate value, 15000 means 150% /// @param _depositTokenSymbol deposit token symbol, default is WAN /// @param _tokenManagerAddress token manager contract address function config( address _priceOracleAddr, address _htlcAddr, address _fastHtlcAddr, address _depositOracleAddr, address _tokenManagerAddress, uint _depositRate, string _depositTokenSymbol ) external onlyOwner { priceOracleAddress = _priceOracleAddr; htlcGroupMap[_htlcAddr] = true; htlcGroupMap[_fastHtlcAddr] = true; depositOracleAddress = _depositOracleAddr; depositRate = _depositRate; depositTokenSymbol = _depositTokenSymbol; tokenManagerAddress = _tokenManagerAddress; } function setDebtOracle(address oracle) external onlyOwner { debtOracleAddress = oracle; } function setFastCrossMinValue(uint value) external onlyOwner { fastCrossMinValue = value; } /// @notice lock quota in mint direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userMintLock( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; uint mintQuota = getUserMintQuota(tokenId, storemanGroupId); require( mintQuota >= value, "Quota is not enough" ); if (!quota._active) { quota._active = true; storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId; storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId] .add(1); } quota.asset_receivable = quota.asset_receivable.add(value); } /// @notice lock quota in mint direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgMintLock( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; if (!quota._active) { quota._active = true; storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId; storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId] .add(1); } quota.debt_receivable = quota.debt_receivable.add(value); } /// @notice revoke quota in mint direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userMintRevoke( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota.asset_receivable = quota.asset_receivable.sub(value); } /// @notice revoke quota in mint direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgMintRevoke( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota.debt_receivable = quota.debt_receivable.sub(value); } /// @notice redeem quota in mint direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userMintRedeem( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota.debt_receivable = quota.debt_receivable.sub(value); quota._debt = quota._debt.add(value); } /// @notice redeem quota in mint direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgMintRedeem( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota.asset_receivable = quota.asset_receivable.sub(value); quota._asset = quota._asset.add(value); } /// @notice perform a fast crosschain mint /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userFastMint( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc checkMinValue(tokenId, value) { Quota storage quota = quotaMap[tokenId][storemanGroupId]; uint mintQuota = getUserMintQuota(tokenId, storemanGroupId); require( mintQuota >= value, "Quota is not enough" ); if (!quota._active) { quota._active = true; storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId; storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId] .add(1); } quota._asset = quota._asset.add(value); } /// @notice perform a fast crosschain mint /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgFastMint( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; if (!quota._active) { quota._active = true; storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId; storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId] .add(1); } quota._debt = quota._debt.add(value); } /// @notice perform a fast crosschain burn /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userFastBurn( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc checkMinValue(tokenId, value) { Quota storage quota = quotaMap[tokenId][storemanGroupId]; require(quota._debt.sub(quota.debt_payable) >= value, "Value is invalid"); quota._debt = quota._debt.sub(value); } /// @notice perform a fast crosschain burn /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgFastBurn( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota._asset = quota._asset.sub(value); } /// @notice lock quota in burn direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userBurnLock( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; require(quota._debt.sub(quota.debt_payable) >= value, "Value is invalid"); quota.debt_payable = quota.debt_payable.add(value); } /// @notice lock quota in burn direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgBurnLock( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota.asset_payable = quota.asset_payable.add(value); } /// @notice revoke quota in burn direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userBurnRevoke( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota.debt_payable = quota.debt_payable.sub(value); } /// @notice revoke quota in burn direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgBurnRevoke( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota.asset_payable = quota.asset_payable.sub(value); } /// @notice redeem quota in burn direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function userBurnRedeem( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota._asset = quota._asset.sub(value); quota.asset_payable = quota.asset_payable.sub(value); } /// @notice redeem quota in burn direction /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group /// @param value amount of exchange token function smgBurnRedeem( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; quota._debt = quota._debt.sub(value); quota.debt_payable = quota.debt_payable.sub(value); } /// @notice source storeman group lock the debt transaction,update the detailed quota info. of the storeman group /// @param srcStoremanGroupId PK of source storeman group /// @param dstStoremanGroupId PK of destination storeman group function debtLock( bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId ) external onlyHtlc { uint tokenCount = storemanTokenCountMap[srcStoremanGroupId]; // TODO gas out of range for (uint i = 0; i < tokenCount; i++) { uint id = storemanTokensMap[srcStoremanGroupId][i]; Quota storage src = quotaMap[id][srcStoremanGroupId]; require( src.debt_receivable == uint(0) && src.debt_payable == uint(0), "There are debt_receivable or debt_payable in src storeman" ); if (src._debt == 0) { continue; } Quota storage dst = quotaMap[id][dstStoremanGroupId]; if (!dst._active) { dst._active = true; storemanTokensMap[dstStoremanGroupId][storemanTokenCountMap[dstStoremanGroupId]] = id; storemanTokenCountMap[dstStoremanGroupId] = storemanTokenCountMap[dstStoremanGroupId] .add(1); } dst.debt_receivable = dst.debt_receivable.add(src._debt); src.debt_payable = src.debt_payable.add(src._debt); } } /// @notice destination storeman group redeem the debt transaction,update the detailed quota info. of the storeman group /// @param srcStoremanGroupId PK of source storeman group /// @param dstStoremanGroupId PK of destination storeman group function debtRedeem( bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId ) external onlyHtlc { uint tokenCount = storemanTokenCountMap[srcStoremanGroupId]; for (uint i = 0; i < tokenCount; i++) { uint id = storemanTokensMap[srcStoremanGroupId][i]; Quota storage src = quotaMap[id][srcStoremanGroupId]; if (src._debt == 0) { continue; } Quota storage dst = quotaMap[id][dstStoremanGroupId]; /// Adjust quota record dst.debt_receivable = dst.debt_receivable.sub(src.debt_payable); dst._debt = dst._debt.add(src._debt); src.debt_payable = 0; src._debt = 0; } } /// @notice source storeman group revoke the debt transaction,update the detailed quota info. of the storeman group /// @param srcStoremanGroupId PK of source storeman group /// @param dstStoremanGroupId PK of destination storeman group function debtRevoke( bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId ) external onlyHtlc { uint tokenCount = storemanTokenCountMap[srcStoremanGroupId]; for (uint i = 0; i < tokenCount; i++) { uint id = storemanTokensMap[srcStoremanGroupId][i]; Quota storage src = quotaMap[id][srcStoremanGroupId]; if (src._debt == 0) { continue; } Quota storage dst = quotaMap[id][dstStoremanGroupId]; dst.debt_receivable = dst.debt_receivable.sub(src.debt_payable); src.debt_payable = 0; } } /// @notice source storeman group lock the debt transaction,update the detailed quota info. of the storeman group /// @param srcStoremanGroupId PK of source storeman group /// @param dstStoremanGroupId PK of destination storeman group function assetLock( bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId ) external onlyHtlc { uint tokenCount = storemanTokenCountMap[srcStoremanGroupId]; for (uint i = 0; i < tokenCount; i++) { uint id = storemanTokensMap[srcStoremanGroupId][i]; Quota storage src = quotaMap[id][srcStoremanGroupId]; require( src.asset_receivable == uint(0) && src.asset_payable == uint(0), "There are asset_receivable or asset_payable in src storeman" ); if (src._asset == 0) { continue; } Quota storage dst = quotaMap[id][dstStoremanGroupId]; if (!dst._active) { dst._active = true; storemanTokensMap[dstStoremanGroupId][storemanTokenCountMap[dstStoremanGroupId]] = id; storemanTokenCountMap[dstStoremanGroupId] = storemanTokenCountMap[dstStoremanGroupId] .add(1); } dst.asset_receivable = dst.asset_receivable.add(src._asset); src.asset_payable = src.asset_payable.add(src._asset); } } /// @notice destination storeman group redeem the debt transaction,update the detailed quota info. of the storeman group /// @param srcStoremanGroupId PK of source storeman group /// @param dstStoremanGroupId PK of destination storeman group function assetRedeem( bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId ) external onlyHtlc { uint tokenCount = storemanTokenCountMap[srcStoremanGroupId]; for (uint i = 0; i < tokenCount; i++) { uint id = storemanTokensMap[srcStoremanGroupId][i]; Quota storage src = quotaMap[id][srcStoremanGroupId]; if (src._asset == 0) { continue; } Quota storage dst = quotaMap[id][dstStoremanGroupId]; /// Adjust quota record dst.asset_receivable = dst.asset_receivable.sub(src.asset_payable); dst._asset = dst._asset.add(src._asset); src.asset_payable = 0; src._asset = 0; } } /// @notice source storeman group revoke the debt transaction,update the detailed quota info. of the storeman group /// @param srcStoremanGroupId PK of source storeman group /// @param dstStoremanGroupId PK of destination storeman group function assetRevoke( bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId ) external onlyHtlc { uint tokenCount = storemanTokenCountMap[srcStoremanGroupId]; for (uint i = 0; i < tokenCount; i++) { uint id = storemanTokensMap[srcStoremanGroupId][i]; Quota storage src = quotaMap[id][srcStoremanGroupId]; if (src._asset == 0) { continue; } Quota storage dst = quotaMap[id][dstStoremanGroupId]; dst.asset_receivable = dst.asset_receivable.sub(src.asset_payable); src.asset_payable = 0; } } /// @notice get user mint quota of storeman, tokenId /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group function getUserMintQuota(uint tokenId, bytes32 storemanGroupId) public view returns (uint) { string memory symbol; uint decimals; uint tokenPrice; (symbol, decimals) = getTokenAncestorInfo(tokenId); tokenPrice = getPrice(symbol); if (tokenPrice == 0) { return 0; } uint fiatQuota = getUserFiatMintQuota(storemanGroupId, symbol); return fiatQuota.div(tokenPrice).mul(10**decimals).div(1 ether); } /// @notice get smg mint quota of storeman, tokenId /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group function getSmgMintQuota(uint tokenId, bytes32 storemanGroupId) public view returns (uint) { string memory symbol; uint decimals; uint tokenPrice; (symbol, decimals) = getTokenAncestorInfo(tokenId); tokenPrice = getPrice(symbol); if (tokenPrice == 0) { return 0; } uint fiatQuota = getSmgFiatMintQuota(storemanGroupId, symbol); return fiatQuota.div(tokenPrice).mul(10**decimals).div(1 ether); } /// @notice get user burn quota of storeman, tokenId /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group function getUserBurnQuota(uint tokenId, bytes32 storemanGroupId) public view returns (uint burnQuota) { Quota storage quota = quotaMap[tokenId][storemanGroupId]; burnQuota = quota._debt.sub(quota.debt_payable); } /// @notice get smg burn quota of storeman, tokenId /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group function getSmgBurnQuota(uint tokenId, bytes32 storemanGroupId) public view returns (uint burnQuota) { Quota storage quota = quotaMap[tokenId][storemanGroupId]; burnQuota = quota._asset.sub(quota.asset_payable); } /// @notice get asset of storeman, tokenId /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group function getAsset(uint tokenId, bytes32 storemanGroupId) public view returns (uint asset, uint asset_receivable, uint asset_payable) { Quota storage quota = quotaMap[tokenId][storemanGroupId]; return (quota._asset, quota.asset_receivable, quota.asset_payable); } /// @notice get debt of storeman, tokenId /// @param tokenId tokenPairId of crosschain /// @param storemanGroupId PK of source storeman group function getDebt(uint tokenId, bytes32 storemanGroupId) public view returns (uint debt, uint debt_receivable, uint debt_payable) { Quota storage quota = quotaMap[tokenId][storemanGroupId]; return (quota._debt, quota.debt_receivable, quota.debt_payable); } /// @notice get debt clean state of storeman /// @param storemanGroupId PK of source storeman group function isDebtClean(bytes32 storemanGroupId) external view returns (bool) { uint tokenCount = storemanTokenCountMap[storemanGroupId]; if (tokenCount == 0) { if (debtOracleAddress == address(0)) { return true; } else { IDebtOracle debtOracle = IDebtOracle(debtOracleAddress); return debtOracle.isDebtClean(storemanGroupId); } } for (uint i = 0; i < tokenCount; i++) { uint id = storemanTokensMap[storemanGroupId][i]; Quota storage src = quotaMap[id][storemanGroupId]; if (src._debt > 0 || src.debt_payable > 0 || src.debt_receivable > 0) { return false; } if (src._asset > 0 || src.asset_payable > 0 || src.asset_receivable > 0) { return false; } } return true; } /// @dev get minimize token count for fast cross chain function getFastMinCount(uint tokenId) public view returns (uint, string, uint, uint, uint) { if (fastCrossMinValue == 0) { return (0, "", 0, 0, 0); } string memory symbol; uint decimals; (symbol, decimals) = getTokenAncestorInfo(tokenId); uint price = getPrice(symbol); uint count = fastCrossMinValue.mul(10**decimals).div(price); return (fastCrossMinValue, symbol, decimals, price, count); } // ----------- Private Functions --------------- /// @notice get storeman group's deposit value in USD /// @param storemanGroupId storeman group ID function getFiatDeposit(bytes32 storemanGroupId) private view returns (uint) { uint deposit = getDepositAmount(storemanGroupId); return deposit.mul(getPrice(depositTokenSymbol)); } /// get mint quota in Fiat/USD decimals: 18 function getUserFiatMintQuota(bytes32 storemanGroupId, string rawSymbol) private view returns (uint) { string memory symbol; uint decimals; uint totalTokenUsedValue = 0; for (uint i = 0; i < storemanTokenCountMap[storemanGroupId]; i++) { uint id = storemanTokensMap[storemanGroupId][i]; (symbol, decimals) = getTokenAncestorInfo(id); Quota storage q = quotaMap[id][storemanGroupId]; uint tokenValue = q.asset_receivable.add(q._asset).mul(getPrice(symbol)).mul(1 ether).div(10**decimals); /// change Decimals to 18 digits totalTokenUsedValue = totalTokenUsedValue.add(tokenValue); } return getLastDeposit(storemanGroupId, rawSymbol, totalTokenUsedValue); } function getLastDeposit(bytes32 storemanGroupId, string rawSymbol, uint totalTokenUsedValue) private view returns (uint depositValue) { // keccak256("WAN") = 0x28ba6d5ac5913a399cc20b18c5316ad1459ae671dd23558d05943d54c61d0997 if (keccak256(rawSymbol) == bytes32(0x28ba6d5ac5913a399cc20b18c5316ad1459ae671dd23558d05943d54c61d0997)) { depositValue = getFiatDeposit(storemanGroupId); } else { depositValue = getFiatDeposit(storemanGroupId).mul(DENOMINATOR).div(depositRate); // 15000 = 150% } if (depositValue <= totalTokenUsedValue) { depositValue = 0; } else { depositValue = depositValue.sub(totalTokenUsedValue); /// decimals: 18 } } /// get mint quota in Fiat/USD decimals: 18 function getSmgFiatMintQuota(bytes32 storemanGroupId, string rawSymbol) private view returns (uint) { string memory symbol; uint decimals; uint totalTokenUsedValue = 0; for (uint i = 0; i < storemanTokenCountMap[storemanGroupId]; i++) { uint id = storemanTokensMap[storemanGroupId][i]; (symbol, decimals) = getTokenAncestorInfo(id); Quota storage q = quotaMap[id][storemanGroupId]; uint tokenValue = q.debt_receivable.add(q._debt).mul(getPrice(symbol)).mul(1 ether).div(10**decimals); /// change Decimals to 18 digits totalTokenUsedValue = totalTokenUsedValue.add(tokenValue); } uint depositValue = 0; if (keccak256(rawSymbol) == keccak256("WAN")) { depositValue = getFiatDeposit(storemanGroupId); } else { depositValue = getFiatDeposit(storemanGroupId).mul(DENOMINATOR).div(depositRate); // 15000 = 150% } if (depositValue <= totalTokenUsedValue) { return 0; } return depositValue.sub(totalTokenUsedValue); /// decimals: 18 } function getDepositAmount(bytes32 storemanGroupId) private view returns (uint) { _IStoremanGroup smgAdmin = _IStoremanGroup(depositOracleAddress); return smgAdmin.getDeposit(storemanGroupId); } function getTokenAncestorInfo(uint tokenId) private view returns (string ancestorSymbol, uint decimals) { _ITokenManager tokenManager = _ITokenManager(tokenManagerAddress); (ancestorSymbol,decimals) = tokenManager.getAncestorSymbol(tokenId); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function getPrice(string symbol) private view returns (uint price) { IOracle oracle = IOracle(priceOracleAddress); price = oracle.getValue(stringToBytes32(symbol)); } }
@notice lock quota in mint direction @param tokenId tokenPairId of crosschain @param storemanGroupId PK of source storeman group @param value amount of exchange token
function userMintLock( uint tokenId, bytes32 storemanGroupId, uint value ) external onlyHtlc { Quota storage quota = quotaMap[tokenId][storemanGroupId]; uint mintQuota = getUserMintQuota(tokenId, storemanGroupId); require( mintQuota >= value, "Quota is not enough" ); if (!quota._active) { quota._active = true; storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId; storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId] .add(1); } quota.asset_receivable = quota.asset_receivable.add(value); }
7,274,956
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 4766, 2176, 13257, 316, 312, 474, 4068, 632, 891, 1147, 548, 12900, 1147, 4154, 548, 434, 6828, 5639, 632, 891, 1707, 4728, 8722, 5375, 11327, 434, 1084, 1707, 4728, 1041, 632, 891, 460, 18701, 3844, 434, 7829, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 729, 49, 474, 2531, 12, 203, 3639, 2254, 1147, 548, 16, 203, 3639, 1731, 1578, 1707, 4728, 8722, 16, 203, 3639, 2254, 460, 203, 565, 262, 3903, 1338, 44, 14596, 288, 203, 3639, 4783, 25441, 2502, 13257, 273, 13257, 863, 63, 2316, 548, 6362, 2233, 4728, 8722, 15533, 203, 540, 203, 3639, 2254, 312, 474, 10334, 273, 4735, 49, 474, 10334, 12, 2316, 548, 16, 1707, 4728, 8722, 1769, 203, 3639, 2583, 12, 203, 5411, 312, 474, 10334, 1545, 460, 16, 203, 5411, 315, 10334, 353, 486, 7304, 6, 203, 3639, 11272, 203, 203, 3639, 309, 16051, 23205, 6315, 3535, 13, 288, 203, 5411, 13257, 6315, 3535, 273, 638, 31, 203, 5411, 1707, 4728, 5157, 863, 63, 2233, 4728, 8722, 6362, 2233, 4728, 1345, 1380, 863, 63, 2233, 4728, 8722, 13563, 273, 1147, 548, 31, 203, 5411, 1707, 4728, 1345, 1380, 863, 63, 2233, 4728, 8722, 65, 273, 1707, 4728, 1345, 1380, 863, 63, 2233, 4728, 8722, 65, 203, 7734, 263, 1289, 12, 21, 1769, 203, 3639, 289, 203, 203, 3639, 13257, 18, 9406, 67, 8606, 427, 429, 273, 13257, 18, 9406, 67, 8606, 427, 429, 18, 1289, 12, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.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 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"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.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 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/SandwichToken.sol pragma solidity 0.6.12; // SandwichToken with Governance. contract SandwichToken is ERC20("SandwichToken", "SWH"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SANDWICH::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SANDWICH::delegateBySig: invalid nonce"); require(now <= expiry, "SANDWICH::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SANDWICH::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SWHs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SANDWICH::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SandwichSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SandwichSwap must mint EXACTLY the same amount of SandwichSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Sandwich. He can make Sandwich and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SANDWICH is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SWHs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSandwichPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSandwichPerShare` (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 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SWHs to distribute per block. uint256 lastRewardBlock; // Last block number that SWHs distribution occurs. uint256 accSandwichPerShare; // Accumulated SWHs per share, times 1e12. See below. } // The SANDWICH TOKEN! SandwichToken public sandwich; // Dev address. address public devaddr; // Block number when bonus SWH period ends. uint256 public bonusEndBlock; // SANDWICH tokens created per block. uint256 public swhPerBlock; // Bonus muliplier for early sandwich makers. uint256 public constant BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SWH mining starts. uint256 public startBlock; 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); event SandwichOwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor( SandwichToken _sandwich, address _devaddr, uint256 _swhPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sandwich = _sandwich; devaddr = _devaddr; swhPerBlock = _swhPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSandwichPerShare: 0 })); } // Update the given pool's SANDWICH allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint,uint256 _lastRewardBlock, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lastRewardBlock = _lastRewardBlock; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // 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 0; } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER); } } // View function to see pending SWHs on frontend. function pendingSandwich(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSandwichPerShare = pool.accSandwichPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0 && pool.lastRewardBlock <= bonusEndBlock) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 swhReward = multiplier.mul(swhPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSandwichPerShare = accSandwichPerShare.add(swhReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSandwichPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables 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]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 swhReward = multiplier.mul(swhPerBlock).mul(pool.allocPoint).div(totalAllocPoint); //sandwich.mint(devaddr, swhReward.div(10));//delete devaddr reward sandwich.mint(address(this), swhReward); pool.accSandwichPerShare = pool.accSandwichPerShare.add(swhReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SANDWICH allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSandwichPerShare).div(1e12).sub(user.rewardDebt); safeSwhTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSandwichPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. 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.accSandwichPerShare).div(1e12).sub(user.rewardDebt); safeSwhTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSandwichPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); 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.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sandwich transfer function, just in case if rounding error causes pool to not have enough SWHs. function safeSwhTransfer(address _to, uint256 _amount) internal { uint256 sandwichBal = sandwich.balanceOf(address(this)); if (_amount > sandwichBal) { sandwich.transfer(_to, sandwichBal); } else { sandwich.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferTokenOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); sandwich.transferOwnership(newOwner); emit SandwichOwnershipTransferred(address(this),newOwner); } /** * @dev update th reward per block. * Can only be called by the current owner. */ function updateSwhPerBlock(uint256 _swhPerBlock) public virtual onlyOwner { swhPerBlock = _swhPerBlock; } /** * @dev reset mint period. * Can only be called by the current owner. */ function updateMintPeriod(uint256 _startBlock,uint256 _bonusEndBlock) public virtual onlyOwner { startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; } }
* @notice Gets the current votes balance for `account` @param account The address to get votes balance @return The number of current votes for `account`/
function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
17,059
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 11881, 326, 783, 19588, 11013, 364, 1375, 4631, 68, 632, 891, 2236, 1021, 1758, 358, 336, 19588, 11013, 632, 2463, 1021, 1300, 434, 783, 19588, 364, 1375, 4631, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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 290, 1564, 4139, 405, 374, 692, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 294, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x08B6863c0A81E477e39CcF2A4BfD14463B2F5847/sources/project_/contracts/RobotToken.sol
calculate amount of tokens to exchange from ether send tokens to buyer
fallback() external payable{ uint256 amount = msg.value; uint256 numberOfT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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 5922, 1435, 3903, 8843, 429, 95, 203, 3639, 2254, 5034, 3844, 273, 1234, 18, 1132, 31, 203, 3639, 2254, 5034, 7922, 5157, 33, 4604, 6275, 12, 3576, 18, 1132, 1769, 203, 3639, 19686, 352, 1345, 24899, 2316, 2934, 81, 474, 24899, 3576, 12021, 9334, 2696, 951, 5157, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * This code is licensed under the MIT License * * Copyright (c) 2019 Aion Foundation https://aion.network/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity ^0.4.15; contract Owned { address public owner; address public ownerCandidate; event ChangedOwner(address indexed _newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function Owned() internal { owner = msg.sender; } function changeOwner(address _newOwner) onlyOwner external { ownerCandidate = _newOwner; } function acceptOwnership() external { if (msg.sender == ownerCandidate) { owner = ownerCandidate; ownerCandidate = 0x0; ChangedOwner(owner); } } } contract Pausable is Owned { bool private paused = false; event Paused(); event Unpaused(); function isPaused() public constant returns (bool) { return paused; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() external onlyOwner whenNotPaused { paused = true; Paused(); } function unpause() external onlyOwner whenPaused { paused = false; Unpaused(); } } interface IBridgeSignatory { function isSignatory(address _signatoryAddress) public constant returns (bool); function signatoryCount() public constant returns (uint); } contract BridgeSignatory is IBridgeSignatory, Owned { string constant network = "Aion-Ethereum"; uint public minimumVotesRequired; bool public initializationMode = true; address[] public validSignatories; mapping(address => bytes32) public signatoryName; mapping(bytes32 => address[]) signedChanges; modifier onlyInitializationMode(){ require(initializationMode); _; } modifier onlySelfGovernanceMode(){ require(!initializationMode); _; } modifier onlySignatories(){ require(signatoryName[msg.sender] != 0); _; } modifier signatoryDoesNotExist(address _signatoryAddress) { require(signatoryName[_signatoryAddress] == 0); _; } modifier signatoryExists(address _signatoryAddress) { require(signatoryName[_signatoryAddress] != 0); _; } event SignatoryAdded(address indexed _signatoryAddress, bytes32 _signatoryName); event SignatoryRemoved(address indexed _signatoryAddress, bytes32 _signatoryName); event SignatureReceived(address indexed _signatoryAddress, bytes32 _signatoryName, uint _currentVoteCount, uint _minimumVotesRequired, bytes1 _operation); function BridgeSignatory(address[] _initialSignatoryAddresses, bytes32[] _initialSignatoryNames){ require(_initialSignatoryAddresses.length == _initialSignatoryNames.length); for (uint i = 0; i < _initialSignatoryAddresses.length; i++) { require(isUniqueSignatory(_initialSignatoryAddresses[i], _initialSignatoryNames[i])); signatoryName[_initialSignatoryAddresses[i]] = _initialSignatoryNames[i]; validSignatories.push(_initialSignatoryAddresses[i]); } } function() public payable { revert(); } /// @notice Add a new signatory /// @dev During the initialization mode only the owner has the authority to add a signatory to the list /// Once the self governance mode is initiated signatories will manage themselves /// With this implementation, owner can be a signatory function addSignatory(address _signatoryAddress, bytes32 _signatoryName) public onlyOwner onlyInitializationMode signatoryDoesNotExist(_signatoryAddress) { addToStorage(_signatoryAddress, _signatoryName); } /// @notice Remove a signatory /// @dev During the initialization mode only the owner has the authority to remove a signatory from the list /// Once the self governance mode is initiated signatories will manage themselves function removeSignatory(address _signatoryAddress, bytes32 _signatoryName) public onlyOwner onlyInitializationMode signatoryExists(_signatoryAddress) { deleteFromStorage(_signatoryAddress, _signatoryName); } /// @notice Submit vote to add a new signatory /// @dev During the self governance mode, majority of signatories should submit their vote for an action to be performed function submitAddSignatoryVote(address _signatoryAddress, bytes32 _signatoryName) public onlySignatories onlySelfGovernanceMode signatoryDoesNotExist(_signatoryAddress) { bytes32 hash = blake2b256(_signatoryAddress, _signatoryName, 0x1); //"add" signedChanges[hash].push(msg.sender); if (signedChanges[hash].length == minimumVotesRequired) { //delete form signedChanges because threshold can change //need to start from scratch every time voting begins delete signedChanges[hash]; addToStorage(_signatoryAddress, _signatoryName); } else { SignatureReceived(_signatoryAddress, _signatoryName, signedChanges[hash].length, minimumVotesRequired, 0x1); } } /// @notice Submit vote to remove a signatory /// @dev During the self governance mode, majority of signatories should submit their vote for an action to be performed function submitRemoveSignatoryVote(address _signatoryAddress, bytes32 _signatoryName) public onlySignatories onlySelfGovernanceMode signatoryExists(_signatoryAddress) { bytes32 hash = blake2b256(_signatoryAddress, signatoryName[_signatoryAddress], 0x2); //"remove" signedChanges[hash].push(msg.sender); if (signedChanges[hash].length == minimumVotesRequired) { //delete form signedChanges because threshold can change. //need to start from scratch every time voting begins. delete signedChanges[hash]; deleteFromStorage(_signatoryAddress, _signatoryName); } else { SignatureReceived(_signatoryAddress, signatoryName[_signatoryAddress], signedChanges[hash].length, minimumVotesRequired, 0x2); } } /// @notice Remove the caller from valid signatory list /// @dev This is possible in both self governance and initialization modes function removeSelfFromSignatoryList() public onlySignatories signatoryExists(msg.sender) { deleteFromStorage(msg.sender, signatoryName[msg.sender]); } /// @notice Starts the self governance mode /// @dev once the self governance mode is initialized owner does not have the power to add or remove signatories /// Mode cannot be reverted back to initialization. function initiateSelfGovernanceMode() public onlyInitializationMode onlyOwner { initializationMode = !initializationMode; } /// @return signatory address associated to the name if it exists function lookupName(bytes32 _signatoryName) constant public returns (address) { for (uint i = 0; i < validSignatories.length; i++) { if (signatoryName[validSignatories[i]] == _signatoryName) { return validSignatories[i]; } } return address(0); } /// @return true if the address is a valid signatory, false otherwise function isSignatory(address _signatoryAddress) public constant returns (bool) { return signatoryName[_signatoryAddress] != 0; } /// @return the number of valid signatories registered in the contract function signatoryCount() public constant returns (uint) { return validSignatories.length; } /// @return the list of valid signatories registered in the contract function getValidSignatoryList() public constant returns (address[] memory) { return validSignatories; } /// @dev Set the minimum number of votes required to add or remove a signatory function setMinimumVotesRequired(uint _newValue) private { require(_newValue != 0 && _newValue <= validSignatories.length); minimumVotesRequired = _newValue; } /// @notice recalculate the quorum threshold /// @dev It is done after each change to the signatory list /// Size of the signatory list can never be 0 function recalculateMinimumVotesRequired() private { if (!initializationMode) { if (validSignatories.length < 5) { setMinimumVotesRequired(validSignatories.length); } else { // compute majority setMinimumVotesRequired(uint((2 * validSignatories.length) / 3)); } } } /// @notice Remove the signatory from the list /// @dev Existence in array has been validated before function deleteFromStorage(address _signatoryAddress, bytes32 _signatoryName) private { require(signatoryName[_signatoryAddress] == _signatoryName); for (uint i = 0; i < validSignatories.length - 1; i++) { if (validSignatories[i] == _signatoryAddress) { validSignatories[i] = validSignatories[validSignatories.length - 1]; break; } } validSignatories.length -= 1; recalculateMinimumVotesRequired(); delete signatoryName[_signatoryAddress]; SignatoryRemoved(_signatoryAddress, _signatoryName); } /// @notice Add the signatory to list function addToStorage(address _signatoryAddress, bytes32 _signatoryName) private { require(isUniqueSignatory(_signatoryAddress, _signatoryName)); signatoryName[_signatoryAddress] = _signatoryName; validSignatories.push(_signatoryAddress); recalculateMinimumVotesRequired(); SignatoryAdded(_signatoryAddress, _signatoryName); } /// @return true if the signatory name and address do not exit in the list, false otherwise function isUniqueSignatory(address _signatoryAddress, bytes32 _signatoryName) private constant returns (bool){ return _signatoryAddress != address(0) && _signatoryName != 0 && lookupName(_signatoryName) == address(0); } } library AionBridgeHelpers { function addressArrayContains(address[] _array, address _value) internal constant returns (bool) { for (uint128 i = 0; i < _array.length; i++) { if (_array[i] == _value) { return true; } } return false; } /// @param _transferHash Hash of the transfer data to be validated /// @param _publicKey Public keys of the signatories who signed the hash /// @param _signaturePart1 First 32 bytes of the signatures /// @param _signaturePart2 Second 32 bytes of the signatures /// @param _signatoryContract Address of the contract containing valid signatories /// @return number of valid signatures recovered function getValidSignatureCount( bytes32 _transferHash, bytes32[] _publicKey, bytes32[] _signaturePart1, bytes32[] _signaturePart2, IBridgeSignatory _signatoryContract ) internal constant returns (uint128) { address[] memory recoveredSigners = new address[](_publicKey.length); uint128 recoveredSignerCount = 0; for (uint128 i = 0; i < _publicKey.length; i++) { if (isValidSignature(_transferHash, _publicKey[i], _signaturePart1[i], _signaturePart2[i])) { address recoveredAddress = recoverAionAddress(_publicKey[i]); if (_signatoryContract.isSignatory(recoveredAddress) && !addressArrayContains(recoveredSigners, recoveredAddress)) { recoveredSigners[recoveredSignerCount] = recoveredAddress; recoveredSignerCount ++; } } } return recoveredSignerCount; } /// @param _transferHash Hash of the transfer data to be validated /// @param _publicKey Public keys of the signatories who signed the hash /// @param _signaturePart1 First 32 bytes of the signatures /// @param _signaturePart2 Second 32 bytes of the signatures /// @param _signatoryContract Address of the contract containing valid signatories /// @param _quorumSize minimum number of valid signatures required /// @return true if _transferHash has been signed by the required number of signatories, false otherwise function hasEnoughValidSignatures( bytes32 _transferHash, bytes32[] _publicKey, bytes32[] _signaturePart1, bytes32[] _signaturePart2, IBridgeSignatory _signatoryContract, uint128 _quorumSize ) internal constant returns (bool) { address[] memory recoveredSigners = new address[](_quorumSize); for (uint128 i = 0; i < _publicKey.length; i++) { if (isValidSignature(_transferHash, _publicKey[i], _signaturePart1[i], _signaturePart2[i])) { address recoveredAddress = recoverAionAddress(_publicKey[i]); if (_signatoryContract.isSignatory(recoveredAddress) && !addressArrayContains(recoveredSigners, recoveredAddress)) { recoveredSigners[_quorumSize-1] = recoveredAddress; _quorumSize--; if (_quorumSize == 0) return true; } } } return false; } /// @notice verifies the signature /// @param _transferHash Hash of the transfer data to be validated /// @param _publicKey Public key of the signatory who signed the hash /// @param _signaturePart1 First 32 bytes of the signature /// @param _signaturePart2 Second 32 bytes of the signature /// @return true if _transferHash has been signed by the signatory holding _publicKey, false otherwise function isValidSignature( bytes32 _transferHash, bytes32 _publicKey, bytes32 _signaturePart1, bytes32 _signaturePart2 ) internal constant returns (bool) { return edverify(_transferHash, _publicKey, _signaturePart1, _signaturePart2) != address(0); } /// @notice recover Aion address from the public key function recoverAionAddress(bytes32 _publicKey) internal constant returns (address){ return address(blake2b256(_publicKey) & bytes32(0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | bytes32(0xa000000000000000000000000000000000000000000000000000000000000000)); } } contract AionBridgeAdapter is Pausable { //ETH bytes1 constant sourceNetworkId = 0x2; IBridgeSignatory public signatoryContract; uint128 public maximumBridgeTransactionGas; uint128 public transactionFee; uint128 requestId; address public relayer; uint public signatoryQuorumSize; //uint128 uint128 expectedSourceTransferId; bytes20 public sourceAdapterAddress; bool public acceptOnlyAuthorizedSenders; mapping(address => bool) public authorizedSenders; //mapping of transactionHash => blockNumber mapping(bytes32 => uint) public processedTransactions; //source events event BridgeTransferRequested(uint128 indexed _requestId, address indexed _transactionInitiator, bytes20 indexed _recipientContract, uint128 _gas, bytes _data); event AuthorizedSenderAdded(address indexed _newAuthorizedSender); event TransactionFeeUpdated(uint128 indexed _txFee); //destination events event Processed(uint128 indexed _sourceTransferId, bytes32 indexed _sourceTransactionHash, address indexed _recipientContract, bytes32 hash, bool result); event AlreadyProcessed(uint indexed _blockNumber); event RelayerChanged (address indexed _newRelayer); event SignatoryQuorumSizeChanged(uint indexed _newSignatoryQuorumSize); //uint128 event SignatoryContractAddressChanged(address indexed _newSignatoryContract); modifier onlyRelayer() { require(msg.sender == relayer); _; } modifier onlyAssociatedSourceAdaptor(bytes20 _sourceAdapterAddress) { require(sourceAdapterAddress == _sourceAdapterAddress); _; } function AionBridgeAdapter( address _signatoryContractAddress, address _relayer, uint _signatoryQuorumSize, //uint128 uint128 _maximumBridgeTransactionGas, uint128 _transactionFee, bool _acceptOnlyAuthorizedSenders) { signatoryContract = IBridgeSignatory(_signatoryContractAddress); relayer = _relayer; signatoryQuorumSize = _signatoryQuorumSize; maximumBridgeTransactionGas = _maximumBridgeTransactionGas; transactionFee = _transactionFee; acceptOnlyAuthorizedSenders = _acceptOnlyAuthorizedSenders; } function() public payable { revert(); } // ------------- destination ------------- /// @notice Processes a message transfer request originated on the Ethereum chain /// @dev Each source transaction is processed once and identified using the transaction hash /// Additionally, transactions are nonced to keep the order on both chains /// @param _sourceTransactionHash Transaction hash from the Ethereum adapter which contains the BridgeTransferRequested event /// @param _recipientContract Contract to call from this adapter /// @param _data Encoded function call and arguments /// @param _gas Amount of gas to be used by the function call /// @param _sourceTransferId Nonce of the Ethereum transfer request event /// @param _publicKey Public keys of signatories /// @param _signaturePart1 First 32 bytes of the signatures /// @param _signaturePart2 Second 32 bytes of the signatures function processTransfer( bytes32 _sourceTransactionHash, address _recipientContract, bytes _data, uint128 _gas, uint128 _sourceTransferId, bytes32[] _publicKey, bytes32[] _signaturePart1, bytes32[] _signaturePart2 ) public onlyRelayer { if (processedTransactions[_sourceTransactionHash] > 0) { AlreadyProcessed(processedTransactions[_sourceTransactionHash]); return; } // if the transaction hash has not been processed yet, it should be the next expected index require(_sourceTransferId == expectedSourceTransferId); require(_publicKey.length >= signatoryQuorumSize); bytes32 hash = computeTransferHash(_sourceTransactionHash, _recipientContract, _data, _gas, _sourceTransferId); require(AionBridgeHelpers.hasEnoughValidSignatures(hash, _publicKey, _signaturePart1, _signaturePart2, signatoryContract, signatoryQuorumSize)); bool result; if (_gas > 0) { result = _recipientContract.call.gas(_gas)(_data); } else { result = _recipientContract.call(_data); } processedTransactions[_sourceTransactionHash] = block.number; expectedSourceTransferId ++; Processed(_sourceTransferId, _sourceTransactionHash, _recipientContract, hash, result); } /// @notice Updates the associated Ethereum adapter contract address function setSourceAdapterAddress(bytes20 _newAdapterAddress) public onlyOwner { sourceAdapterAddress = _newAdapterAddress; } //uint128 /// @notice Updates the minimum number of signatures required function updateSignatoryQuorumSize(uint _newQuorumSize) public onlyOwner { //Quorum size should not be higher than the available signatories require(_newQuorumSize <= signatoryContract.signatoryCount()); signatoryQuorumSize = _newQuorumSize; SignatoryQuorumSizeChanged(signatoryQuorumSize); } /// @notice Updates the relayer account function updateRelayer(address _newRelayer) public onlyOwner { relayer = _newRelayer; RelayerChanged(relayer); } /// @notice Computes blake2b hash /// @param _sourceTransactionHash Transaction hash from the Ethereum adapter which contains the BridgeTransferRequested event /// @param _recipientContract Contract to call from this adapter /// @param _data Encoded function call and arguments /// @param _gas Amount of gas to be used by the function call /// @param _sourceTransferId Nonce of the Ethereum transfer request event function computeTransferHash( bytes32 _sourceTransactionHash, address _recipientContract, bytes _data, uint128 _gas, uint128 _sourceTransferId ) public constant returns (bytes32) { return blake2b256(_sourceTransactionHash, sourceAdapterAddress, _recipientContract, _data, _gas, _sourceTransferId, sourceNetworkId); } // ---------------------------------- // ------------- source ------------- /// @notice Generates a cross chain transfer request event to be picked up by the bridge /// @dev Contract owner can define a fee for each transaction relayed to Ethereum /// @param _destinationContract Recipient contract address to be called on Ethereum /// @param _data Encoded function call and arguments /// @param _gas Amount of gas to be used by the function call function requestTransfer( bytes20 _destinationContract, bytes _data, uint128 _gas ) external whenNotPaused payable { //ensure adapter can return the extra value require(msg.value == transactionFee || msg.value - transactionFee < this.balance); require(isAuthorizedSender(msg.sender)); require(0 <= _gas && _gas <= maximumBridgeTransactionGas); BridgeTransferRequested(requestId, msg.sender, _destinationContract, _gas, _data); requestId ++; //transfer the extra value back to the sender //Sender contract should be able to deal with the transferred balance if(msg.value > transactionFee){ msg.sender.transfer(msg.value - transactionFee); } } /// @notice Adds the address to the list of accounts authorized to request message transfers function addAuthorizedSender(address _newSender) public onlyOwner { // mode is not checked. It's not necessary to add senders only if we're validating them authorizedSenders[_newSender] = true; AuthorizedSenderAdded(_newSender); } /// @notice Set the policy to either accept requests from a pre-authorized list of senders or any address function setAuthorizedSenderPolicy(bool _acceptOnlyAuthorizedSenders) public onlyOwner { acceptOnlyAuthorizedSenders = _acceptOnlyAuthorizedSenders; } /// @notice Updates the maximum amount of gas that can be used on Ethereum to call a function function updateMaximumBridgeTransactionGas(uint128 _maximumBridgeTransactionGas) public onlyOwner { maximumBridgeTransactionGas = _maximumBridgeTransactionGas; } /// @notice Updates the fee for relaying each message to Ethereum function updateTransactionFee(uint128 _transactionFee) public onlyOwner { transactionFee = _transactionFee; TransactionFeeUpdated(transactionFee); } /// @return true if the address is authorized to request message transfers, false otherwise function isAuthorizedSender(address _senderAddress) public constant returns (bool){ if (!acceptOnlyAuthorizedSenders) return true; else return authorizedSenders[_senderAddress]; } /// @notice Update the contract address containing valid signatories function updateSignatoryContract(address _newSignatoryContract) public onlyOwner { signatoryContract = IBridgeSignatory(_newSignatoryContract); SignatoryContractAddressChanged(signatoryContract); } function destroy() onlyOwner public { selfdestruct(owner); } /// @notice Withdraw certain amount from the contract function withdraw(uint amount) onlyOwner returns (bool) { require(amount <= this.balance); owner.transfer(amount); return true; } }
@notice Adds the address to the list of accounts authorized to request message transfers mode is not checked. It's not necessary to add senders only if we're validating them
function addAuthorizedSender(address _newSender) public onlyOwner { authorizedSenders[_newSender] = true; AuthorizedSenderAdded(_newSender); }
12,720,370
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 15605, 326, 1758, 358, 326, 666, 434, 9484, 10799, 358, 590, 883, 29375, 1965, 353, 486, 5950, 18, 2597, 1807, 486, 4573, 358, 527, 1366, 414, 1338, 309, 732, 4565, 18075, 2182, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 15341, 12021, 12, 2867, 389, 2704, 12021, 13, 1071, 1338, 5541, 288, 203, 3639, 10799, 3826, 414, 63, 67, 2704, 12021, 65, 273, 638, 31, 203, 3639, 6712, 1235, 12021, 8602, 24899, 2704, 12021, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract HeroCoin is StandardToken { // data structures enum States { Initial, // deployment time ValuationSet, Ico, // whitelist addresses, accept funds, update balances Underfunded, // ICO time finished and minimal amount not raised Operational, // manage contests Paused // for contract upgrades } //should be constant, but is not, to avoid compiler warning address public rakeEventPlaceholderAddress = 0x0000000000000000000000000000000000000000; string public constant name = "Herocoin"; string public constant symbol = "PLAY"; uint8 public constant decimals = 18; mapping (address => bool) public whitelist; address public initialHolder; address public stateControl; address public whitelistControl; address public withdrawControl; States public state; uint256 public weiICOMinimum; uint256 public weiICOMaximum; uint256 public silencePeriod; uint256 public startAcceptingFundsBlock; uint256 public endBlock; uint256 public ETH_HEROCOIN; //number of herocoins per ETH mapping (address => uint256) lastRakePoints; uint256 pointMultiplier = 1e18; //100% = 1*10^18 points uint256 totalRakePoints; //total amount of rakes ever paid out as a points value. increases monotonically, but the number range is 2^256, that's enough. uint256 unclaimedRakes; //amount of coins unclaimed. acts like a special entry to balances uint256 constant percentForSale = 30; mapping (address => bool) public contests; // true if this address holds a contest //this creates the contract and stores the owner. it also passes in 3 addresses to be used later during the lifetime of the contract. function HeroCoin(address _stateControl, address _whitelistControl, address _withdraw, address _initialHolder) { initialHolder = _initialHolder; stateControl = _stateControl; whitelistControl = _whitelistControl; withdrawControl = _withdraw; moveToState(States.Initial); weiICOMinimum = 0; //to be overridden weiICOMaximum = 0; endBlock = 0; ETH_HEROCOIN = 0; totalSupply = 2000000000 * pointMultiplier; //sets the value in the superclass. balances[initialHolder] = totalSupply; //initially, initialHolder has 100% } event ContestAnnouncement(address addr); event Whitelisted(address addr); event Credited(address addr, uint balance, uint txAmount); event StateTransition(States oldState, States newState); modifier onlyWhitelist() { require(msg.sender == whitelistControl); _; } modifier onlyOwner() { require(msg.sender == initialHolder); _; } modifier onlyStateControl() { require(msg.sender == stateControl); _; } modifier onlyWithdraw() { require(msg.sender == withdrawControl); _; } modifier requireState(States _requiredState) { require(state == _requiredState); _; } /** BEGIN ICO functions */ //this is the main funding function, it updates the balances of Herocoins during the ICO. //no particular incentive schemes have been implemented here //it is only accessible during the "ICO" phase. function() payable requireState(States.Ico) { require(whitelist[msg.sender] == true); require(this.balance <= weiICOMaximum); //note that msg.value is already included in this.balance require(block.number < endBlock); require(block.number >= startAcceptingFundsBlock); uint256 heroCoinIncrease = msg.value * ETH_HEROCOIN; balances[initialHolder] -= heroCoinIncrease; balances[msg.sender] += heroCoinIncrease; Credited(msg.sender, balances[msg.sender], msg.value); } function moveToState(States _newState) internal { StateTransition(state, _newState); state = _newState; } // ICO contract configuration function // newEthICOMinimum is the minimum amount of funds to raise // newEthICOMaximum is the maximum amount of funds to raise // silencePeriod is a number of blocks to wait after starting the ICO. No funds are accepted during the silence period. It can be set to zero. // newEndBlock is the absolute block number at which the ICO must stop. It must be set after now + silence period. function updateEthICOThresholds(uint256 _newWeiICOMinimum, uint256 _newWeiICOMaximum, uint256 _silencePeriod, uint256 _newEndBlock) onlyStateControl { require(state == States.Initial || state == States.ValuationSet); require(_newWeiICOMaximum > _newWeiICOMinimum); require(block.number + silencePeriod < _newEndBlock); require(block.number < _newEndBlock); weiICOMinimum = _newWeiICOMinimum; weiICOMaximum = _newWeiICOMaximum; silencePeriod = _silencePeriod; endBlock = _newEndBlock; // initial conversion rate of ETH_HEROCOIN set now, this is used during the Ico phase. ETH_HEROCOIN = ((totalSupply * percentForSale) / 100) / weiICOMaximum; // check pointMultiplier moveToState(States.ValuationSet); } function startICO() onlyStateControl requireState(States.ValuationSet) { require(block.number < endBlock); require(block.number + silencePeriod < endBlock); startAcceptingFundsBlock = block.number + silencePeriod; moveToState(States.Ico); } function endICO() onlyStateControl requireState(States.Ico) { if (this.balance < weiICOMinimum) { moveToState(States.Underfunded); } else { burnUnsoldCoins(); moveToState(States.Operational); } } function anyoneEndICO() requireState(States.Ico) { require(block.number > endBlock); if (this.balance < weiICOMinimum) { moveToState(States.Underfunded); } else { burnUnsoldCoins(); moveToState(States.Operational); } } function burnUnsoldCoins() internal { uint256 soldcoins = this.balance * ETH_HEROCOIN; totalSupply = soldcoins * 100 / percentForSale; balances[initialHolder] = totalSupply - soldcoins; //slashing the initial supply, so that the ico is selling 30% total } function addToWhitelist(address _whitelisted) onlyWhitelist // requireState(States.Ico) { whitelist[_whitelisted] = true; Whitelisted(_whitelisted); } //emergency pause for the ICO function pause() onlyStateControl requireState(States.Ico) { moveToState(States.Paused); } //in case we want to completely abort function abort() onlyStateControl requireState(States.Paused) { moveToState(States.Underfunded); } //un-pause function resumeICO() onlyStateControl requireState(States.Paused) { moveToState(States.Ico); } //in case of a failed/aborted ICO every investor can get back their money function requestRefund() requireState(States.Underfunded) { require(balances[msg.sender] > 0); //there is no need for updateAccount(msg.sender) since the token never became active. uint256 payout = balances[msg.sender] / ETH_HEROCOIN; //reverse calculate the amount to pay out balances[msg.sender] = 0; msg.sender.transfer(payout); } //after the ico has run its course, the withdraw account can drain funds bit-by-bit as needed. function requestPayout(uint _amount) onlyWithdraw //very important! requireState(States.Operational) { msg.sender.transfer(_amount); } /** END ICO functions */ /** BEGIN ERC20 functions */ function transfer(address _to, uint256 _value) requireState(States.Operational) updateAccount(msg.sender) //update senders rake before transfer, so they can access their full balance updateAccount(_to) //update receivers rake before transfer as well, to avoid over-attributing rake enforceRake(msg.sender, _value) returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) requireState(States.Operational) updateAccount(_from) //update senders rake before transfer, so they can access their full balance updateAccount(_to) //update receivers rake before transfer as well, to avoid over-attributing rake enforceRake(_from, _value) returns (bool success) { return super.transferFrom(_from, _to, _value); } function balanceOf(address _account) constant returns (uint256 balance) { return balances[_account] + rakesOwing(_account); } function payRake(uint256 _value) requireState(States.Operational) updateAccount(msg.sender) returns (bool success) { return payRakeInternal(msg.sender, _value); } function payRakeInternal(address _sender, uint256 _value) internal returns (bool success) { if (balances[_sender] <= _value) { return false; } if (_value != 0) { Transfer(_sender, rakeEventPlaceholderAddress, _value); balances[_sender] -= _value; unclaimedRakes += _value; // calc amount of points from total: uint256 pointsPaid = _value * pointMultiplier / totalSupply; totalRakePoints += pointsPaid; } return true; } /** END ERC20 functions */ /** BEGIN Rake modifier updateAccount */ modifier updateAccount(address _account) { uint256 owing = rakesOwing(_account); if (owing != 0) { unclaimedRakes -= owing; balances[_account] += owing; Transfer(rakeEventPlaceholderAddress, _account, owing); } //also if 0 this needs to be called, since lastRakePoints need the right value lastRakePoints[_account] = totalRakePoints; _; } //todo use safemath.sol function rakesOwing(address _account) internal constant returns (uint256) {//returns always > 0 value //how much is _account owed, denominated in points from total supply uint256 newRakePoints = totalRakePoints - lastRakePoints[_account]; //always positive //weigh by my balance (dimension HC*10^18) uint256 basicPoints = balances[_account] * newRakePoints; //still positive //normalize to dimension HC by moving comma left by 18 places return (basicPoints) / pointMultiplier; } /** END Rake modifier updateAccount */ // contest management functions modifier enforceRake(address _contest, uint256 _value){ //we calculate 1% of the total value, rounded up. division would round down otherwise. //explicit brackets illustrate that the calculation only round down when dividing by 100, to avoid an expression // like value * (99/100) if (contests[_contest]) { uint256 toPay = _value - ((_value * 99) / 100); bool paid = payRakeInternal(_contest, toPay); require(paid); } _; } // all functions require HeroCoin operational state // registerContest declares a contest to HeroCoin. // It must be called from an address that has HeroCoin. // This address is recorded as the contract admin. function registerContest() { contests[msg.sender] = true; ContestAnnouncement(msg.sender); } }
in case we want to completely abort
function abort() onlyStateControl requireState(States.Paused) { moveToState(States.Underfunded); }
12,862,539
[ 1, 4625, 348, 7953, 560, 30, 316, 648, 732, 2545, 358, 14416, 6263, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6263, 1435, 203, 565, 1338, 1119, 3367, 203, 565, 2583, 1119, 12, 7629, 18, 28590, 13, 203, 565, 288, 203, 3639, 13863, 1119, 12, 7629, 18, 14655, 12125, 785, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy 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 stable rate and 2 for variable 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); 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); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; 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); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; 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); function getReserveTotalBorrowsStable(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 ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ 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); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; 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"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } 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); } } } } pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. 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); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; 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; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; 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( DFSExchangeData.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( DFSExchangeData.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); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, 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 getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.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(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; 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(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; 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 wrapper; 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)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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"); } } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; 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); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; 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 burnGas(20) { 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs 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 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; 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, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _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(managerAddr, _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, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _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(managerAddr, _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 _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).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 _managerAddr Address of the CDP Manager /// @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(address _managerAddr, 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(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, 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(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).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 /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).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(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _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 _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _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); } 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); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; 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}); } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; 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; } pragma solidity ^0.6.0; import "./Gem.sol"; 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; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @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(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; 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_NOT_ZEROX_EXCHANGE = "Zerox exchange 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(EXCHANGE_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; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } 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(EXCHANGE_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; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } 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 (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @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); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; 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); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; 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; } } pragma solidity ^0.6.0; 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); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; 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; } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, 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; } 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 ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).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, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).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, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; 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); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; 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)))); } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; 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); function borrowCaps(address) external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; 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); } } pragma solidity ^0.6.0; import "./CarefulMath.sol"; 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; } } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, 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)", market, ETH_ADDR, ethAmount)); // 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(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @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)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet 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; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @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(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { 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(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ 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); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); 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; ManagerType managerType; } 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 burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).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(managerAddr).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 _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); 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(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _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(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _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 ); } } } pragma solidity ^0.6.0; 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); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; 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, (_collAmount + collSwaped)); 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 {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @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 getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring 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); } } } pragma solidity ^0.6.0; /// @title Implements enum Method 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; } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; 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)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } 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); } } } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay 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 = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; 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( DFSExchangeData.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.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (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( DFSExchangeData.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.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (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; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; 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); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @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 onlyOwner { 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 onlyOwner { 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 onlyOwner { 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 onlyOwner { 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 onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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 } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, 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]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _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 _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } 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); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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 } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { 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; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _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) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} 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 sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( 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( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _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"; } } receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // 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) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); 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) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); 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); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage 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, DFSExchangeData.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); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; 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: "" }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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(); } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; 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; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // 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 { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; 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] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost 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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; 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; ManagerType managerType; } 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, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); 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 managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).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(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).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 managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _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(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _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(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; 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; 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; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _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 + _closeData.flFee); (, 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(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).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(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_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 {} } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy 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); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy 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); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; 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 DSProxy 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) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); 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)); } } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @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 cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow 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 function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // 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, _market, _rateMode, _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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; 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 DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @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 _market, 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(_market, _collateralToken, _borrowToken, _ethAmount, 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; 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 DSProxy 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, 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)); } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; 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); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; 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 (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 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); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 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); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; 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 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.user = msg.sender; 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: _amount}(); // 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)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy 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)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy 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)); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions 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; uint borrowCap; } 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]), borrowCap: comp.borrowCaps(_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(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system 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 = 1500000; uint public BOOST_GAS_COST = 1000000; 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 As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @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); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; 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; exData.user = _user; // 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; exData.user = _user; // 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.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(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions 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(); } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; 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(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet 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)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, 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) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(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.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin 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, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(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, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(user); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @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)}(); } } } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 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 = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_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( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) 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,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (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, "AutomaticAaveRepayV2", 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( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) 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,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (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, "AutomaticAaveBoostV2", 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); AaveSubscriptionsV2.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(AAVE_MARKET_ADDRESS, _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) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _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 As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @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; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @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 Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is 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 onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { 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 onlyOwner { 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 onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; 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); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } 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); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); 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].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, 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(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); 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 (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, 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(_market, _users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // 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 coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, 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)}(); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; 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 As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @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; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; 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; uint256 borrowRate; 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].borrowRate,,,,,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]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_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]); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); 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 { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; 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); } } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract 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(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @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(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract 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(); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; 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); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; 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; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges 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); }
@notice Fetches Aave collateral factors for tokens @param _market Address of LendingPoolAddressesProvider for specific market @param _tokens Arr. of tokens for which to get the coll. factors @return collFactors Array of coll. factors
function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } }
381,324
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 8065, 281, 432, 836, 4508, 2045, 287, 14490, 364, 2430, 632, 891, 389, 27151, 5267, 434, 511, 2846, 2864, 7148, 2249, 364, 2923, 13667, 632, 891, 389, 7860, 10371, 18, 434, 2430, 364, 1492, 358, 336, 326, 4508, 18, 14490, 632, 2463, 4508, 23535, 1510, 434, 4508, 18, 14490, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 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, 336, 13535, 23535, 12, 2867, 389, 27151, 16, 1758, 8526, 3778, 389, 7860, 13, 1071, 1476, 1135, 261, 11890, 5034, 8526, 3778, 4508, 23535, 13, 288, 203, 3639, 467, 37, 836, 5752, 20757, 58, 22, 14383, 273, 4303, 2249, 24899, 27151, 1769, 203, 3639, 4508, 23535, 273, 394, 2254, 5034, 8526, 24899, 7860, 18, 2469, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 7860, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 261, 16, 12910, 23535, 63, 77, 6487, 30495, 16408, 16, 13, 273, 14383, 18, 588, 607, 6527, 1750, 751, 24899, 7860, 63, 77, 19226, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; contract SafeMath { function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } contract Token { /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant public returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant public 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 ,SafeMath{ function transfer(address _to, uint256 _value) public returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = safeSubtract(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value) ; emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to],_value) ; balances[_from] = safeSubtract(balances[_from],_value) ; allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); emit Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract POCCToken is StandardToken { // metadata string public constant name = "POCC Token"; string public constant symbol = "POCC"; uint256 public constant decimals = 18; string public version = "1.0"; uint256 public tokenExchangeRate = 80000; // 80000 tokens per 1 ETH address public owner; //owner // events event DecreaseSupply(uint256 _value); // constructor constructor(address _owner) public { owner = _owner; totalSupply = safeMult(10000000000,10 ** decimals); balances[owner] = totalSupply; } modifier onlyOwner { require(msg.sender == owner); _; } /// @dev decrease the token's supply function decreaseSupply (uint256 _value) onlyOwner public{ if (balances[owner] < _value) revert(); uint256 value = safeMult(_value , 10 ** decimals); balances[owner] = safeSubtract(balances[owner],value); totalSupply = safeSubtract(totalSupply, value); emit DecreaseSupply(value); } }
@dev decrease the token's supply
function decreaseSupply (uint256 _value) onlyOwner public{ if (balances[owner] < _value) revert(); uint256 value = safeMult(_value , 10 ** decimals); balances[owner] = safeSubtract(balances[owner],value); totalSupply = safeSubtract(totalSupply, value); emit DecreaseSupply(value); }
5,458,426
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 20467, 326, 1147, 1807, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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254, 5034, 460, 273, 4183, 5049, 24899, 1132, 269, 1728, 2826, 15105, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 4183, 27904, 12, 70, 26488, 63, 8443, 6487, 1132, 1769, 203, 3639, 2078, 3088, 1283, 273, 4183, 27904, 12, 4963, 3088, 1283, 16, 460, 1769, 203, 3639, 3626, 31073, 448, 3088, 1283, 12, 1132, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "../story/story.sol"; import "../register.sol"; /// @title Scene /// @author ["Cryptape Technologies <[email protected]>"] contract Scene { Register register; string public name; string public description; uint location_x; uint location_y; address public proxy; // 0 none 1 talk 2 fight uint8 public kind; address public owner; /// Constructor constructor( address _owner, string _name, address _proxy ) public { register = Register(msg.sender); owner = _owner; name = _name; proxy = _proxy; } modifier onlyOperator { require(msg.sender == register.sceneOpAddr(), "not operator"); _; } modifier onlyOwner(address _owner) { require(owner == _owner, "not owner"); _; } /// @notice Set name function setName(string _name, address _owner) public onlyOperator onlyOwner(_owner) returns (bool) { name = _name; return true; } /// @notice Set description function setDescription(string _description, address _owner) public onlyOperator onlyOwner(_owner) returns (bool) { description = _description; return true; } /// @notice Set location function setLocation(uint x, uint y, address _owner) public onlyOperator onlyOwner(_owner) returns (bool) { location_x = x; location_y = y; return true; } /// @notice Set kind function setKind(uint8 _kind, address _owner) public onlyOperator onlyOwner(_owner) returns (bool) { kind = _kind; return true; } /// @notice Set proxy function setProxy(address _proxy, address _owner) public onlyOperator onlyOwner(_owner) returns (bool) { proxy = _proxy; return true; } /// @notice Call proxy process function function process(address _to, uint256 decision, address _owner) public onlyOperator onlyOwner(_owner) returns (bool) { Story(proxy).process(_owner, _to, decision); return true; } /// @notice Call proxy info function function info() public view returns (bytes32[8]) { return Story(proxy).info(msg.sender); } /// @notice Get the location function location() public view returns (uint x, uint y) { return (location_x, location_y); } }
@notice Call proxy info function
function info() public view returns (bytes32[8]) { return Story(proxy).info(msg.sender); }
13,051,823
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 3049, 2889, 1123, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1123, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 1578, 63, 28, 5717, 203, 565, 288, 203, 3639, 327, 934, 630, 12, 5656, 2934, 1376, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 >=0.8.10 >=0.8.0 <0.9.0; pragma experimental ABIEncoderV2; /* pragma solidity ^0.8.0; */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /* pragma solidity ^0.8.0; */ 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); } } /* 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); } /* pragma solidity ^0.8.0; */ /* import "../IERC20.sol"; */ /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) /* pragma solidity ^0.8.0; */ /* import "./IERC20.sol"; */ /* import "./extensions/IERC20Metadata.sol"; */ /* import "../../utils/Context.sol"; */ /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } ////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) /* pragma solidity ^0.8.0; */ // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } ////// src/IUniswapV2Factory.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } ////// src/IUniswapV2Pair.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } ////// src/IUniswapV2Router02.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /* pragma solidity >=0.8.10; */ /* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ contract POD is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = false; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("PumpOrDump", "POD") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 6; uint256 _buyLiquidityFee = 1; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 1; uint256 _sellDevFee = 1; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 7_000_000 * 1e18; // 0.7% from total supply maxTransactionAmountTxn maxWallet = 14_000_000 * 1e18; // 1.4% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x32b7a41fc956549e9dF64A0b055239004c13F8E4); // set as marketing wallet devWallet = address(0x32b7a41fc956549e9dF64A0b055239004c13F8E4); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
1.4% from total supply maxWallet
maxWallet = 14_000_000 * 1e18;
10,233,494
[ 1, 4625, 348, 7953, 560, 30, 225, 404, 18, 24, 9, 628, 2078, 14467, 943, 16936, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 16936, 273, 5045, 67, 3784, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-30 */ /** *Submitted for verification at Etherscan.io on 2022-04-20 */ /** *Submitted for verification at Etherscan.io on 2022-04-14 */ // SPDX-License-Identifier: UNLICENSED /* tg: elonsbird twitter: elonsbirdeth website: elonsbird.com */ 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 elonsbird is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Elon's Bird"; string private constant _symbol = "ELONSBIRD"; 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 = 1000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; //Buy Fee uint256 private _redisFeeOnBuy = 1; uint256 private _taxFeeOnBuy = 12; //Sell Fee uint256 private _redisFeeOnSell = 1; uint256 private _taxFeeOnSell = 12; //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 => uint256) private cooldown; address payable private _developmentAddress = payable(0xBD1bD4529bd0C4065AE7e287cf9695D783141ff4); address payable private _marketingAddress = payable(0x60E0EdaCB6c6D39c5d7A41378E3c0287058Ac295); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen = false; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 10000 * 10**9; //1% uint256 public _maxWalletSize = 30000 * 10**9; //3% uint256 public _swapTokensAtAmount = 4000 * 10**9; //.4% event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { //Trade start check 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; //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; } } }
Buy FeeSell FeeOriginal Fee
contract elonsbird is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Elon's Bird"; string private constant _symbol = "ELONSBIRD"; 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 = 1000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _redisFeeOnBuy = 1; uint256 private _taxFeeOnBuy = 12; uint256 private _redisFeeOnSell = 1; uint256 private _taxFeeOnSell = 12; 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(0xBD1bD4529bd0C4065AE7e287cf9695D783141ff4); address payable private _marketingAddress = payable(0x60E0EdaCB6c6D39c5d7A41378E3c0287058Ac295); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen = false; 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; 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; } 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; } } }
15,400,808
[ 1, 4625, 348, 7953, 560, 30, 605, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 415, 7008, 31245, 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, 4958, 265, 1807, 605, 6909, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 2247, 673, 14541, 7937, 40, 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, 15088, 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, 404, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 2593, 31, 203, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 404, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 55, 1165, 273, 2593, 31, 203, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 273, 389, 12311, 14667, 1398, 55, 1165, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 273, 389, 8066, 14667, 1398, 55, 1165, 31, 203, 203, 565, 2254, 5034, 3238, 389, 11515, 12311, 14667, 273, 389, 12311, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 1484, 522, 83, 641, 651, 14667, 273, 389, 8066, 14667, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 2512, 87, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 27367, 2378, 31, 203, 203, 565, 1758, 8843, 429, 3238, 389, 26630, 1887, 273, 8843, 429, 12, 20, 92, 18096, 21, 70, 40, 7950, 5540, 16410, 20, 39, 7132, 9222, 16985, 27, 73, 6030, 27, 8522, 29, 8148, 25, 40, 8285, 23, 3461, 21, 1403, 24, 1769, 203, 565, 1758, 8843, 429, 3238, 389, 3355, 21747, 1887, 273, 8843, 429, 12, 20, 92, 4848, 41, 20, 41, 2414, 8876, 26, 71, 26, 40, 5520, 71, 25, 72, 27, 37, 24, 3437, 8285, 41, 23, 71, 3103, 11035, 6260, 28, 9988, 29286, 1769, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 1284, 7459, 3678, 273, 629, 31, 203, 565, 1426, 3238, 316, 12521, 273, 629, 31, 203, 565, 1426, 3238, 7720, 1526, 273, 638, 31, 203, 203, 203, 565, 871, 4238, 4188, 6275, 7381, 12, 11890, 5034, 389, 1896, 4188, 6275, 1769, 203, 565, 9606, 2176, 1986, 12521, 288, 203, 3639, 316, 12521, 273, 638, 31, 203, 3639, 389, 31, 203, 3639, 316, 12521, 273, 629, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 288, 203, 203, 3639, 389, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 67, 26630, 1887, 65, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 67, 3355, 21747, 1887, 65, 273, 638, 31, 203, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 3576, 12021, 9334, 389, 88, 5269, 1769, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 16618, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 16618, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 88, 5269, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1147, 1265, 9801, 24899, 86, 5460, 329, 63, 4631, 19226, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 389, 13866, 24899, 3576, 12021, 9334, 8027, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 203, 3639, 2 ]
./partial_match/1/0x33d6282665DECC570C0b5a8B34465c1029A5C9f6/sources/PEANUT.sol
set as marketing wallet
marketingWallet = address(0x059b43B631e1BE848973Afc5e587A8585014937B);
9,176,775
[ 1, 4625, 348, 7953, 560, 30, 225, 444, 487, 13667, 310, 9230, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13667, 310, 16936, 273, 1758, 12, 20, 92, 20, 6162, 70, 8942, 38, 4449, 21, 73, 21, 5948, 5193, 6675, 9036, 37, 7142, 25, 73, 8204, 27, 37, 7140, 7140, 1611, 7616, 6418, 38, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]