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: GPL-3.0
pragma solidity 0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title Friendship contract
/// @author Mauro Molinari
/// @notice This contract can be use to keep track of friend requests and friends of its users
/// @dev Friend requests and Friends structs contains the pubKey used by Textile to talk with each other in the app
contract Friends is Ownable, Pausable {
// Friend request struct containing the sender address with the associated pubKey used by Textile
struct FriendRequest {
address sender;
string pubKey;
}
// Friend struct containing the dweller address with the associated pubKey used by Textile
struct Friend {
address dweller;
string pubKey;
}
// Constant kept to clear previous requests or friends
uint MAX_UINT = 2**256 - 1;
// All friend requests received by an address
mapping(address => FriendRequest[]) private requests;
// Tracks the index of each friend request inside the mapping
mapping(address => mapping(address => uint)) private requestsTracker;
// All friends that an address has
mapping(address => Friend[]) private friends;
// Tracks the index of each Friend inside the mapping
mapping(address => mapping(address => uint)) private friendsTracker;
/// @notice Request sent event
/// @param to Receiver of the request
event FriendRequestSent(address indexed to);
/// @notice Request accepted event
/// @param from Original sender of the request
event FriendRequestAccepted(address indexed from);
/// @notice Request denied event
/// @param from Original sender of the request
event FriendRequestDenied(address indexed from);
/// @notice Request removed event
/// @param to Receiver of the request
event FriendRequestRemoved(address indexed to);
/// @notice Friend removed event
/// @param friendRemoved Friend removed
event FriendRemoved(address indexed friendRemoved);
/// @notice Returns a friend from the friends mapping
/// @param _from From friend address
/// @param _toGet To friend address
/// @return fr Friend from the mapping
function _getFriend(address _from, address _toGet) private view returns (Friend memory fr) {
uint index = friendsTracker[_from][_toGet];
require(index != 0, "Friend does not exist");
return friends[_from][index - 1];
}
/// @notice Adds a friend to the friends mapping
/// @param _to To friend address
/// @param fr Friend to add
function _addFriend(address _to, Friend memory fr) private {
friends[_to].push(fr);
uint index = friends[_to].length;
friendsTracker[_to][fr.dweller] = index;
}
/// @notice Removes a friend from the friends mapping
/// @param _from From friend address
/// @param _toRemove To remove friend address
function _removeFriend(address _from, address _toRemove) private {
require(friends[_from].length > 0, "There are no friends to remove");
// Index of the element to remove
uint index = friendsTracker[_from][_toRemove] - 1;
uint lastIndex = friends[_from].length - 1;
if(index != lastIndex){
// Last friend inside the array
Friend memory last = friends[_from][lastIndex];
// Change the last with the element to remove
friends[_from][index] = last;
// Update the Index
friendsTracker[_from][last.dweller] = index + 1;
}
// Clear the previous index by setting the maximum integer
friendsTracker[_from][_toRemove] = MAX_UINT;
// Reduce the size of the array by 1
friends[_from].pop();
}
/// @notice Returns a friend request from the requests mapping
/// @param _from From friend address
/// @param _toGet To friend address
/// @return fr FriendRequest from the mapping
function _getRequest(address _from, address _toGet) private view returns (FriendRequest memory fr) {
uint index = requestsTracker[_from][_toGet];
require(index != 0, "Request does not exist");
return requests[_from][index];
}
/// @notice Adds a friend request to the requests mapping
/// @param _to To friend address
/// @param _from From friend address
function _addRequest(address _to, FriendRequest memory _from) private {
requests[_to].push(_from);
uint index = requests[_to].length;
requestsTracker[_to][_from.sender] = index;
requestsTracker[_from.sender][_to] = index;
}
/// @notice Removes a friend request from the requests mapping
/// @param _from From friend address
/// @param _toRemove To remove friend address
function _removeRequest(address _from, address _toRemove) private {
require(requests[_from].length > 0, "There are no requests to remove");
// Index of the element to remove
uint index = requestsTracker[_from][_toRemove] - 1;
uint lastIndex = requests[_from].length - 1;
if(index != lastIndex){
// Last friend inside the array
FriendRequest memory last = requests[_from][lastIndex];
// Change the last with the element to remove
requests[_from][index] = last;
// Update the Index
requestsTracker[_from][last.sender] = index + 1;
}
// Clear the previous index by setting the maximum integer
requestsTracker[_from][_toRemove] = MAX_UINT;
requestsTracker[_toRemove][_from] = MAX_UINT;
// Reduce the size of the array by 1
requests[_from].pop();
}
/// @notice Add a new friend request to the mapping
/// @param _to To friend address
/// @param _pubKey PubKey associated with the request
function makeRequest(address _to, string memory _pubKey) public whenNotPaused {
uint index = requestsTracker[_to][msg.sender];
require(msg.sender != _to, "You cannot send a friend request to yourself");
// You have already sent a friend request to this address
require(index == 0 || index == MAX_UINT, "Friend request already sent");
// You have already received a friend request from this address
require(requestsTracker[msg.sender][_to] == 0 || requestsTracker[msg.sender][_to] == MAX_UINT, "Friend request already sent");
// Must not be friend
require(friendsTracker[msg.sender][_to] == 0 || friendsTracker[msg.sender][_to] == MAX_UINT, "You are already friends");
_addRequest(
_to,
FriendRequest(msg.sender, _pubKey)
);
emit FriendRequestSent(_to);
}
/// @notice Accept a friend request
/// @param _from From friend address
/// @param pubKey PubKey associated with the request
function acceptRequest(address _from, string memory pubKey) public whenNotPaused {
uint friendRequestIndex = requestsTracker[msg.sender][_from];
// Check if the friend request has already been removed
require(friendRequestIndex != MAX_UINT, "Friend request has been removed");
// Check if the request exist
FriendRequest memory friendRequest = requests[msg.sender][friendRequestIndex - 1];
require(friendRequest.sender != address(0), "Request does not exist");
Friend memory senderFriend = Friend(
_from,
friendRequest.pubKey
);
Friend memory receiverFriend = Friend(
msg.sender,
pubKey
);
_removeRequest(msg.sender, friendRequest.sender);
_addFriend(msg.sender, senderFriend);
_addFriend(friendRequest.sender, receiverFriend);
emit FriendRequestAccepted(_from);
}
/// @notice Deny a friend request
/// @param _from From friend address
function denyRequest(address _from) public whenNotPaused {
uint friendRequestIndex = requestsTracker[msg.sender][_from];
// Check if the friend request exist
require(friendRequestIndex != 0, "Friend request does not exist");
// Check if the friend request has already been removed
require(friendRequestIndex != MAX_UINT, "Friend request has been removed");
_removeRequest(msg.sender, _from);
emit FriendRequestDenied(_from);
}
/// @notice Remove a friend request from the mapping
/// @param to To friend address
function removeRequest(address to) public whenNotPaused {
uint index = requestsTracker[to][msg.sender];
require(index != 0, "Friend request does not exist");
_removeRequest(to, msg.sender);
emit FriendRequestRemoved(to);
}
/// @notice Remove a friend from the mapping
/// @param _toRemove To friend address
function removeFriend(address _toRemove) public whenNotPaused {
uint index = friendsTracker[msg.sender][_toRemove];
require(index != 0, "Friend does not exist");
_removeFriend(msg.sender, _toRemove);
_removeFriend(_toRemove, msg.sender);
emit FriendRemoved(_toRemove);
}
/// @notice Returns the friends list related to the msg.sender
/// @return Friends mapping related
function getFriends() public view returns (Friend[] memory) {
return friends[msg.sender];
}
/// @notice Returns the requests list directed to the msg.sender
/// @return Friends requests mapping related
function getRequests() public view returns (FriendRequest[] memory) {
return requests[msg.sender];
}
/// @notice Pause the contract
/// @dev Only the owner can pause the contract
function pauseContract() public onlyOwner whenNotPaused {
_pause();
}
/// @notice Unpause the contract
/// @dev Only the owner can unpause the contract
function unpauseContract() public onlyOwner whenPaused {
_unpause();
}
} | Reduce the size of the array by 1 | requests[_from].pop();
| 12,810,985 | [
1,
12944,
326,
963,
434,
326,
526,
635,
404,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3285,
63,
67,
2080,
8009,
5120,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4436485155E81382b8DE76b29d4f79C52C27AAF7/sources/contracts/dao/ERC1155Dao.sol | @notice only auction winner can widthdraw the token. Signature : `0xf45f4bb7` | error OnlyWinnerToWidthdraw();
| 5,682,192 | [
1,
3700,
279,
4062,
5657,
1224,
848,
1835,
9446,
326,
1147,
18,
9249,
294,
1375,
20,
5841,
7950,
74,
24,
9897,
27,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
555,
5098,
59,
7872,
774,
2384,
9446,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xdAbb2487cA1e14E39F70fd414D06d05e2262587F/sources/browser/DEFI1.sol | Symbol : DEFI1 Name : DeFi1 Mint 120,000,000 DeFi1 (18 Decimals) | constructor() public ERC20 ("DeFi1", "DEFI1") {
_mint(msg.sender, 120000000e18);
}
| 14,176,433 | [
1,
5335,
294,
2030,
1653,
21,
1770,
294,
1505,
42,
77,
21,
490,
474,
15743,
16,
3784,
16,
3784,
1505,
42,
77,
21,
261,
2643,
3416,
11366,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
3885,
1435,
1071,
4232,
39,
3462,
7566,
758,
42,
77,
21,
3113,
315,
1639,
1653,
21,
7923,
288,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
2593,
17877,
73,
2643,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/libraries/CurveMath.sol | @dev The fixed point arithmetic results in output that's a close approximation to the true real value, but could be skewed in either direction. The output from this function should not be consumed in any context that requires strict boundness. / | function invertFlow (uint128 liq, uint128 price, uint128 denomFlow,
bool isBuy, bool inBaseQty) private pure returns (uint128) {
uint256 invertReserve = reserveAtPrice(liq, price, !inBaseQty);
uint256 initReserve = reserveAtPrice(liq, price, inBaseQty);
unchecked {
uint256 endReserve = (isBuy == inBaseQty) ?
uint256 endInvert = uint256(liq) * uint256(liq) / endReserve;
return (endInvert > invertReserve ?
endInvert - invertReserve :
invertReserve - endInvert).toUint128();
}
}
| 4,651,654 | [
1,
1986,
5499,
1634,
30828,
1686,
316,
876,
716,
1807,
279,
1746,
24769,
282,
358,
326,
638,
2863,
460,
16,
1496,
3377,
506,
20001,
329,
316,
3344,
4068,
18,
1021,
876,
282,
628,
333,
445,
1410,
486,
506,
12393,
316,
1281,
819,
716,
4991,
5490,
282,
2489,
4496,
18,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9848,
5249,
261,
11890,
10392,
4501,
85,
16,
2254,
10392,
6205,
16,
2254,
10392,
10716,
5249,
16,
203,
7682,
1426,
27057,
9835,
16,
1426,
316,
2171,
53,
4098,
13,
3238,
16618,
1135,
261,
11890,
10392,
13,
288,
203,
203,
3639,
2254,
5034,
9848,
607,
6527,
273,
20501,
861,
5147,
12,
549,
85,
16,
6205,
16,
401,
267,
2171,
53,
4098,
1769,
203,
3639,
2254,
5034,
1208,
607,
6527,
273,
20501,
861,
5147,
12,
549,
85,
16,
6205,
16,
316,
2171,
53,
4098,
1769,
203,
203,
3639,
22893,
288,
203,
3639,
2254,
5034,
679,
607,
6527,
273,
261,
291,
38,
9835,
422,
316,
2171,
53,
4098,
13,
692,
203,
540,
203,
3639,
2254,
5034,
679,
382,
1097,
273,
2254,
5034,
12,
549,
85,
13,
380,
2254,
5034,
12,
549,
85,
13,
342,
679,
607,
6527,
31,
203,
3639,
327,
261,
409,
382,
1097,
405,
9848,
607,
6527,
692,
203,
7734,
679,
382,
1097,
300,
9848,
607,
6527,
294,
203,
7734,
9848,
607,
6527,
300,
679,
382,
1097,
2934,
869,
5487,
10392,
5621,
203,
3639,
289,
203,
377,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-20
*/
/*
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.9;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* C U ON THE MOON
* 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);
}
}
}
}
abstract contract Context {
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
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 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 IDexPair {
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;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
interface IAntiSnipe {
function setTokenOwner(address owner) external;
function onPreTransferCheck(
address from,
address to,
uint256 amount
) external returns (bool checked);
}
contract MetaNami is IERC20, Ownable {
using Address for address;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
string constant _name = "Meta Nami";
string constant _symbol = "NAMI";
uint8 constant _decimals = 9;
uint256 _totalSupply = 100_000_000 * (10 ** _decimals);
uint256 _maxBuyTxAmount = (_totalSupply * 1) / 400;
uint256 _maxSellTxAmount = (_totalSupply * 1) / 400;
uint256 _maxWalletSize = (_totalSupply * 1) / 100;
mapping (address => uint256) _balances;
mapping (address => uint256) firstBuy;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) isFeeExempt;
mapping (address => bool) isTxLimitExempt;
mapping (address => bool) liquidityCreator;
uint256 devFee = 200;
uint256 marketingFee = 600;
uint256 poolFee = 300;
uint256 totalFees = marketingFee + devFee;
uint256 sellBias = 0;
uint256 highFeePeriod = 24 hours;
uint256 highFeeMult = 250;
uint256 feeDenominator = 10000;
address public liquidityFeeReceiver;
address payable public marketingFeeReceiver = payable(0x007a79d2bAe62770942C866E419D32001fd4Dd06);
address payable public devReceiver1;
address payable public devReceiver2;
address public poolReceiver;
IDEXRouter public router;
//address routerAddress = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3;
//address routerAddress = 0x10ED43C718714eb63d5aA57B78B54704E256024E;
address routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
mapping (address => bool) liquidityPools;
IAntiSnipe public antisnipe;
bool public protectionEnabled = true;
bool public protectionDisabled = false;
address public pair;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
uint256 public launchedAt;
uint256 public launchedTime;
uint256 public deadBlocks = 1;
bool public swapEnabled = false;
uint256 public swapThreshold = _totalSupply / 200;
uint256 public swapMinimum = _totalSupply / 10000;
bool inSwap;
modifier swapping() { inSwap = true; _; inSwap = false; }
constructor (address _dev1, address _dev2) {
router = IDEXRouter(routerAddress);
pair = IDEXFactory(router.factory()).createPair(address(this),router.WETH());
liquidityPools[pair] = true;
_allowances[owner()][routerAddress] = type(uint256).max;
_allowances[address(this)][routerAddress] = type(uint256).max;
isFeeExempt[owner()] = true;
liquidityCreator[owner()] = true;
liquidityFeeReceiver = msg.sender;
poolReceiver = marketingFeeReceiver;
devReceiver1 = payable(_dev1);
devReceiver2 = payable(_dev2);
isTxLimitExempt[address(this)] = true;
isTxLimitExempt[owner()] = true;
isTxLimitExempt[routerAddress] = true;
isTxLimitExempt[DEAD] = true;
_balances[owner()] = _totalSupply;
emit Transfer(address(0), owner(), _totalSupply);
}
receive() external payable { }
function totalSupply() external view override returns (uint256) { return _totalSupply; }
function decimals() external pure returns (uint8) { return _decimals; }
function symbol() external pure returns (string memory) { return _symbol; }
function name() external pure returns (string memory) { return _name; }
function getOwner() external view returns (address) { return owner(); }
function maxBuyTxTokens() external view returns (uint256) { return _maxBuyTxAmount / (10 ** _decimals); }
function maxSellTxTokens() external view returns (uint256) { return _maxSellTxAmount / (10 ** _decimals); }
function maxWalletTokens() external view returns (uint256) { return _maxWalletSize / (10 ** _decimals); }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, type(uint256).max);
}
function airdrop(address[] calldata addresses, uint256[] calldata amounts) external onlyOwner {
require(addresses.length > 0 && amounts.length == addresses.length);
address from = msg.sender;
for (uint i = 0; i < addresses.length; i++) {
if(!liquidityPools[addresses[i]] && !liquidityCreator[addresses[i]]) {
_basicTransfer(from, addresses[i], amounts[i] * (10 ** _decimals));
}
}
}
function rescueToken(address tokenAddress, uint256 tokens) external onlyOwner
returns (bool success)
{
return IERC20(tokenAddress).transfer(msg.sender, tokens);
}
function claimMarketing() external onlyOwner {
uint256 bal = address(this).balance;
uint256 amountMarketing = (bal * marketingFee) / (marketingFee + devFee);
uint256 amountDev = (bal * devFee) / (marketingFee + devFee);
if (amountMarketing > 0)
marketingFeeReceiver.transfer(amountMarketing);
if (amountDev > 0) {
devReceiver1.transfer(amountDev / 2);
devReceiver2.transfer(amountDev / 2);
}
}
function setProtectionEnabled(bool _protect) external onlyOwner {
if (_protect)
require(!protectionDisabled);
protectionEnabled = _protect;
}
function setProtection(address _protection, bool _call) external onlyOwner {
if (_protection != address(antisnipe)){
require(!protectionDisabled);
antisnipe = IAntiSnipe(_protection);
}
if (_call)
antisnipe.setTokenOwner(msg.sender);
}
function disableProtection() external onlyOwner {
protectionDisabled = true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != type(uint256).max){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(amount > 0, "Amount must be > zero");
require(_balances[sender] >= amount, "Insufficient balance");
if(!launched() && liquidityPools[recipient]){ require(liquidityCreator[sender], "Liquidity not added yet."); launch(); }
checkTxLimit(sender, amount);
if (!liquidityPools[recipient] && recipient != DEAD) {
if(_balances[recipient] == 0) {
firstBuy[recipient] = block.timestamp;
}
if (!isTxLimitExempt[recipient]) {
checkWalletLimit(recipient, amount);
}
}
if(inSwap){ return _basicTransfer(sender, recipient, amount); }
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) && shouldTakeFee(recipient) ? takeFee(sender, recipient, amount) : amount;
if(shouldSwapBack(recipient)){ if (amount > 0) swapBack(amount); }
_balances[recipient] = _balances[recipient] + amountReceived;
if (protectionEnabled)
antisnipe.onPreTransferCheck(sender, recipient, amount);
emit Transfer(sender, recipient, amountReceived);
return true;
}
function launched() internal view returns (bool) {
return launchedTime != 0;
}
function launch() internal {
launchedAt = block.number;
launchedTime = block.timestamp;
swapEnabled = true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender] - amount;
_balances[recipient] = _balances[recipient] + amount;
emit Transfer(sender, recipient, amount);
return true;
}
function checkWalletLimit(address recipient, uint256 amount) internal view {
uint256 walletLimit = _maxWalletSize;
require(_balances[recipient] + amount <= walletLimit, "Transfer amount exceeds the bag size.");
}
function checkTxLimit(address sender, uint256 amount) internal view {
require(isTxLimitExempt[sender] || amount <= (liquidityPools[sender] ? _maxBuyTxAmount : _maxSellTxAmount), "TX Limit Exceeded");
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function getTotalFee(bool selling, bool highPeriod) public view returns (uint256) {
if(launchedAt + deadBlocks > block.number){ return feeDenominator - 1; }
if (selling) return highPeriod ? (totalFees * highFeeMult) / 100 : totalFees + sellBias;
return highPeriod ? (totalFees * highFeeMult) / 100 : totalFees - sellBias;
}
function takeFee(address from, address recipient, uint256 amount) internal returns (uint256) {
bool selling = liquidityPools[recipient];
uint256 feeAmount = (amount * getTotalFee(selling, !liquidityPools[from] && firstBuy[from] + highFeePeriod > block.timestamp)) / feeDenominator;
uint256 poolAmount;
if (poolFee > 0){
poolAmount = (amount * poolFee) / feeDenominator;
_balances[poolReceiver] += poolAmount;
emit Transfer(from, poolReceiver, poolAmount);
}
if (feeAmount > 0) {
_balances[address(this)] += feeAmount;
emit Transfer(from, address(this), feeAmount);
}
return amount - (feeAmount + poolAmount);
}
function shouldSwapBack(address recipient) internal view returns (bool) {
return !liquidityPools[msg.sender]
&& !inSwap
&& swapEnabled
&& liquidityPools[recipient]
&& _balances[address(this)] >= swapMinimum &&
totalFees > 0;
}
function swapBack(uint256 amount) internal swapping {
uint256 amountToSwap = amount < swapThreshold ? amount : swapThreshold;
if (_balances[address(this)] < amountToSwap) amountToSwap = _balances[address(this)];
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidityPool(address lp, bool isPool) external onlyOwner {
require(lp != pair, "Can't alter current liquidity pair");
liquidityPools[lp] = isPool;
emit UpdatedSettings(isPool ? 'Liquidity Pool Enabled' : 'Liquidity Pool Disabled', [Log(toString(abi.encodePacked(lp)), 1), Log('', 0), Log('', 0)]);
}
function switchRouter(address newRouter, address newPair) external onlyOwner {
router = IDEXRouter(newRouter);
pair = newPair;
liquidityPools[newPair] = true;
isTxLimitExempt[newRouter] = true;
emit UpdatedSettings('Exchange Router Updated', [Log(concatenate('New Router: ',toString(abi.encodePacked(newRouter))), 1),Log(concatenate('New Liquidity Pair: ',toString(abi.encodePacked(pair))), 1), Log('', 0)]);
}
function excludePresaleAddress(address presaleAddress) external onlyOwner {
liquidityCreator[presaleAddress] = true;
isTxLimitExempt[presaleAddress] = true;
isFeeExempt[presaleAddress] = true;
emit UpdatedSettings('Presale Setup', [Log(concatenate('Presale Address: ',toString(abi.encodePacked(presaleAddress))), 1), Log('', 0), Log('', 0)]);
}
function setTxLimit(uint256 buyNumerator, uint256 sellNumerator, uint256 divisor) external onlyOwner {
require(buyNumerator > 0 && sellNumerator > 0 && divisor > 0 && divisor <= 10000);
_maxBuyTxAmount = (_totalSupply * buyNumerator) / divisor;
_maxSellTxAmount = (_totalSupply * sellNumerator) / divisor;
emit UpdatedSettings('Maximum Transaction Size', [Log('Max Buy Tokens', _maxBuyTxAmount / (10 ** _decimals)), Log('Max Sell Tokens', _maxSellTxAmount / (10 ** _decimals)), Log('', 0)]);
}
function setMaxWallet(uint256 numerator, uint256 divisor) external onlyOwner() {
require(numerator > 0 && divisor > 0 && divisor <= 10000);
_maxWalletSize = (_totalSupply * numerator) / divisor;
emit UpdatedSettings('Maximum Wallet Size', [Log('Tokens', _maxWalletSize / (10 ** _decimals)), Log('', 0), Log('', 0)]);
}
function setIsFeeExempt(address holder, bool exempt) external onlyOwner {
isFeeExempt[holder] = exempt;
emit UpdatedSettings(exempt ? 'Fees Removed' : 'Fees Enforced', [Log(toString(abi.encodePacked(holder)), 1), Log('', 0), Log('', 0)]);
}
function setIsTxLimitExempt(address holder, bool exempt) external onlyOwner {
isTxLimitExempt[holder] = exempt;
emit UpdatedSettings(exempt ? 'Transaction Limit Removed' : 'Transaction Limit Enforced', [Log(toString(abi.encodePacked(holder)), 1), Log('', 0), Log('', 0)]);
}
function setFees(uint256 _marketingFee, uint256 _devFee, uint256 _poolFee, uint256 _sellBias, uint256 _feeDenominator) external onlyOwner {
marketingFee = _marketingFee;
devFee = _devFee;
poolFee = _poolFee;
totalFees = _devFee + _marketingFee;
sellBias = _sellBias;
feeDenominator = _feeDenominator;
require(totalFees + poolFee < feeDenominator / 2);
emit UpdatedSettings('Fees', [Log('Total Fee Percent', totalFees * 100 / feeDenominator), Log('Marketing Percent', _marketingFee * 100 / feeDenominator), Log('Dev Percent', _devFee * 100 / feeDenominator)]);
}
function setFeeReceivers(address _liquidityFeeReceiver, address _marketingFeeReceiver, address _dev1, address _dev2, address _poolReceiver) external onlyOwner {
liquidityFeeReceiver = payable(_liquidityFeeReceiver);
marketingFeeReceiver = payable(_marketingFeeReceiver);
devReceiver1 = payable(_dev1);
devReceiver2 = payable(_dev2);
poolReceiver = _poolReceiver;
emit UpdatedSettings('Fee Receivers', [Log(concatenate('Liquidity Receiver: ',toString(abi.encodePacked(_liquidityFeeReceiver))), 1),Log(concatenate('Marketing Receiver: ',toString(abi.encodePacked(_marketingFeeReceiver))), 1), Log(concatenate('Pool Receiver: ',toString(abi.encodePacked(_poolReceiver))), 1)]);
}
function setSwapBackSettings(bool _enabled, uint256 _denominator, uint256 _swapMinimumDenom) external onlyOwner {
require(_denominator > 0);
swapEnabled = _enabled;
swapThreshold = _totalSupply / _denominator;
swapMinimum = _totalSupply / _swapMinimumDenom;
emit UpdatedSettings('Swap Settings', [Log('Enabled', _enabled ? 1 : 0),Log('Swap Maximum', swapThreshold), Log('Swap Minimum', swapMinimum)]);
}
function getCirculatingSupply() public view returns (uint256) {
return _totalSupply - (balanceOf(DEAD) + balanceOf(ZERO));
}
function burnLP(uint256 percent) external onlyOwner {
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 5 && percent > 0, "Max of 5% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 pairBalance = this.balanceOf(pair);
_basicTransfer(pair, DEAD, (pairBalance * percent) / 100);
IDexPair(pair).sync();
}
function toString(bytes memory data) internal pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
function concatenate(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
struct Log {
string name;
uint256 value;
}
event UpdatedSettings(string name, Log[3] values);
//C U ON THE MOON
} | address routerAddress = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3;address routerAddress = 0x10ED43C718714eb63d5aA57B78B54704E256024E; | contract MetaNami is IERC20, Ownable {
using Address for address;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
string constant _name = "Meta Nami";
string constant _symbol = "NAMI";
uint8 constant _decimals = 9;
uint256 _totalSupply = 100_000_000 * (10 ** _decimals);
uint256 _maxBuyTxAmount = (_totalSupply * 1) / 400;
uint256 _maxSellTxAmount = (_totalSupply * 1) / 400;
uint256 _maxWalletSize = (_totalSupply * 1) / 100;
mapping (address => uint256) _balances;
mapping (address => uint256) firstBuy;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) isFeeExempt;
mapping (address => bool) isTxLimitExempt;
mapping (address => bool) liquidityCreator;
uint256 devFee = 200;
uint256 marketingFee = 600;
uint256 poolFee = 300;
uint256 totalFees = marketingFee + devFee;
uint256 sellBias = 0;
uint256 highFeePeriod = 24 hours;
uint256 highFeeMult = 250;
uint256 feeDenominator = 10000;
address public liquidityFeeReceiver;
address payable public marketingFeeReceiver = payable(0x007a79d2bAe62770942C866E419D32001fd4Dd06);
address payable public devReceiver1;
address payable public devReceiver2;
address public poolReceiver;
IDEXRouter public router;
address routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
mapping (address => bool) liquidityPools;
IAntiSnipe public antisnipe;
bool public protectionEnabled = true;
bool public protectionDisabled = false;
address public pair;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
uint256 public launchedAt;
uint256 public launchedTime;
uint256 public deadBlocks = 1;
bool public swapEnabled = false;
uint256 public swapThreshold = _totalSupply / 200;
uint256 public swapMinimum = _totalSupply / 10000;
bool inSwap;
modifier swapping() { inSwap = true; _; inSwap = false; }
constructor (address _dev1, address _dev2) {
router = IDEXRouter(routerAddress);
pair = IDEXFactory(router.factory()).createPair(address(this),router.WETH());
liquidityPools[pair] = true;
_allowances[owner()][routerAddress] = type(uint256).max;
_allowances[address(this)][routerAddress] = type(uint256).max;
isFeeExempt[owner()] = true;
liquidityCreator[owner()] = true;
liquidityFeeReceiver = msg.sender;
poolReceiver = marketingFeeReceiver;
devReceiver1 = payable(_dev1);
devReceiver2 = payable(_dev2);
isTxLimitExempt[address(this)] = true;
isTxLimitExempt[owner()] = true;
isTxLimitExempt[routerAddress] = true;
isTxLimitExempt[DEAD] = true;
_balances[owner()] = _totalSupply;
emit Transfer(address(0), owner(), _totalSupply);
}
receive() external payable { }
function totalSupply() external view override returns (uint256) { return _totalSupply; }
function decimals() external pure returns (uint8) { return _decimals; }
function symbol() external pure returns (string memory) { return _symbol; }
function name() external pure returns (string memory) { return _name; }
function getOwner() external view returns (address) { return owner(); }
function maxBuyTxTokens() external view returns (uint256) { return _maxBuyTxAmount / (10 ** _decimals); }
function maxSellTxTokens() external view returns (uint256) { return _maxSellTxAmount / (10 ** _decimals); }
function maxWalletTokens() external view returns (uint256) { return _maxWalletSize / (10 ** _decimals); }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, type(uint256).max);
}
function airdrop(address[] calldata addresses, uint256[] calldata amounts) external onlyOwner {
require(addresses.length > 0 && amounts.length == addresses.length);
address from = msg.sender;
for (uint i = 0; i < addresses.length; i++) {
if(!liquidityPools[addresses[i]] && !liquidityCreator[addresses[i]]) {
_basicTransfer(from, addresses[i], amounts[i] * (10 ** _decimals));
}
}
}
function airdrop(address[] calldata addresses, uint256[] calldata amounts) external onlyOwner {
require(addresses.length > 0 && amounts.length == addresses.length);
address from = msg.sender;
for (uint i = 0; i < addresses.length; i++) {
if(!liquidityPools[addresses[i]] && !liquidityCreator[addresses[i]]) {
_basicTransfer(from, addresses[i], amounts[i] * (10 ** _decimals));
}
}
}
function airdrop(address[] calldata addresses, uint256[] calldata amounts) external onlyOwner {
require(addresses.length > 0 && amounts.length == addresses.length);
address from = msg.sender;
for (uint i = 0; i < addresses.length; i++) {
if(!liquidityPools[addresses[i]] && !liquidityCreator[addresses[i]]) {
_basicTransfer(from, addresses[i], amounts[i] * (10 ** _decimals));
}
}
}
function rescueToken(address tokenAddress, uint256 tokens) external onlyOwner
returns (bool success)
{
return IERC20(tokenAddress).transfer(msg.sender, tokens);
}
function claimMarketing() external onlyOwner {
uint256 bal = address(this).balance;
uint256 amountMarketing = (bal * marketingFee) / (marketingFee + devFee);
uint256 amountDev = (bal * devFee) / (marketingFee + devFee);
if (amountMarketing > 0)
marketingFeeReceiver.transfer(amountMarketing);
if (amountDev > 0) {
devReceiver1.transfer(amountDev / 2);
devReceiver2.transfer(amountDev / 2);
}
}
function claimMarketing() external onlyOwner {
uint256 bal = address(this).balance;
uint256 amountMarketing = (bal * marketingFee) / (marketingFee + devFee);
uint256 amountDev = (bal * devFee) / (marketingFee + devFee);
if (amountMarketing > 0)
marketingFeeReceiver.transfer(amountMarketing);
if (amountDev > 0) {
devReceiver1.transfer(amountDev / 2);
devReceiver2.transfer(amountDev / 2);
}
}
function setProtectionEnabled(bool _protect) external onlyOwner {
if (_protect)
require(!protectionDisabled);
protectionEnabled = _protect;
}
function setProtection(address _protection, bool _call) external onlyOwner {
if (_protection != address(antisnipe)){
require(!protectionDisabled);
antisnipe = IAntiSnipe(_protection);
}
if (_call)
antisnipe.setTokenOwner(msg.sender);
}
function setProtection(address _protection, bool _call) external onlyOwner {
if (_protection != address(antisnipe)){
require(!protectionDisabled);
antisnipe = IAntiSnipe(_protection);
}
if (_call)
antisnipe.setTokenOwner(msg.sender);
}
function disableProtection() external onlyOwner {
protectionDisabled = true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != type(uint256).max){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != type(uint256).max){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(amount > 0, "Amount must be > zero");
require(_balances[sender] >= amount, "Insufficient balance");
checkTxLimit(sender, amount);
if (!liquidityPools[recipient] && recipient != DEAD) {
if(_balances[recipient] == 0) {
firstBuy[recipient] = block.timestamp;
}
if (!isTxLimitExempt[recipient]) {
checkWalletLimit(recipient, amount);
}
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) && shouldTakeFee(recipient) ? takeFee(sender, recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (protectionEnabled)
antisnipe.onPreTransferCheck(sender, recipient, amount);
emit Transfer(sender, recipient, amountReceived);
return true;
}
if(!launched() && liquidityPools[recipient]){ require(liquidityCreator[sender], "Liquidity not added yet."); launch(); }
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(amount > 0, "Amount must be > zero");
require(_balances[sender] >= amount, "Insufficient balance");
checkTxLimit(sender, amount);
if (!liquidityPools[recipient] && recipient != DEAD) {
if(_balances[recipient] == 0) {
firstBuy[recipient] = block.timestamp;
}
if (!isTxLimitExempt[recipient]) {
checkWalletLimit(recipient, amount);
}
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) && shouldTakeFee(recipient) ? takeFee(sender, recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (protectionEnabled)
antisnipe.onPreTransferCheck(sender, recipient, amount);
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(amount > 0, "Amount must be > zero");
require(_balances[sender] >= amount, "Insufficient balance");
checkTxLimit(sender, amount);
if (!liquidityPools[recipient] && recipient != DEAD) {
if(_balances[recipient] == 0) {
firstBuy[recipient] = block.timestamp;
}
if (!isTxLimitExempt[recipient]) {
checkWalletLimit(recipient, amount);
}
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) && shouldTakeFee(recipient) ? takeFee(sender, recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (protectionEnabled)
antisnipe.onPreTransferCheck(sender, recipient, amount);
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(amount > 0, "Amount must be > zero");
require(_balances[sender] >= amount, "Insufficient balance");
checkTxLimit(sender, amount);
if (!liquidityPools[recipient] && recipient != DEAD) {
if(_balances[recipient] == 0) {
firstBuy[recipient] = block.timestamp;
}
if (!isTxLimitExempt[recipient]) {
checkWalletLimit(recipient, amount);
}
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) && shouldTakeFee(recipient) ? takeFee(sender, recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (protectionEnabled)
antisnipe.onPreTransferCheck(sender, recipient, amount);
emit Transfer(sender, recipient, amountReceived);
return true;
}
if(inSwap){ return _basicTransfer(sender, recipient, amount); }
if(shouldSwapBack(recipient)){ if (amount > 0) swapBack(amount); }
function launched() internal view returns (bool) {
return launchedTime != 0;
}
function launch() internal {
launchedAt = block.number;
launchedTime = block.timestamp;
swapEnabled = true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender] - amount;
_balances[recipient] = _balances[recipient] + amount;
emit Transfer(sender, recipient, amount);
return true;
}
function checkWalletLimit(address recipient, uint256 amount) internal view {
uint256 walletLimit = _maxWalletSize;
require(_balances[recipient] + amount <= walletLimit, "Transfer amount exceeds the bag size.");
}
function checkTxLimit(address sender, uint256 amount) internal view {
require(isTxLimitExempt[sender] || amount <= (liquidityPools[sender] ? _maxBuyTxAmount : _maxSellTxAmount), "TX Limit Exceeded");
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function getTotalFee(bool selling, bool highPeriod) public view returns (uint256) {
if (selling) return highPeriod ? (totalFees * highFeeMult) / 100 : totalFees + sellBias;
return highPeriod ? (totalFees * highFeeMult) / 100 : totalFees - sellBias;
}
if(launchedAt + deadBlocks > block.number){ return feeDenominator - 1; }
function takeFee(address from, address recipient, uint256 amount) internal returns (uint256) {
bool selling = liquidityPools[recipient];
uint256 feeAmount = (amount * getTotalFee(selling, !liquidityPools[from] && firstBuy[from] + highFeePeriod > block.timestamp)) / feeDenominator;
uint256 poolAmount;
if (poolFee > 0){
poolAmount = (amount * poolFee) / feeDenominator;
_balances[poolReceiver] += poolAmount;
emit Transfer(from, poolReceiver, poolAmount);
}
if (feeAmount > 0) {
_balances[address(this)] += feeAmount;
emit Transfer(from, address(this), feeAmount);
}
return amount - (feeAmount + poolAmount);
}
function takeFee(address from, address recipient, uint256 amount) internal returns (uint256) {
bool selling = liquidityPools[recipient];
uint256 feeAmount = (amount * getTotalFee(selling, !liquidityPools[from] && firstBuy[from] + highFeePeriod > block.timestamp)) / feeDenominator;
uint256 poolAmount;
if (poolFee > 0){
poolAmount = (amount * poolFee) / feeDenominator;
_balances[poolReceiver] += poolAmount;
emit Transfer(from, poolReceiver, poolAmount);
}
if (feeAmount > 0) {
_balances[address(this)] += feeAmount;
emit Transfer(from, address(this), feeAmount);
}
return amount - (feeAmount + poolAmount);
}
function takeFee(address from, address recipient, uint256 amount) internal returns (uint256) {
bool selling = liquidityPools[recipient];
uint256 feeAmount = (amount * getTotalFee(selling, !liquidityPools[from] && firstBuy[from] + highFeePeriod > block.timestamp)) / feeDenominator;
uint256 poolAmount;
if (poolFee > 0){
poolAmount = (amount * poolFee) / feeDenominator;
_balances[poolReceiver] += poolAmount;
emit Transfer(from, poolReceiver, poolAmount);
}
if (feeAmount > 0) {
_balances[address(this)] += feeAmount;
emit Transfer(from, address(this), feeAmount);
}
return amount - (feeAmount + poolAmount);
}
function shouldSwapBack(address recipient) internal view returns (bool) {
return !liquidityPools[msg.sender]
&& !inSwap
&& swapEnabled
&& liquidityPools[recipient]
&& _balances[address(this)] >= swapMinimum &&
totalFees > 0;
}
function swapBack(uint256 amount) internal swapping {
uint256 amountToSwap = amount < swapThreshold ? amount : swapThreshold;
if (_balances[address(this)] < amountToSwap) amountToSwap = _balances[address(this)];
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidityPool(address lp, bool isPool) external onlyOwner {
require(lp != pair, "Can't alter current liquidity pair");
liquidityPools[lp] = isPool;
emit UpdatedSettings(isPool ? 'Liquidity Pool Enabled' : 'Liquidity Pool Disabled', [Log(toString(abi.encodePacked(lp)), 1), Log('', 0), Log('', 0)]);
}
function switchRouter(address newRouter, address newPair) external onlyOwner {
router = IDEXRouter(newRouter);
pair = newPair;
liquidityPools[newPair] = true;
isTxLimitExempt[newRouter] = true;
emit UpdatedSettings('Exchange Router Updated', [Log(concatenate('New Router: ',toString(abi.encodePacked(newRouter))), 1),Log(concatenate('New Liquidity Pair: ',toString(abi.encodePacked(pair))), 1), Log('', 0)]);
}
function excludePresaleAddress(address presaleAddress) external onlyOwner {
liquidityCreator[presaleAddress] = true;
isTxLimitExempt[presaleAddress] = true;
isFeeExempt[presaleAddress] = true;
emit UpdatedSettings('Presale Setup', [Log(concatenate('Presale Address: ',toString(abi.encodePacked(presaleAddress))), 1), Log('', 0), Log('', 0)]);
}
function setTxLimit(uint256 buyNumerator, uint256 sellNumerator, uint256 divisor) external onlyOwner {
require(buyNumerator > 0 && sellNumerator > 0 && divisor > 0 && divisor <= 10000);
_maxBuyTxAmount = (_totalSupply * buyNumerator) / divisor;
_maxSellTxAmount = (_totalSupply * sellNumerator) / divisor;
emit UpdatedSettings('Maximum Transaction Size', [Log('Max Buy Tokens', _maxBuyTxAmount / (10 ** _decimals)), Log('Max Sell Tokens', _maxSellTxAmount / (10 ** _decimals)), Log('', 0)]);
}
function setMaxWallet(uint256 numerator, uint256 divisor) external onlyOwner() {
require(numerator > 0 && divisor > 0 && divisor <= 10000);
_maxWalletSize = (_totalSupply * numerator) / divisor;
emit UpdatedSettings('Maximum Wallet Size', [Log('Tokens', _maxWalletSize / (10 ** _decimals)), Log('', 0), Log('', 0)]);
}
function setIsFeeExempt(address holder, bool exempt) external onlyOwner {
isFeeExempt[holder] = exempt;
emit UpdatedSettings(exempt ? 'Fees Removed' : 'Fees Enforced', [Log(toString(abi.encodePacked(holder)), 1), Log('', 0), Log('', 0)]);
}
function setIsTxLimitExempt(address holder, bool exempt) external onlyOwner {
isTxLimitExempt[holder] = exempt;
emit UpdatedSettings(exempt ? 'Transaction Limit Removed' : 'Transaction Limit Enforced', [Log(toString(abi.encodePacked(holder)), 1), Log('', 0), Log('', 0)]);
}
function setFees(uint256 _marketingFee, uint256 _devFee, uint256 _poolFee, uint256 _sellBias, uint256 _feeDenominator) external onlyOwner {
marketingFee = _marketingFee;
devFee = _devFee;
poolFee = _poolFee;
totalFees = _devFee + _marketingFee;
sellBias = _sellBias;
feeDenominator = _feeDenominator;
require(totalFees + poolFee < feeDenominator / 2);
emit UpdatedSettings('Fees', [Log('Total Fee Percent', totalFees * 100 / feeDenominator), Log('Marketing Percent', _marketingFee * 100 / feeDenominator), Log('Dev Percent', _devFee * 100 / feeDenominator)]);
}
function setFeeReceivers(address _liquidityFeeReceiver, address _marketingFeeReceiver, address _dev1, address _dev2, address _poolReceiver) external onlyOwner {
liquidityFeeReceiver = payable(_liquidityFeeReceiver);
marketingFeeReceiver = payable(_marketingFeeReceiver);
devReceiver1 = payable(_dev1);
devReceiver2 = payable(_dev2);
poolReceiver = _poolReceiver;
emit UpdatedSettings('Fee Receivers', [Log(concatenate('Liquidity Receiver: ',toString(abi.encodePacked(_liquidityFeeReceiver))), 1),Log(concatenate('Marketing Receiver: ',toString(abi.encodePacked(_marketingFeeReceiver))), 1), Log(concatenate('Pool Receiver: ',toString(abi.encodePacked(_poolReceiver))), 1)]);
}
function setSwapBackSettings(bool _enabled, uint256 _denominator, uint256 _swapMinimumDenom) external onlyOwner {
require(_denominator > 0);
swapEnabled = _enabled;
swapThreshold = _totalSupply / _denominator;
swapMinimum = _totalSupply / _swapMinimumDenom;
emit UpdatedSettings('Swap Settings', [Log('Enabled', _enabled ? 1 : 0),Log('Swap Maximum', swapThreshold), Log('Swap Minimum', swapMinimum)]);
}
function getCirculatingSupply() public view returns (uint256) {
return _totalSupply - (balanceOf(DEAD) + balanceOf(ZERO));
}
function burnLP(uint256 percent) external onlyOwner {
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 5 && percent > 0, "Max of 5% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 pairBalance = this.balanceOf(pair);
_basicTransfer(pair, DEAD, (pairBalance * percent) / 100);
IDexPair(pair).sync();
}
function toString(bytes memory data) internal pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
function toString(bytes memory data) internal pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
function concatenate(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
struct Log {
string name;
uint256 value;
}
event UpdatedSettings(string name, Log[3] values);
} | 15,122,206 | [
1,
2867,
4633,
1887,
273,
374,
92,
29,
9988,
1105,
39,
71,
26,
73,
6334,
3600,
25339,
39,
24,
2539,
18096,
28,
41,
8875,
6418,
2954,
69,
2539,
26,
4630,
73,
25,
71,
23,
31,
2867,
4633,
1887,
273,
374,
92,
2163,
2056,
8942,
39,
27,
2643,
27,
3461,
24008,
4449,
72,
25,
69,
37,
10321,
38,
8285,
38,
6564,
27,
3028,
41,
5034,
3103,
24,
41,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
6565,
50,
26223,
353,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
377,
203,
565,
1758,
2030,
1880,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
31,
203,
565,
1758,
18449,
273,
374,
92,
12648,
12648,
12648,
12648,
12648,
31,
203,
203,
565,
533,
5381,
389,
529,
273,
315,
2781,
423,
26223,
14432,
203,
565,
533,
5381,
389,
7175,
273,
315,
50,
2192,
45,
14432,
203,
565,
2254,
28,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2254,
5034,
389,
4963,
3088,
1283,
273,
2130,
67,
3784,
67,
3784,
380,
261,
2163,
2826,
389,
31734,
1769,
203,
565,
2254,
5034,
389,
1896,
38,
9835,
4188,
6275,
273,
261,
67,
4963,
3088,
1283,
380,
404,
13,
342,
7409,
31,
203,
565,
2254,
5034,
389,
1896,
55,
1165,
4188,
6275,
273,
261,
67,
4963,
3088,
1283,
380,
404,
13,
342,
7409,
31,
203,
565,
2254,
5034,
389,
1896,
16936,
1225,
273,
261,
67,
4963,
3088,
1283,
380,
404,
13,
342,
2130,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1122,
38,
9835,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
389,
5965,
6872,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
353,
14667,
424,
5744,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
353,
4188,
3039,
424,
5744,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
2
] |
pragma solidity ^0.4.19;
import "./Pausable.sol";
contract Remittance is Pausable {
uint constant fee = 50;
uint constant maxDurationInBlocks = 4 weeks / 15;
uint constant minDurationInBlocks = 1 days / 15;
struct RemittanceBox {
address sentFrom;
address moneyChanger;
uint amount;
uint deadline;
}
// for every bytes32 there is a RemittanceBox and those namespaces (struct) will conform a mapping named remittanceStructs
mapping (bytes32 => RemittanceBox) public remittanceStructs;
event LogDeposit(address indexed sentFrom, address indexed moneyChanger, uint amount, uint fee, uint numberOfBlocks);
event LogCollect(address indexed moneyChanger, uint amount);
event LogCancel(address indexed sentFrom, uint amount);
function Remittance() public {
}
function hashHelper(bytes32 password1, bytes32 password2) public pure returns(bytes32 hashedPassword) {
return keccak256(password1, password2);
}
function depositRemittance(bytes32 hashedPassword, address moneyChanger, uint numberOfBlocks) public payable onlyIfRunning returns(bool success) {
require(hashedPassword != 0);
require(remittanceStructs[hashedPassword].amount == 0);
require(msg.value > fee);
require(moneyChanger != 0x0);
require(numberOfBlocks > minDurationInBlocks);
require(numberOfBlocks < maxDurationInBlocks);
remittanceStructs[hashedPassword].moneyChanger = moneyChanger;
remittanceStructs[hashedPassword].sentFrom = msg.sender;
remittanceStructs[hashedPassword].amount = msg.value - fee;
remittanceStructs[hashedPassword].deadline = block.number + numberOfBlocks;
LogDeposit(msg.sender, moneyChanger, msg.value, fee, numberOfBlocks);
super.getOwner().transfer(fee);
return true;
}
function collectRemittance(bytes32 password1, bytes32 password2) public onlyIfRunning returns(bool success) {
bytes32 hashedPassword = hashHelper(password1, password2);
//this goes before requirements as an exception, to avoid having to write twice in the box and therefore
//save some serious gas. You can do that when variables are transient (stored in memory, not in storage)
uint amount = remittanceStructs[hashedPassword].amount;
require(amount != 0);
require(remittanceStructs[hashedPassword].moneyChanger == msg.sender);
require(remittanceStructs[hashedPassword].deadline >= block.number);
remittanceStructs[hashedPassword].amount = 0;
remittanceStructs[hashedPassword].deadline = 0;
remittanceStructs[hashedPassword].moneyChanger = 0x0;
remittanceStructs[hashedPassword].sentFrom = 0x0;
LogCollect(msg.sender, remittanceStructs[hashedPassword].amount);
msg.sender.transfer(amount);
return true;
}
function cancelRemittance(bytes32 hashedPassword) public onlyIfRunning returns(bool success) {
require(remittanceStructs[hashedPassword].amount != 0);
require(remittanceStructs[hashedPassword].sentFrom == msg.sender);
require(remittanceStructs[hashedPassword].deadline < block.number);
uint amount = remittanceStructs[hashedPassword].amount;
remittanceStructs[hashedPassword].amount = 0;
remittanceStructs[hashedPassword].deadline = 0;
remittanceStructs[hashedPassword].sentFrom = 0x0;
remittanceStructs[hashedPassword].moneyChanger = 0x0;
LogCancel(msg.sender, amount);
msg.sender.transfer(amount);
return true;
}
} | for every bytes32 there is a RemittanceBox and those namespaces (struct) will conform a mapping named remittanceStructs | mapping (bytes32 => RemittanceBox) public remittanceStructs;
| 5,473,185 | [
1,
1884,
3614,
1731,
1578,
1915,
353,
279,
2663,
305,
88,
1359,
3514,
471,
5348,
7728,
261,
1697,
13,
903,
20156,
279,
2874,
4141,
849,
305,
88,
1359,
3823,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
3890,
1578,
516,
2663,
305,
88,
1359,
3514,
13,
1071,
849,
305,
88,
1359,
3823,
87,
31,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x66938285B15da67A93D80D08f8f2DA665449F08d/sources/contracts/AXLPresale.sol | Total presale tokens sold
| uint256 sold_amount; | 4,929,504 | [
1,
5269,
4075,
5349,
2430,
272,
1673,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
272,
1673,
67,
8949,
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
] |
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/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/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/StubbornApe.sol
pragma solidity ^0.8.7;
contract StubbornApe is ERC721Enumerable, Ownable {
using Strings for uint256;
using SafeMath for uint256;
string public baseURI;
// Costs ====================================
uint256 public presaleCost = 0.06 ether;
uint256 public publicSaleCost = 0.08 ether;
// Sale dates ===============================
uint256 public presaleStartTimestamp = 1649970000; // 14 April 2022 5 PM EST
uint256 public publicSaleStartTimestamp = 1650124800; // 16 April 2022 12 PM EST
// Count values =============================
uint256 public MAX_ITEMS = 7000;
uint256 public _mintedItems = 0;
uint256 public maxMintAmount = 10; // Max items per tx
bool public paused = false;
string public notRevealedUri;
bool public revealed = false;
// Lists ====================================
mapping(address => bool) public whitelisted;
mapping(address => uint256) public presaleWallets;
// Events ===================================
event PublicSaleMint(address indexed _from, uint256 indexed _tokenId);
constructor() ERC721("The Stubborn Apes Society", "SAS") {
setNotRevealedURI(
"https://gateway.pinata.cloud/ipfs/QmWuYUPfxr2pi788S3vbtYKYti9YE5AgzYHBgndb5W4FMx"
);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// Presale Minting ============================
function presaleMint() public payable {
require(!paused, "Contract is paused!");
require(
block.timestamp >= presaleStartTimestamp,
"Presale time is not active yet"
);
require(
block.timestamp <= publicSaleStartTimestamp,
"Current period is not within public time"
);
uint256 remainder = msg.value % presaleCost;
uint256 _mintAmount = msg.value / presaleCost;
require(remainder == 0, "Send a divisible amount of price");
require(
_mintedItems.add(_mintAmount) <= MAX_ITEMS,
"Purchase would exceed max supply"
);
require(_mintAmount <= maxMintAmount, "Over the maxMintAmount");
require(whitelisted[msg.sender] == true, "You need to be in whitelist");
require(presaleWallets[msg.sender] <= 10, "Max 10 items per wallet");
if (msg.sender != owner()) {
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 mintIndex = _mintedItems + 1;
require(_mintedItems < MAX_ITEMS, "All items sold!");
_safeMint(msg.sender, mintIndex);
_mintedItems++;
}
presaleUser(msg.sender, presaleWallets[msg.sender] + _mintAmount);
}
}
// Public sale Minting =================================
function publicSaleMint() public payable {
require(!paused, "Contract is paused");
require(
block.timestamp >= publicSaleStartTimestamp,
"Public sale time is not active yet"
);
uint256 remainder = msg.value % publicSaleCost;
uint256 _mintAmount = msg.value / publicSaleCost;
require(remainder == 0, "Send a divisible amount of price");
require(
_mintedItems.add(_mintAmount) <= MAX_ITEMS,
"Purchase would exceed max supply"
);
require(_mintAmount <= maxMintAmount, "Over the maxMintAmount");
if (msg.sender != owner()) {
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 mintIndex = _mintedItems + 1;
require(_mintedItems < MAX_ITEMS, "All items sold!");
_safeMint(msg.sender, mintIndex);
emit PublicSaleMint(msg.sender, mintIndex);
_mintedItems++;
}
}
}
// Admin Minting (Mint by owner) =========================
function ownerMint(uint256 _mintAmount) public payable onlyOwner {
require(!paused, "Contract is paused");
require(
_mintedItems.add(_mintAmount) <= MAX_ITEMS,
"Purchase would exceed max supply"
);
require(_mintAmount <= maxMintAmount, "Over the maxMintAmount");
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 mintIndex = _mintedItems + 1;
require(_mintedItems < MAX_ITEMS, "All items sold!");
_safeMint(msg.sender, mintIndex);
_mintedItems++;
}
}
// Get MetaData TokenURI =======================
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
".json"
)
)
: "";
}
// Reveal Metadata of Tokens =======================
function reveal(bool _state) public onlyOwner {
revealed = _state;
}
// Set Placeholder metadata URI =======================
function setNotRevealedURI(string memory _notRevealedURI) public {
notRevealedUri = _notRevealedURI;
}
// Set Presale timestamp, (input: timestamp in UTC) =======================
function setPresaleStartTimestamp(uint256 _startTimestamp)
external
onlyOwner
{
presaleStartTimestamp = _startTimestamp;
}
// Set public timestamp (input: timestamp in UTC) =======================
function setPublicSaleStartTimestamp(uint256 _startTimestamp)
external
onlyOwner
{
publicSaleStartTimestamp = _startTimestamp;
}
// Set Presale cost for token in ether =======================
function setPresaleCost(uint256 _newCost) public onlyOwner {
presaleCost = _newCost;
}
// Set public sale cost for token in ether =======================
function setPublicSaleCost(uint256 _newCost) public onlyOwner {
publicSaleCost = _newCost;
}
// Set max mint limit for single transaction at a time =======================
function setMaxMintAmount(uint256 _maxItemsPerTx) public onlyOwner {
maxMintAmount = _maxItemsPerTx;
}
// Set base URI of metadata (an IPFS URL) =======================
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
// Pause the contract which will stop minting process =======================
function pause(bool _state) public onlyOwner {
paused = _state;
}
// Add a whitelist user who can mint in presale =======================
function whitelistUser(address _user) public onlyOwner {
whitelisted[_user] = true;
}
// Remove a whitelist user from current whitelist list =======================
function removeWhitelistUser(address _user) public onlyOwner {
whitelisted[_user] = false;
}
// Add a presale user =======================
function presaleUser(address _user, uint256 _amount) internal {
presaleWallets[_user] = _amount;
}
// Get number of tokens minted by a particular address =======================
function getMintedCountByPresaledUser(address _user)
public
view
virtual
returns (uint256)
{
return presaleWallets[_user];
}
// Remove a presale user from wallet =======================
function removePresaleUser(address _user, uint256 _amount)
external
onlyOwner
{
presaleWallets[_user] = _amount;
}
// Withdraw the balance from samrt contract =======================
function withdraw() external onlyOwner {
(bool success, ) = owner().call{value: address(this).balance}("");
require(success, "Failed to withdraw");
}
} | Public sale Minting ================================= | function publicSaleMint() public payable {
require(!paused, "Contract is paused");
require(
block.timestamp >= publicSaleStartTimestamp,
"Public sale time is not active yet"
);
uint256 remainder = msg.value % publicSaleCost;
uint256 _mintAmount = msg.value / publicSaleCost;
require(remainder == 0, "Send a divisible amount of price");
require(
_mintedItems.add(_mintAmount) <= MAX_ITEMS,
"Purchase would exceed max supply"
);
require(_mintAmount <= maxMintAmount, "Over the maxMintAmount");
if (msg.sender != owner()) {
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 mintIndex = _mintedItems + 1;
require(_mintedItems < MAX_ITEMS, "All items sold!");
_safeMint(msg.sender, mintIndex);
emit PublicSaleMint(msg.sender, mintIndex);
_mintedItems++;
}
}
}
| 5,893,348 | [
1,
4782,
272,
5349,
490,
474,
310,
28562,
14468,
12275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1071,
30746,
49,
474,
1435,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
5,
8774,
3668,
16,
315,
8924,
353,
17781,
8863,
203,
3639,
2583,
12,
203,
5411,
1203,
18,
5508,
1545,
1071,
30746,
1685,
4921,
16,
203,
5411,
315,
4782,
272,
5349,
813,
353,
486,
2695,
4671,
6,
203,
3639,
11272,
203,
3639,
2254,
5034,
10022,
273,
1234,
18,
1132,
738,
1071,
30746,
8018,
31,
203,
3639,
2254,
5034,
389,
81,
474,
6275,
273,
1234,
18,
1132,
342,
1071,
30746,
8018,
31,
203,
3639,
2583,
12,
2764,
25407,
422,
374,
16,
315,
3826,
279,
3739,
18932,
3844,
434,
6205,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
81,
474,
329,
3126,
18,
1289,
24899,
81,
474,
6275,
13,
1648,
4552,
67,
29887,
16,
203,
5411,
315,
23164,
4102,
9943,
943,
14467,
6,
203,
3639,
11272,
203,
3639,
2583,
24899,
81,
474,
6275,
1648,
943,
49,
474,
6275,
16,
315,
4851,
326,
943,
49,
474,
6275,
8863,
203,
203,
3639,
309,
261,
3576,
18,
15330,
480,
3410,
10756,
288,
203,
5411,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
81,
474,
6275,
31,
277,
27245,
288,
203,
7734,
2254,
5034,
312,
474,
1016,
273,
389,
81,
474,
329,
3126,
397,
404,
31,
203,
7734,
2583,
24899,
81,
474,
329,
3126,
411,
4552,
67,
29887,
16,
315,
1595,
1516,
272,
1673,
4442,
1769,
203,
7734,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
312,
474,
1016,
1769,
203,
7734,
3626,
7224,
30746,
49,
474,
12,
3576,
18,
15330,
16,
2
] |
./full_match/80001/0x5d88b06E942e9AbB9470e80384d7E28ACb743511/sources/contracts/ThriftClub.sol | do other stuff, like call winner function to send to pot to the winner Check ThriftPurseBalance and ThriftPurseTokenBalance before transferring the pot balance payable(winner).transfer(ThriftPurseBalance); Update the state based on the number of paid participants | function fulfillRandomWords(
uint256 /* requestId */,
uint256[] memory randomWords
) internal override {
s_randomWords = randomWords;
uint256 winnerIndex = s_randomWords[0] % participants.length;
address winner = participants[winnerIndex];
require(
ThriftPurseBalance > 0 ||
ThriftPurseTokenBalance[s_thriftClub.token] > 0,
"No balance in the ThriftPurse"
);
if (ThriftPurseBalance > 0) {
if (!success) {
revert __TransferFailed();
}
emit AddressPaid(winner, ThriftPurseBalance);
ThriftPurseBalance = 0;
bool success = IERC20(s_thriftClub.token).transfer(
msg.sender,
ThriftPurseTokenBalance[s_thriftClub.token]
);
if (!success) {
revert __TransferFailed();
}
emit AddressPaid(
winner,
ThriftPurseTokenBalance[s_thriftClub.token]
);
ThriftPurseTokenBalance[s_thriftClub.token] = 0;
}
if (paidParticipants == s_thriftClub.maxParticipant) {
s_thriftClub.t_state = TANDA_STATE.CLOSED;
s_thriftClub.t_state = TANDA_STATE.OPEN;
}
}
| 5,586,932 | [
1,
2896,
1308,
10769,
16,
3007,
745,
5657,
1224,
445,
358,
1366,
358,
5974,
358,
326,
5657,
1224,
2073,
18604,
10262,
307,
13937,
471,
18604,
10262,
307,
1345,
13937,
1865,
906,
74,
20245,
326,
5974,
11013,
8843,
429,
12,
91,
7872,
2934,
13866,
12,
30007,
10262,
307,
13937,
1769,
2315,
326,
919,
2511,
603,
326,
1300,
434,
30591,
22346,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22290,
8529,
7363,
12,
203,
3639,
2254,
5034,
1748,
14459,
1195,
16,
203,
3639,
2254,
5034,
8526,
3778,
2744,
7363,
203,
565,
262,
2713,
3849,
288,
203,
3639,
272,
67,
9188,
7363,
273,
2744,
7363,
31,
203,
3639,
2254,
5034,
5657,
1224,
1016,
273,
272,
67,
9188,
7363,
63,
20,
65,
738,
22346,
18,
2469,
31,
203,
3639,
1758,
5657,
1224,
273,
22346,
63,
91,
7872,
1016,
15533,
203,
203,
3639,
2583,
12,
203,
5411,
18604,
10262,
307,
13937,
405,
374,
747,
203,
7734,
18604,
10262,
307,
1345,
13937,
63,
87,
67,
451,
10526,
2009,
373,
18,
2316,
65,
405,
374,
16,
203,
5411,
315,
2279,
11013,
316,
326,
18604,
10262,
307,
6,
203,
3639,
11272,
203,
203,
3639,
309,
261,
30007,
10262,
307,
13937,
405,
374,
13,
288,
203,
5411,
309,
16051,
4768,
13,
288,
203,
7734,
15226,
1001,
5912,
2925,
5621,
203,
5411,
289,
203,
5411,
3626,
5267,
16507,
350,
12,
91,
7872,
16,
18604,
10262,
307,
13937,
1769,
203,
5411,
18604,
10262,
307,
13937,
273,
374,
31,
203,
203,
5411,
1426,
2216,
273,
467,
654,
39,
3462,
12,
87,
67,
451,
10526,
2009,
373,
18,
2316,
2934,
13866,
12,
203,
7734,
1234,
18,
15330,
16,
203,
7734,
18604,
10262,
307,
1345,
13937,
63,
87,
67,
451,
10526,
2009,
373,
18,
2316,
65,
203,
5411,
11272,
203,
5411,
309,
16051,
4768,
13,
288,
203,
7734,
15226,
1001,
5912,
2925,
5621,
203,
5411,
289,
203,
5411,
3626,
5267,
16507,
350,
12,
203,
7734,
5657,
1224,
16,
203,
7734,
18604,
10262,
307,
2
] |
pragma solidity 0.4.24;
/**
* DO NOT SEND ETH TO THIS CONTRACT ON MAINNET. ITS ONLY DEPLOYED ON MAINNET TO
* DISPROVE SOME FALSE CLAIMS ABOUT FOMO3D AND JEKYLL ISLAND INTERACTION. YOU
* CAN TEST ALL THE PAYABLE FUNCTIONS SENDING 0 ETH. OR BETTER YET COPY THIS TO
* THE TESTNETS.
*
* IF YOU SEND ETH TO THIS CONTRACT IT CANNOT BE RECOVERED. THERE IS NO WITHDRAW.
*
* THE CHECK BALANCE FUNCTIONS ARE FOR WHEN TESTING ON TESTNET TO SHOW THAT ALTHOUGH
* THE CORP BANK COULD BE FORCED TO REVERT TX'S OR TRY AND BURN UP ALL/MOST GAS
* FOMO3D STILL MOVES ON WITHOUT RISK OF LOCKING UP. AND IN CASES OF REVERT OR
* OOG INSIDE CORP BANK. ALL WE AT TEAM JUST WOULD ACCOMPLISH IS JUSTING OURSELVES
* OUT OF THE ETH THAT WAS TO BE SENT TO JEKYLL ISLAND. FOREVER LEAVING IT UNCLAIMABLE
* IN FOMO3D CONTACT. SO WE CAN ONLY HARM OURSELVES IF WE TRIED SUCH A USELESS
* THING. AND FOMO3D WILL CONTINUE ON, UNAFFECTED
*/
// this is deployed on mainnet at: 0x38aEfE9e8E0Fc938475bfC6d7E52aE28D39FEBD8
contract Fomo3d {
// create some data tracking vars for testing
bool public depositSuccessful_;
uint256 public successfulTransactions_;
uint256 public gasBefore_;
uint256 public gasAfter_;
// create forwarder instance
Forwarder Jekyll_Island_Inc;
// take addr for forwarder in constructor arguments
constructor(address _addr)
public
{
// set up forwarder to point to its contract location
Jekyll_Island_Inc = Forwarder(_addr);
}
// some fomo3d function that deposits to Forwarder
function someFunction()
public
payable
{
// grab gas left
gasBefore_ = gasleft();
// deposit to forwarder, uses low level call so forwards all gas
if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit()"))))
{
// give fomo3d work to do that needs gas. what better way than storage
// write calls, since their so costly.
depositSuccessful_ = false;
gasAfter_ = gasleft();
} else {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
}
}
// some fomo3d function that deposits to Forwarder
function someFunction2()
public
payable
{
// grab gas left
gasBefore_ = gasleft();
// deposit to forwarder, uses low level call so forwards all gas
if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit2()"))))
{
// give fomo3d work to do that needs gas. what better way than storage
// write calls, since their so costly.
depositSuccessful_ = false;
gasAfter_ = gasleft();
} else {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
}
}
// some fomo3d function that deposits to Forwarder
function someFunction3()
public
payable
{
// grab gas left
gasBefore_ = gasleft();
// deposit to forwarder, uses low level call so forwards all gas
if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit3()"))))
{
// give fomo3d work to do that needs gas. what better way than storage
// write calls, since their so costly.
depositSuccessful_ = false;
gasAfter_ = gasleft();
} else {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
}
}
// some fomo3d function that deposits to Forwarder
function someFunction4()
public
payable
{
// grab gas left
gasBefore_ = gasleft();
// deposit to forwarder, uses low level call so forwards all gas
if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit4()"))))
{
// give fomo3d work to do that needs gas. what better way than storage
// write calls, since their so costly.
depositSuccessful_ = false;
gasAfter_ = gasleft();
} else {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
}
}
// for data tracking lets make a function to check this contracts balance
function checkBalance()
public
view
returns(uint256)
{
return(address(this).balance);
}
}
// heres a sample forwarder with a copy of the jekyll island forwarder (requirements on
// msg.sender removed for simplicity since its irrelevant to testing this. and some
// tracking vars added for test.)
// this is deployed on mainnet at: 0x8F59323d8400CC0deE71ee91f92961989D508160
contract Forwarder {
// lets create some tracking vars
bool public depositSuccessful_;
uint256 public successfulTransactions_;
uint256 public gasBefore_;
uint256 public gasAfter_;
// create an instance of the jekyll island bank
Bank currentCorpBank_;
// take an address in the constructor arguments to set up bank with
constructor(address _addr)
public
{
// point the created instance to the address given
currentCorpBank_ = Bank(_addr);
}
function deposit()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit2()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit2.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit3()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit3.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit4()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit4.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
// for data tracking lets make a function to check this contracts balance
function checkBalance()
public
view
returns(uint256)
{
return(address(this).balance);
}
}
// heres the bank with various ways someone could try and migrate to a bank that
// screws the tx. to show none of them effect fomo3d.
// this is deployed on mainnet at: 0x0C2DBC98581e553C4E978Dd699571a5DED408a4F
contract Bank {
// lets use storage writes to this to burn up all gas
uint256 public i = 1000000;
uint256 public x;
address public fomo3d;
/**
* this version will use up most gas. but return just enough to make it back
* to fomo3d. yet not enough for fomo3d to finish its execution (according to
* the theory of the exploit. which when you run this you'll find due to my
* use of ! in the call from fomo3d to forwarder, and the use of a normal function
* call from forwarder to bank, this fails to stop fomo3d from continuing)
*/
function deposit(address _fomo3daddress)
external
payable
returns(bool)
{
// burn all gas leaving just enough to get back to fomo3d and it to do
// a write call in a attempt to make Fomo3d OOG (doesn't work cause fomo3d
// protects itself from this behavior)
while (i > 41000)
{
i = gasleft();
}
return(true);
}
/**
* this version just tries a plain revert. (pssst... fomo3d doesn't care)
*/
function deposit2(address _fomo3daddress)
external
payable
returns(bool)
{
// straight up revert (since we use low level call in fomo3d it doesn't
// care if we revert the internal tx to bank. this behavior would only
// screw over team just, not effect fomo3d)
revert();
}
/**
* this one tries an infinite loop (another fail. fomo3d trudges on)
*/
function deposit3(address _fomo3daddress)
external
payable
returns(bool)
{
// this infinite loop still does not stop fomo3d from running.
while(1 == 1) {
x++;
fomo3d = _fomo3daddress;
}
return(true);
}
/**
* this one just runs a set length loops that OOG's (and.. again.. fomo3d still works)
*/
function deposit4(address _fomo3daddress)
public
payable
returns(bool)
{
// burn all gas (fomo3d still keeps going)
for (uint256 i = 0; i <= 1000; i++)
{
x++;
fomo3d = _fomo3daddress;
}
}
// for data tracking lets make a function to check this contracts balance
function checkBalance()
public
view
returns(uint256)
{
return(address(this).balance);
}
} | some fomo3d function that deposits to Forwarder grab gas left deposit to forwarder, uses low level call so forwards all gas give fomo3d work to do that needs gas. what better way than storage write calls, since their so costly. | function someFunction2()
public
payable
{
gasBefore_ = gasleft();
if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit2()"))))
{
depositSuccessful_ = false;
gasAfter_ = gasleft();
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
}
}
| 5,430,800 | [
1,
19068,
284,
362,
83,
23,
72,
445,
716,
443,
917,
1282,
358,
2457,
20099,
11086,
16189,
2002,
443,
1724,
358,
364,
20099,
16,
4692,
4587,
1801,
745,
1427,
24578,
777,
16189,
8492,
284,
362,
83,
23,
72,
1440,
358,
741,
716,
4260,
16189,
18,
4121,
7844,
4031,
2353,
2502,
1045,
4097,
16,
3241,
3675,
1427,
6991,
715,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2690,
2083,
22,
1435,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
565,
288,
203,
3639,
16189,
4649,
67,
273,
16189,
4482,
5621,
203,
540,
203,
3639,
309,
16051,
2867,
12,
46,
3839,
93,
2906,
67,
45,
2069,
464,
67,
14559,
2934,
1991,
18,
1132,
12,
3576,
18,
1132,
21433,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
323,
1724,
22,
10031,
3719,
3719,
21281,
3639,
288,
203,
5411,
443,
1724,
14277,
67,
273,
629,
31,
203,
5411,
16189,
4436,
67,
273,
16189,
4482,
5621,
203,
5411,
443,
1724,
14277,
67,
273,
638,
31,
203,
5411,
6873,
14186,
67,
9904,
31,
203,
5411,
16189,
4436,
67,
273,
16189,
4482,
5621,
203,
3639,
289,
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
] |
pragma solidity >=0.4.21 <0.6.0;
// ICE ICE BABY Seperated this from ICToken to allow for repayBorrowBehalf.value()() without compiling errors
interface ICEToken {
function repayBorrowBehalf(address _borrower) external payable;
} | ICE ICE BABY Seperated this from ICToken to allow for repayBorrowBehalf.value()() without compiling errors | interface ICEToken {
function repayBorrowBehalf(address _borrower) external payable;
} | 5,367,348 | [
1,
11774,
467,
1441,
605,
2090,
61,
3265,
457,
690,
333,
628,
467,
1268,
969,
358,
1699,
364,
2071,
528,
38,
15318,
1919,
20222,
18,
1132,
1435,
1435,
2887,
1161,
4973,
1334,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
1441,
1345,
288,
203,
565,
445,
2071,
528,
38,
15318,
1919,
20222,
12,
2867,
389,
70,
15318,
264,
13,
3903,
8843,
429,
31,
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
] |
//Address: 0xf5aca7f577de131c176d6a2069eb90b494a34fff
//Contract name: StatusBuyer
//Balance: 0 Ether
//Verification Date: 6/16/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.11;
/*
Status Buyer
========================
Buys Status tokens from the crowdsale on your behalf.
Author: /u/Cintix
*/
// ERC20 Interface: https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
function transfer(address _to, uint256 _value) returns (bool success);
function balanceOf(address _owner) constant returns (uint256 balance);
}
// Interface to Status ICO Contract
contract StatusContribution {
uint256 public totalNormalCollected;
function proxyPayment(address _th) payable returns (bool);
}
// Interface to Status Cap Determination Contract
contract DynamicCeiling {
function curves(uint currentIndex) returns (bytes32 hash,
uint256 limit,
uint256 slopeFactor,
uint256 collectMinimum);
uint256 public currentIndex;
uint256 public revealedCurves;
}
contract StatusBuyer {
// Store the amount of ETH deposited by each account.
mapping (address => uint256) public deposits;
// Track the amount of SNT each account's "buy" calls have purchased from the ICO.
// Allows tracking which accounts would have made it into the ICO on their own.
mapping (address => uint256) public purchased_snt;
// Bounty for executing buy.
uint256 public bounty;
// Track whether the contract has started buying tokens yet.
bool public bought_tokens;
// The Status Token Sale address.
StatusContribution public sale = StatusContribution(0x0);
// The Status DynamicCeiling Contract address.
DynamicCeiling public dynamic = DynamicCeiling(0x0);
// Status Network Token (SNT) Contract address.
ERC20 public token = ERC20(0x0);
// The developer address.
address developer = 0x4e6A1c57CdBfd97e8efe831f8f4418b1F2A09e6e;
// Withdraws all ETH/SNT owned by the user in the ratio currently owned by the contract.
function withdraw() {
// Store the user's deposit prior to withdrawal in a temporary variable.
uint256 user_deposit = deposits[msg.sender];
// Update the user's deposit prior to sending ETH to prevent recursive call.
deposits[msg.sender] = 0;
// Retrieve current ETH balance of contract (less the bounty).
uint256 contract_eth_balance = this.balance - bounty;
// Retrieve current SNT balance of contract.
uint256 contract_snt_balance = token.balanceOf(address(this));
// Calculate total SNT value of ETH and SNT owned by the contract.
// 1 ETH Wei -> 10000 SNT Wei
uint256 contract_value = (contract_eth_balance * 10000) + contract_snt_balance;
// Calculate amount of ETH to withdraw.
uint256 eth_amount = (user_deposit * contract_eth_balance * 10000) / contract_value;
// Calculate amount of SNT to withdraw.
uint256 snt_amount = 10000 * ((user_deposit * contract_snt_balance) / contract_value);
// No fee for withdrawing if user would have made it into the crowdsale alone.
uint256 fee = 0;
// 1% fee on portion of tokens user would not have been able to buy alone.
if (purchased_snt[msg.sender] < snt_amount) {
fee = (snt_amount - purchased_snt[msg.sender]) / 100;
}
// Send the funds. Throws on failure to prevent loss of funds.
if(!token.transfer(msg.sender, snt_amount - fee)) throw;
if(!token.transfer(developer, fee)) throw;
msg.sender.transfer(eth_amount);
}
// Allow anyone to contribute to the buy execution bounty.
function add_bounty() payable {
// Update bounty to include received amount.
bounty += msg.value;
}
// Buys tokens for the contract and rewards the caller. Callable by anyone.
function buy() {
buy_for(msg.sender);
}
// Buys tokens in the crowdsale and rewards the given address. Callable by anyone.
// Enables Sybil attacks, wherein a single user creates multiple accounts with which
// to call "buy_for" to reward their primary account. Useful for bounty-seekers who
// haven't sent ETH to the contract, but don't want to clean up Sybil dust, or for users
// who have sent a large amount of ETH to the contract and want to reduce/avoid their fee.
function buy_for(address user) {
// Short circuit to save gas if the contract doesn't have any ETH left to buy tokens.
if (this.balance == 0) return;
// Store the current curve/cap index as temporary variable to avoid calling twice.
uint256 currentIndex = dynamic.currentIndex();
// Check whether the current curve/cap is the last one revealed so far.
if ((currentIndex + 1) >= dynamic.revealedCurves()) {
// Extract the buy limit of the current curve/cap.
uint256 limit;
(,limit,,) = dynamic.curves(currentIndex);
// Short circuit to save gas if the ICO is currently at the cap, waiting for a reveal.
if (limit <= sale.totalNormalCollected()) return;
}
// Record that the contract has started buying tokens.
bought_tokens = true;
// Store the contract's ETH balance prior to the purchase in a temporary variable.
uint256 old_contract_eth_balance = this.balance;
// Transfer all the funds (less the bounty) to the Status ICO contract
// to buy tokens. Throws if the crowdsale hasn't started yet or has
// already completed, preventing loss of funds.
sale.proxyPayment.value(this.balance - bounty)(address(this));
// Verify contract ETH balance has not increased instead of decreased.
if (this.balance > old_contract_eth_balance) throw;
// Calculate ETH spent to buy tokens.
uint256 eth_spent = old_contract_eth_balance - this.balance;
// Update user's number of purchased SNT to include this purchase.
purchased_snt[user] += (eth_spent * 10000);
// Calculate the user's bounty proportionally to the amount purchased.
uint256 user_bounty = (bounty * eth_spent) / (old_contract_eth_balance - bounty);
// Update the bounty prior to sending ETH to prevent recursive call.
bounty -= user_bounty;
// Send the user their bounty for buying tokens for the contract.
user.transfer(user_bounty);
}
// A helper function for the default function, allowing contracts to interact.
function default_helper() payable {
// Only allow deposits if the contract hasn't already purchased the tokens.
if (!bought_tokens) {
// Update records of deposited ETH to include the received amount.
deposits[msg.sender] += msg.value;
}
// Withdraw the sender's ETH and SNT if the contract has started purchasing SNT.
else {
// Reject ETH sent after the contract has already purchased tokens.
if (msg.value != 0) throw;
// Withdraw user's funds if they sent 0 ETH to the contract after the ICO.
withdraw();
}
}
// Default function. Called when a user sends ETH to the contract.
function () payable {
throw; // Safety throw, which will be removed in deployed version.
// Avoid recursively buying tokens when the sale contract refunds ETH.
if (msg.sender != address(sale)) {
// Delegate to the helper function.
default_helper();
}
}
}
| Allow anyone to contribute to the buy execution bounty. Update bounty to include received amount. | function add_bounty() payable {
bounty += msg.value;
}
| 7,238,037 | [
1,
7009,
1281,
476,
358,
356,
887,
358,
326,
30143,
4588,
324,
592,
93,
18,
2315,
324,
592,
93,
358,
2341,
5079,
3844,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
527,
67,
70,
592,
93,
1435,
8843,
429,
288,
203,
565,
324,
592,
93,
1011,
1234,
18,
1132,
31,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.4;
// ----------------------------------------------------------------------------
// BokkyPooBah's Token Teleportation Service v1.10
//
// https://github.com/bokkypoobah/BokkyPooBahsTokenTeleportationServiceSmartContract
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence.
// ----------------------------------------------------------------------------
// import "../Shared/BTTSTokenInterface120.sol";
import "../Shared/BTTSTokenLibrary120.sol";
// ----------------------------------------------------------------------------
// BokkyPooBah's Token Teleportation Service Token v1.10
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence.
// ----------------------------------------------------------------------------
contract DreamFramesToken is BTTSTokenInterface {
using BTTSLib for BTTSLib.Data;
BTTSLib.Data data;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor(address owner, string memory symbol, string memory name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public {
data.init(owner, symbol, name, decimals, initialSupply, mintable, transferable);
}
// ------------------------------------------------------------------------
// Ownership
// ------------------------------------------------------------------------
function owner() public view returns (address) {
return data.owner;
}
function newOwner() public view returns (address) {
return data.newOwner;
}
function transferOwnership(address _newOwner) public {
data.transferOwnership(_newOwner);
}
function acceptOwnership() public {
data.acceptOwnership();
}
function transferOwnershipImmediately(address _newOwner) public {
data.transferOwnershipImmediately(_newOwner);
}
// ------------------------------------------------------------------------
// Token
// ------------------------------------------------------------------------
function symbol() public view returns (string memory) {
return data.symbol;
}
function name() public view returns (string memory) {
return data.name;
}
function decimals() public view returns (uint8) {
return data.decimals;
}
// ------------------------------------------------------------------------
// Minting and management
// ------------------------------------------------------------------------
function minter() public view returns (address) {
return data.minter;
}
function setMinter(address _minter) public {
data.setMinter(_minter);
}
function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) {
return data.mint(tokenOwner, tokens, lockAccount);
}
function accountLocked(address tokenOwner) public view returns (bool) {
return data.accountLocked[tokenOwner];
}
function unlockAccount(address tokenOwner) public {
data.unlockAccount(tokenOwner);
}
function mintable() public view returns (bool) {
return data.mintable;
}
function transferable() public view returns (bool) {
return data.transferable;
}
function disableMinting() public {
data.disableMinting();
}
function enableTransfers() public {
data.enableTransfers();
}
function nextNonce(address spender) public view returns (uint) {
return data.nextNonce[spender];
}
// ------------------------------------------------------------------------
// Other functions
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) {
return data.transferAnyERC20Token(tokenAddress, tokens);
}
// ------------------------------------------------------------------------
// Don't accept ethers
// ------------------------------------------------------------------------
function () external payable {
revert();
}
// ------------------------------------------------------------------------
// Token functions
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return data.totalSupply - data.balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return data.balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return data.allowed[tokenOwner][spender];
}
function transfer(address to, uint tokens) public returns (bool success) {
return data.transfer(to, tokens);
}
function approve(address spender, uint tokens) public returns (bool success) {
return data.approve(spender, tokens);
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
return data.transferFrom(from, to, tokens);
}
function approveAndCall(address spender, uint tokens, bytes memory _data) public returns (bool success) {
return data.approveAndCall(spender, tokens, _data);
}
// ------------------------------------------------------------------------
// Signed function
// ------------------------------------------------------------------------
function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedTransferHash(tokenOwner, to, tokens, fee, nonce);
}
function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedTransferCheck(tokenOwner, to, tokens, fee, nonce, sig, feeAccount);
}
function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedTransfer(tokenOwner, to, tokens, fee, nonce, sig, feeAccount);
}
function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedApproveHash(tokenOwner, spender, tokens, fee, nonce);
}
function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedApproveCheck(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount);
}
function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedApprove(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount);
}
function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedTransferFromHash(spender, from, to, tokens, fee, nonce);
}
function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedTransferFromCheck(spender, from, to, tokens, fee, nonce, sig, feeAccount);
}
function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedTransferFrom(spender, from, to, tokens, fee, nonce, sig, feeAccount);
}
function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes memory _data, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedApproveAndCallHash(tokenOwner, spender, tokens, _data, fee, nonce);
}
function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes memory _data, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedApproveAndCallCheck(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount);
}
function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes memory _data, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedApproveAndCall(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount);
}
}
| ---------------------------------------------------------------------------- BokkyPooBah's Token Teleportation Service Token v1.10 Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence. ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract DreamFramesToken is BTTSTokenInterface {
using BTTSLib for BTTSLib.Data;
BTTSLib.Data data;
import "../Shared/BTTSTokenLibrary120.sol";
constructor(address owner, string memory symbol, string memory name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public {
data.init(owner, symbol, name, decimals, initialSupply, mintable, transferable);
}
function owner() public view returns (address) {
return data.owner;
}
function newOwner() public view returns (address) {
return data.newOwner;
}
function transferOwnership(address _newOwner) public {
data.transferOwnership(_newOwner);
}
function acceptOwnership() public {
data.acceptOwnership();
}
function transferOwnershipImmediately(address _newOwner) public {
data.transferOwnershipImmediately(_newOwner);
}
function symbol() public view returns (string memory) {
return data.symbol;
}
function name() public view returns (string memory) {
return data.name;
}
function decimals() public view returns (uint8) {
return data.decimals;
}
function minter() public view returns (address) {
return data.minter;
}
function setMinter(address _minter) public {
data.setMinter(_minter);
}
function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) {
return data.mint(tokenOwner, tokens, lockAccount);
}
function accountLocked(address tokenOwner) public view returns (bool) {
return data.accountLocked[tokenOwner];
}
function unlockAccount(address tokenOwner) public {
data.unlockAccount(tokenOwner);
}
function mintable() public view returns (bool) {
return data.mintable;
}
function transferable() public view returns (bool) {
return data.transferable;
}
function disableMinting() public {
data.disableMinting();
}
function enableTransfers() public {
data.enableTransfers();
}
function nextNonce(address spender) public view returns (uint) {
return data.nextNonce[spender];
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) {
return data.transferAnyERC20Token(tokenAddress, tokens);
}
function () external payable {
revert();
}
function totalSupply() public view returns (uint) {
return data.totalSupply - data.balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return data.balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return data.allowed[tokenOwner][spender];
}
function transfer(address to, uint tokens) public returns (bool success) {
return data.transfer(to, tokens);
}
function approve(address spender, uint tokens) public returns (bool success) {
return data.approve(spender, tokens);
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
return data.transferFrom(from, to, tokens);
}
function approveAndCall(address spender, uint tokens, bytes memory _data) public returns (bool success) {
return data.approveAndCall(spender, tokens, _data);
}
function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedTransferHash(tokenOwner, to, tokens, fee, nonce);
}
function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedTransferCheck(tokenOwner, to, tokens, fee, nonce, sig, feeAccount);
}
function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedTransfer(tokenOwner, to, tokens, fee, nonce, sig, feeAccount);
}
function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedApproveHash(tokenOwner, spender, tokens, fee, nonce);
}
function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedApproveCheck(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount);
}
function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedApprove(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount);
}
function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedTransferFromHash(spender, from, to, tokens, fee, nonce);
}
function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedTransferFromCheck(spender, from, to, tokens, fee, nonce, sig, feeAccount);
}
function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedTransferFrom(spender, from, to, tokens, fee, nonce, sig, feeAccount);
}
function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes memory _data, uint fee, uint nonce) public view returns (bytes32 hash) {
return data.signedApproveAndCallHash(tokenOwner, spender, tokens, _data, fee, nonce);
}
function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes memory _data, uint fee, uint nonce, bytes memory sig, address feeAccount) public view returns (CheckResult result) {
return data.signedApproveAndCallCheck(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount);
}
function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes memory _data, uint fee, uint nonce, bytes memory sig, address feeAccount) public returns (bool success) {
return data.signedApproveAndCall(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount);
}
}
| 2,508,201 | [
1,
5802,
7620,
605,
601,
18465,
52,
5161,
38,
9795,
1807,
3155,
399,
19738,
367,
1956,
3155,
331,
21,
18,
2163,
1374,
78,
13372,
18,
261,
71,
13,
605,
601,
18465,
52,
5161,
38,
9795,
342,
605,
601,
11020,
406,
310,
453,
4098,
511,
4465,
14863,
18,
1021,
490,
1285,
511,
335,
802,
18,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
463,
793,
15162,
1345,
353,
605,
1470,
882,
969,
1358,
288,
203,
565,
1450,
605,
1470,
4559,
495,
364,
605,
1470,
4559,
495,
18,
751,
31,
203,
203,
565,
605,
1470,
4559,
495,
18,
751,
501,
31,
203,
203,
203,
5666,
315,
6216,
7887,
19,
38,
1470,
882,
969,
9313,
22343,
18,
18281,
14432,
203,
565,
3885,
12,
2867,
3410,
16,
533,
3778,
3273,
16,
533,
3778,
508,
16,
2254,
28,
15105,
16,
2254,
2172,
3088,
1283,
16,
1426,
312,
474,
429,
16,
1426,
7412,
429,
13,
1071,
225,
288,
203,
3639,
501,
18,
2738,
12,
8443,
16,
3273,
16,
508,
16,
15105,
16,
2172,
3088,
1283,
16,
312,
474,
429,
16,
7412,
429,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
501,
18,
8443,
31,
203,
565,
289,
203,
565,
445,
394,
5541,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
501,
18,
2704,
5541,
31,
203,
565,
289,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
389,
2704,
5541,
13,
1071,
288,
203,
3639,
501,
18,
13866,
5460,
12565,
24899,
2704,
5541,
1769,
203,
565,
289,
203,
565,
445,
2791,
5460,
12565,
1435,
1071,
288,
203,
3639,
501,
18,
9436,
5460,
12565,
5621,
203,
565,
289,
203,
565,
445,
7412,
5460,
12565,
1170,
7101,
12,
2867,
389,
2704,
5541,
13,
1071,
288,
203,
3639,
501,
18,
13866,
5460,
12565,
1170,
7101,
24899,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
2
] |
pragma solidity ^0.4.12;
contract Leaderboard {
// Contract owner
address owner;
// Bid must be multiples of minBid
uint256 public minBid;
// Max num of leaders on the board
uint public maxLeaders;
// Linked list of leaders on the board
uint public numLeaders;
address public head;
address public tail;
mapping (address => Leader) public leaders;
struct Leader {
// Data
uint256 amount;
string url;
string img_url;
// Pointer to next and prev element in linked list
address next;
address previous;
}
// Set initial parameters
function Leaderboard() {
owner = msg.sender;
minBid = 0.001 ether;
numLeaders = 0;
maxLeaders = 10;
}
/*
Default function, make a new bid or add to bid by sending Eth to contract
*/
function () payable {
// Bid must be larger than minBid
require(msg.value >= minBid);
// Bid must be multiple of minBid. Remainder is sent back.
uint256 remainder = msg.value % minBid;
uint256 bid_amount = msg.value - remainder;
// If leaderboard is full, bid needs to be larger than the lowest placed leader
require(!((numLeaders == maxLeaders) && (bid_amount <= leaders[tail].amount)));
// Get leader
Leader memory leader = popLeader(msg.sender);
// Add to leader's bid
leader.amount += bid_amount;
// Insert leader in appropriate position
insertLeader(leader);
// If leaderboard is full, drop last leader
if (numLeaders > maxLeaders) {
dropLast();
}
// Return remainder to sender
if (remainder > 0) msg.sender.transfer(remainder);
}
/*
Set the urls for the link and image
*/
function setUrls(string url, string img_url) {
var leader = leaders[msg.sender];
require(leader.amount > 0);
// Set leader's url if it is not an empty string
bytes memory tmp_url = bytes(url);
if (tmp_url.length != 0) {
// Set url
leader.url = url;
}
// Set leader's img_url if it is not an empty string
bytes memory tmp_img_url = bytes(img_url);
if (tmp_img_url.length != 0) {
// Set image url
leader.img_url = img_url;
}
}
/*
Allow user to reset urls if he wants nothing to show on the board
*/
function resetUrls(bool url, bool img_url) {
var leader = leaders[msg.sender];
require(leader.amount > 0);
// Reset urls
if (url) leader.url = "";
if (img_url) leader.img_url = "";
}
/*
Get a leader at position
*/
function getLeader(address key) constant returns (uint amount, string url, string img_url, address next) {
amount = leaders[key].amount;
url = leaders[key].url;
img_url = leaders[key].img_url;
next = leaders[key].next;
}
/*
Remove from leaderboard LL
*/
function popLeader(address key) internal returns (Leader leader) {
leader = leaders[key];
// If no leader - return
if (leader.amount == 0) {
return leader;
}
if (numLeaders == 1) {
tail = 0x0;
head = 0x0;
} else if (key == head) {
head = leader.next;
leaders[head].previous = 0x0;
} else if (key == tail) {
tail = leader.previous;
leaders[tail].next = 0x0;
} else {
leaders[leader.previous].next = leader.next;
leaders[leader.next].previous = leader.previous;
}
numLeaders--;
return leader;
}
/*
Insert in leaderboard LinkedList
*/
function insertLeader(Leader leader) internal {
if (numLeaders == 0) {
head = msg.sender;
tail = msg.sender;
} else if (leader.amount <= leaders[tail].amount) {
leaders[tail].next = msg.sender;
tail = msg.sender;
} else if (leader.amount > leaders[head].amount) {
leader.next = head;
leaders[head].previous = msg.sender;
head = msg.sender;
} else {
var current_addr = head;
var current = leaders[current_addr];
while (current.amount > 0) {
if (leader.amount > current.amount) {
leader.next = current_addr;
leader.previous = current.previous;
current.previous = msg.sender;
leaders[current.previous].next = msg.sender;
break;
}
current_addr = current.next;
current = leaders[current_addr];
}
}
leaders[msg.sender] = leader;
numLeaders++;
}
/*
Drop last leader from board and return his/her funds
*/
function dropLast() internal {
// Get last leader
address leader_addr = tail;
var leader = popLeader(leader_addr);
uint256 refund_amount = leader.amount;
// Delete leader from board
delete leader;
// Return funds to leader
leader_addr.transfer(refund_amount);
}
/*
Modifier that only allows the owner to call certain functions
*/
modifier onlyOwner {
require(owner == msg.sender);
_;
}
/*
Lets owner withdraw Eth from the contract. Owner can withdraw all funds,
because leaders who fall of the board can always be refunded with the new
bid: (newBid > refund).
*/
function withdraw() onlyOwner {
owner.transfer(this.balance);
}
/*
Set new maximum for amount of leaders
*/
function setMaxLeaders(uint newMax) onlyOwner {
maxLeaders = newMax;
}
} | / Get last leader Delete leader from board Return funds to leader | function dropLast() internal {
address leader_addr = tail;
var leader = popLeader(leader_addr);
uint256 refund_amount = leader.amount;
delete leader;
leader_addr.transfer(refund_amount);
}
| 14,055,162 | [
1,
19,
968,
1142,
10302,
2504,
10302,
628,
11094,
2000,
284,
19156,
358,
10302,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3640,
3024,
1435,
2713,
288,
203,
3639,
1758,
10302,
67,
4793,
273,
5798,
31,
203,
3639,
569,
10302,
273,
1843,
15254,
12,
27863,
67,
4793,
1769,
203,
540,
203,
3639,
2254,
5034,
16255,
67,
8949,
273,
10302,
18,
8949,
31,
203,
540,
203,
3639,
1430,
10302,
31,
203,
540,
203,
3639,
10302,
67,
4793,
18,
13866,
12,
1734,
1074,
67,
8949,
1769,
203,
565,
289,
203,
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
] |
// ___ _ ___ _ _ _
// / __\_ __ _ _ _ __ | |_ ___ / __\(_)| |_ (_) ___ ___
// / / | '__|| | | || '_ \ | __|/ _ \ / / | || __|| | / _ \/ __|
// / /___| | | |_| || |_) || |_| (_) |/ /___ | || |_ | || __/\__ \
// \____/|_| \__, || .__/ \__|\___/ \____/ |_| \__||_| \___||___/
// |___/ |_|
//
// CryptoCities is an ERC721 compliant smart contract for this project:
// (https://cryptocities.net)
//
// In addition to a standard ERC721 interface it also includes:
// - a maker / taker off-chain marketplace which executes final trades here
// - batch functions for most token read functions
// - a limited supply of 25000 tokens
//
// Discord:
// https://discord.gg/Y4mhwWg
//
// Bug Bounty:
// Please see the details of our bug bounty program below.
// https://cryptocities.net/bug_bounty
//
// Disclaimer:
// We take the greatest of care when making our smart contracts but this is crypto and the future
// is always unknown. Even if it is exciting and full of wonderful possibilities, anything can happen,
// blockchains will evolve, vulnerabilities can arise, and markets can go up and down. CryptoCities and its
// owners accept no liability for any issues relating to the use of this contract or any losses that may occur.
// Please see our full terms here:
// https://cryptocities.net/terms
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./base/ERC721Batchable.sol";
contract CryptoCities is ERC721Batchable
{
// there can only ever be a max of this many tokens in the contract
uint public constant tokenLimit = 25000;
// the base url used for all meta data
// likely to be stored on IPFS over time
string private _baseTokenURI;
// the opensea proxy registry contract (can be changed if this registry ever moves to a new contract)
// 0xa5409ec958C83C3f309868babACA7c86DCB077c1 mainnet
// 0xF57B2c51dED3A29e6891aba85459d600256Cf317 rinkeby
// 0x0000000000000000000000000000000000000000 local
address private _proxyRegistryAddress;
// only authorized minters can mint tokens
// this will originally be set to a swapping contract to allow users to swap their tokens to this new contract
mapping (address => bool) public isMinter;
// pausing the market disables the built-in maker/taker offer system
// it does not affect normal ERC721 transfers
bool public marketPaused;
// the marketplace fee for any internal paid trades (stored in basis points eg. 250 = 2.5% fee)
uint16 public marketFee;
// the marketplace witness is used to validate marketplace offers
address private _marketWitness;
// offer that can no longer be used any more
mapping (bytes32 => bool) private _cancelledOrCompletedOffers;
// support for ERC2981
uint16 private _royaltyFee;
address private _royaltyReciever;
constructor(address _owner, address _recovery, address proxyRegistryAddress) ERC721("CryptoCities", unicode"⬢City")
{
// set the owner, recovery & treasury addresses
transferOwnership(_owner);
treasury = _owner;
recovery = _recovery;
// set the meta base url
_baseTokenURI = "https://cryptocities.net/meta/";
// set the open sea proxy registry address
_proxyRegistryAddress = proxyRegistryAddress;
// market starts disabled
marketPaused = true;
marketFee = 250;
}
/// BASE URI
// base uri is where the metadata lives
// only the owner can change this
function setBaseURI(string memory baseTokenURI) external onlyOwner {
_baseTokenURI = baseTokenURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function contractURI() public pure returns (string memory) {
return "https://cryptocities.net/meta/cities_contract";
}
/// PROXY REGISTRY
// registers a proxy address for OpenSea or others
// can only be changed by the contract owner
// setting address to 0 will disable the proxy
function setProxyRegistry(address proxyRegistry) external onlyOwner {
// check the contract address is correct (will revert if not)
if(proxyRegistry!= address(0)) {
ProxyRegistry(proxyRegistry).proxies(address(0));
}
_proxyRegistryAddress = proxyRegistry;
}
// this override allows us to whitelist user's OpenSea proxy accounts to enable gas-less listings
function isApprovedForAll(address token_owner, address operator) public view override returns (bool)
{
// whitelist OpenSea proxy contract for easy trading.
if(_proxyRegistryAddress!= address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
if (address(proxyRegistry.proxies(token_owner)) == operator) {
return true;
}
}
return super.isApprovedForAll(token_owner, operator);
}
/// MINTING
// only authorized minters can mint
// can't mint more tokens than the token limit
// ERC721 standard checks:
// can't mint while the contract is paused (checked in _beforeTokenTransfer())
// token id's can't already exist
// cant mint to address(0)
// if 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
// emitted when a minter's authorization changes
event MinterSet(address indexed minter, bool auth);
// only allows an authorized minter to call the function
modifier onlyMinters()
{
require(isMinter[_msgSender()]==true, "caller not a minter");
_;
}
// changes a minter's authorization
function setMinter(address minter, bool authorized) external onlyOwner
{
isMinter[minter] = authorized;
emit MinterSet(minter, authorized);
}
// mint a single token
function mint(address to, uint256 tokenId) external onlyMinters
{
require(totalSupply()<tokenLimit, "token limit reached");
_safeMint(to, tokenId);
}
// mint a batch of tokens
// (gas: this function can run out of gas if too many id's are provided
// limiting to 25 will currently fit in the block gas limit but this may change in future)
function mintBatch(address to, uint256[] memory tokenIds) external onlyMinters
{
require(tokenIds.length <= 25, "more than 25 ids");
require(totalSupply()+tokenIds.length <= tokenLimit, "batch exceeds token limit");
for (uint256 i = 0; i < tokenIds.length; i++) {
// we safe mint the first token
if(i==0) _safeMint(to, tokenIds[i]);
// then we assume the rest are safe because they are going to the same receiver
else _mint(to, tokenIds[i]);
}
}
/// BURNING
// only the contract owner can burn tokens it owns
// the contract owner can't burn someone elses tokens
// normal users can't burn tokens
// ERC721 standard checks:
// can't burn while the contract is paused (checked in _beforeTokenTransfer())
// the token id must exist
function burn(uint256 tokenId) external onlyOwner
{
require(ownerOf(tokenId) == owner(), "token owner not contract owner");
_burn(tokenId);
}
/// MARKETPLACE
// this contract includes a maker / taker offerplace
// (similar to those seen in OpenSea, 0x Protocol and other NFT projects)
//
// offers are made by makers off-chain and filled by callers on-chain
// makers do this by signing their offer with their wallet
// smart contracts can't be makers because they can't sign messages
// if a witness address is set then it must sign the offer hash too (eg. the website marketplace)
// there are two types of offers depending on whether the maker specifies a taker in their offer:
// maker / taker (peer-to-peer offer: two users agreeing to trade items)
// maker / no taker (open offer: one user listing their items in the marketplace)
// if eth is paid then it will always be on the taker side (the maker never pays eth in this simplified model)
// a market fee is charged if eth is paid
// trading tokens with no eth is free and no fee is deducted
// allowed exchanges:
// maker tokens > < eth (maker sells their tokens to anyone)
// maker tokens > (maker gives their tokens away to anyone)
// maker tokens > taker (maker gives their tokens to a specific taker)
// maker tokens > < taker tokens .. for specific tokens back
// maker tokens > < taker tokens & eth .. for specific tokens and eth back
// maker tokens > < taker eth .. for eth only
// maker < taker tokens (taker gives their tokens to the maker)
// maker < taker tokens & eth .. and with eth
event OfferAccepted(bytes32 indexed hash, address indexed maker, address indexed taker, uint[] makerIds, uint[] takerIds, uint takerWei, uint marketFee);
event OfferCancelled(bytes32 indexed hash);
struct Offer {
address maker;
address taker;
uint256[] makerIds;
uint256[] takerIds;
uint256 takerWei;
uint256 expiry;
uint256 nonce;
}
// pausing the market will stop offers from being able to be accepted (they can still be generated or cancelled)
function pauseMarket(bool pauseTrading) external onlyOwner {
marketPaused = pauseTrading;
}
// the market fee is set in basis points (eg. 250 basis points = 2.5%)
function setMarketFee(uint16 basisPoints) external onlyOwner {
require(basisPoints <= 10000);
marketFee = basisPoints;
}
// if a market witness is set then it will need to sign all offers too (set to 0 to disable)
function setMarketWitness(address newWitness) external onlyOwner {
_marketWitness = newWitness;
}
// recovers the signer address from a offer hash and signature
function signerOfHash(bytes32 offer_hash, bytes memory signature) public pure returns (address signer){
require(signature.length == 65, "sig wrong length");
bytes32 geth_modified_hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", offer_hash));
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "bad sig v");
return ecrecover(geth_modified_hash, v, r, s);
}
// this generates a hash of an offer that can then be signed by a maker
// the offer has to have basic validity before it can be hashed
// if checking ids then the tokens need to be owned by the parties too
function hashOffer(Offer memory offer, bool checkIds) public view returns (bytes32){
// the maker can't be 0
require(offer.maker!=address(0), "maker is 0");
// maker and taker can't be the same
require(offer.maker!=offer.taker, "same maker / taker");
// the offer must not be expired yet
require(block.timestamp < offer.expiry, "expired");
// token id must be in the offer
require(offer.makerIds.length>0 || offer.takerIds.length>0, "no ids");
// if checking ids then maker must own the maker token ids
if(checkIds){
for(uint i=0; i<offer.makerIds.length; i++){
require(ownerOf(offer.makerIds[i])==offer.maker, "bad maker ids");
}
}
// if no taker has been specified (open offer - i.e. typical marketplace listing)
if(offer.taker==address(0)){
// then there can't be taker token ids in the offer
require(offer.takerIds.length==0, "taker ids with no taker");
}
// if a taker has been specified (peer-to-peer offer - i.e. direct trade between two users)
else{
if(checkIds){
// then the taker must own all the taker token ids
for(uint i=0; i<offer.takerIds.length; i++){
require(ownerOf(offer.takerIds[i])==offer.taker, "bad taker ids");
}
}
}
// now return the hash
return keccak256(abi.encode(
offer.maker,
offer.taker,
keccak256(abi.encodePacked(offer.makerIds)),
keccak256(abi.encodePacked(offer.takerIds)),
offer.takerWei,
offer.expiry,
offer.nonce,
address(this) // including the contract address prevents cross-contract replays
));
}
// an offer is valid if:
// it's maker / taker details are valid
// it has been signed by the maker
// it has not been cancelled or completed yet
// the parties own their tokens (if checking ids)
// the witness has signed it (if witnessing is enabled)
// the trade is valid (if requested)
function validOffer(Offer memory offer, bytes memory signature, bytes memory witnessSignature, bool checkIds, bool checkTradeValid, uint checkValue) external view returns (bool){
// will revert if the offer or signer is not valid or checks fail
bytes32 _offer_hash = _getValidOfferHash(offer, signature, checkIds, checkTradeValid, checkValue);
// check the witness if needed
_validWitness(_offer_hash, witnessSignature);
return true;
}
// if a market witness is set then they need to sign the offer hash too
function _validWitness(bytes32 _offer_hash, bytes memory witnessSignature) internal view {
if(_marketWitness!=address(0)){
require(_marketWitness == signerOfHash(_offer_hash, witnessSignature), "wrong witness");
}
}
// gets the hash of an offer and checks that it has been signed by the maker
function _getValidOfferHash(Offer memory offer, bytes memory signature, bool checkIds, bool checkTradeValid, uint checkValue) internal view returns (bytes32){
// get the offer signer
bytes32 _offer_hash = hashOffer(offer, checkIds);
address _signer = signerOfHash(_offer_hash, signature);
// the signer must be the maker
require(offer.maker==_signer, "maker not signer");
// the offer can't be cancelled or completed already
require(_cancelledOrCompletedOffers[_offer_hash]!=true, "offer cancelled or completed");
// if checking the trade then we need to check the taker side too
if(checkTradeValid){
address caller = _msgSender();
// no trading when paused
require(!marketPaused, "marketplace paused");
// caller can't be the maker
require(caller!=offer.maker, "caller is the maker");
// if there is a taker specified then they must be the caller
require(caller==offer.taker || offer.taker==address(0), "caller not the taker");
// check the correct wei has been provided by the taker (can be 0)
require(checkValue==offer.takerWei, "wrong payment sent");
}
return _offer_hash;
}
// (gas: these functions can run out of gas if too many id's are provided
// not limiting them here because block gas limits change over time and we don't know what they will be in future)
// stops the offer hash from being usable in future
// can only be cancelled by the maker or the contract owner
function cancelOffer(Offer memory offer) external {
address caller = _msgSender();
require(caller == offer.maker || caller == owner(), "caller not maker or contract owner");
// get the offer hash
bytes32 _offer_hash = hashOffer(offer, false);
// set the offer hash as cancelled
_cancelledOrCompletedOffers[_offer_hash]=true;
emit OfferCancelled(_offer_hash);
}
// fills an offer
// offers can't be traded when the market is paused or the contract is paused
// offers must be valid and signed by the maker
// the caller has to be the taker or can be an unknown party if no taker is set
// eth may or may not be required by the offer
// tokens must belong to the makers and takers
function acceptOffer(Offer memory offer, bytes memory signature, bytes memory witnessSignature) external payable reentrancyGuard {
// CHECKS
// will revert if the offer or signer is not valid
// will also check token ids to make sure they belong to the parties
// will check the caller and eth matches the offer taker details
bytes32 _offer_hash = _getValidOfferHash(offer, signature, true, true, msg.value);
// check the witness if needed
_validWitness(_offer_hash, witnessSignature);
// EFFECTS
address caller = _msgSender();
// transfer the maker tokens to the caller
for(uint i=0; i<offer.makerIds.length; i++){
_safeTransfer(offer.maker, caller, offer.makerIds[i], "");
}
// transfer the taker tokens to the maker
for(uint i=0; i<offer.takerIds.length; i++){
_safeTransfer(caller, offer.maker, offer.takerIds[i], "");
}
// set the offer has as completed (stops the offer from being reused)
_cancelledOrCompletedOffers[_offer_hash]=true;
// INTERACTIONS
// transfer the payment if one is present
uint _fee = 0;
if(msg.value>0){
// calculate the marketplace fee (stored as basis points)
// eg. 250 basis points is 2.5% (250/10000)
_fee = msg.value * marketFee / 10000;
uint _earned = msg.value - _fee;
// safety check (should never be hit)
assert(_fee>=0 && _earned>=0 && _earned<= msg.value && _fee+_earned==msg.value);
// send the payment to the maker
// security note: calls to a maker should only revert if insufficient gas is sent by the caller/taker
// makers can't be smart contracts because makers need to sign the offer hash for us
// - currently only EOA's (externally owned accounts) can sign a message on the ethereum network
// - smart contracts don't have a private key and can't sign a message, so they can't be makers here
// - offers for specific makers can be blacklisted in the marketplace if required
(bool success, ) = offer.maker.call{value:_earned}("");
require(success, "payment to maker failed");
}
emit OfferAccepted(_offer_hash, offer.maker, caller, offer.makerIds, offer.takerIds, offer.takerWei, _fee);
}
/// ERC2981 support
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == 0x2a55205a // ERC2981
|| super.supportsInterface(interfaceId);
}
function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount)
{
return (_royaltyReciever, (salePrice * _royaltyFee) / 10000);
}
// the royalties fee is set in basis points (eg. 250 basis points = 2.5%)
function setRoyalties(address newReceiver, uint16 basisPoints) external onlyOwner {
require(basisPoints <= 10000);
_royaltyReciever = newReceiver;
_royaltyFee = basisPoints;
}
}
// used to whitelist proxy accounts of OpenSea users so that they are automatically able to trade any item on OpenSea
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "../base/OwnableRecoverable.sol";
// ERC721Batchable wraps multiple commonly used base contracts into a single contract
//
// it includes:
// ERC721 with Enumerable
// contract ownership & recovery
// contract pausing
// treasury
// batching
abstract contract ERC721Batchable is ERC721Enumerable, Pausable, OwnableRecoverable
{
// the treasure address that can make withdrawals from the contract balance
address public treasury;
constructor()
{
}
// used to stop a contract function from being reentrant-called
bool private _reentrancyLock = false;
modifier reentrancyGuard {
require(!_reentrancyLock, "ReentrancyGuard: reentrant call");
_reentrancyLock = true;
_;
_reentrancyLock = false;
}
/// PAUSING
// only the contract owner can pause and unpause
// can't pause if already paused
// can't unpause if already unpaused
// disables minting, burning, transfers (including marketplace accepted offers)
function pause() external virtual onlyOwner {
_pause();
}
function unpause() external virtual onlyOwner {
_unpause();
}
// this hook is called by _mint, _burn & _transfer
// it allows us to block these actions while the contract is paused
// also prevent transfers to the contract address
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
require(to != address(this), "cant transfer to the contract address");
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "token transfer while contract paused");
}
/// TREASURY
// can only be called by the contract owner
// withdrawals can only be made to the treasury account
// allows for a dedicated address to be used for withdrawals
function setTreasury(address newTreasury) external onlyOwner {
require(newTreasury!=address(0), "cant be 0 address");
treasury = newTreasury;
}
// funds can be withdrawn to the treasury account for safe keeping
function treasuryOut(uint amount) external onlyOwner reentrancyGuard {
// can withdraw any amount up to the account balance (0 will withdraw everything)
uint balance = address(this).balance;
if(amount == 0 || amount > balance) amount = balance;
// make the withdrawal
(bool success, ) = treasury.call{value:amount}("");
require(success, "transfer failed");
}
// the owner can pay funds in at any time although this is not needed
// perhaps the contract needs to hold a certain balance in future for some external requirement
function treasuryIn() external payable onlyOwner {
}
/// BATCHING
// all normal ERC721 read functions can be batched
// this allows for any user or app to look up all their tokens in a single call or via paging
function tokenByIndexBatch(uint256[] memory indexes) public view virtual returns (uint256[] memory) {
uint256[] memory batch = new uint256[](indexes.length);
for (uint256 i = 0; i < indexes.length; i++) {
batch[i] = tokenByIndex(indexes[i]);
}
return batch;
}
function balanceOfBatch(address[] memory owners) external view virtual returns (uint256[] memory) {
uint256[] memory batch = new uint256[](owners.length);
for (uint256 i = 0; i < owners.length; i++) {
batch[i] = balanceOf(owners[i]);
}
return batch;
}
function ownerOfBatch(uint256[] memory tokenIds) external view virtual returns (address[] memory) {
address[] memory batch = new address[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; i++) {
batch[i] = ownerOf(tokenIds[i]);
}
return batch;
}
function tokenURIBatch(uint256[] memory tokenIds) external view virtual returns (string[] memory) {
string[] memory batch = new string[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; i++) {
batch[i] = tokenURI(tokenIds[i]);
}
return batch;
}
function getApprovedBatch(uint256[] memory tokenIds) external view virtual returns (address[] memory) {
address[] memory batch = new address[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; i++) {
batch[i] = getApproved(tokenIds[i]);
}
return batch;
}
function tokenOfOwnerByIndexBatch(address owner_, uint256[] memory indexes) external view virtual returns (uint256[] memory) {
uint256[] memory batch = new uint256[](indexes.length);
for (uint256 i = 0; i < indexes.length; i++) {
batch[i] = tokenOfOwnerByIndex(owner_, indexes[i]);
}
return batch;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* This is a modified version of the standard OpenZeppelin Ownable contract that allows for a recovery address to be used to recover ownership
*
*
* @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 OwnableRecoverable is Context {
address private _owner;
// the recovery address can be used to recover ownership if the owner wallet is ever lost
// it should be a cold-storage wallet stored in a vault and never used for any other operation
// it should be set in the parent constructor
// if ownership moves to a new organization then the recovery address should be moved too
address public recovery;
// 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(), "caller is not the owner");
_;
}
modifier onlyOwnerOrRecovery() {
require(_msgSender() == owner() || _msgSender() == recovery, "caller is not the owner or recovery");
_;
}
/**
* @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 onlyOwnerOrRecovery {
require(newOwner != address(0), "cant use 0 address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
_owner = newOwner;
}
// the recovery address can be changed by the owner or the recovery address
function setRecovery(address newRecovery) public virtual onlyOwnerOrRecovery {
require(newRecovery != address(0), "cant use 0 address");
recovery = newRecovery;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| * This is a modified version of the standard OpenZeppelin Ownable contract that allows for a recovery address to be used to recover ownership @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./ the recovery address can be used to recover ownership if the owner wallet is ever lost it should be a cold-storage wallet stored in a vault and never used for any other operation it should be set in the parent constructor if ownership moves to a new organization then the recovery address should be moved too initializes the contract setting the deployer as the initial owner. | abstract contract OwnableRecoverable is Context {
address private _owner;
address public recovery;
constructor () {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "caller is not the owner");
_;
}
modifier onlyOwnerOrRecovery() {
require(_msgSender() == owner() || _msgSender() == recovery, "caller is not the owner or recovery");
_;
}
function transferOwnership(address newOwner) public virtual onlyOwnerOrRecovery {
require(newOwner != address(0), "cant use 0 address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
_owner = newOwner;
}
function setRecovery(address newRecovery) public virtual onlyOwnerOrRecovery {
require(newRecovery != address(0), "cant use 0 address");
recovery = newRecovery;
}
}
| 5,840,733 | [
1,
2503,
353,
279,
4358,
1177,
434,
326,
4529,
3502,
62,
881,
84,
292,
267,
14223,
6914,
6835,
716,
5360,
364,
279,
11044,
1758,
358,
506,
1399,
358,
5910,
23178,
225,
13456,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
326,
11044,
1758,
848,
506,
1399,
358,
5910,
23178,
309,
326,
3410,
9230,
353,
14103,
13557,
518,
1410,
506,
279,
645,
72,
17,
5697,
9230,
4041,
316,
279,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
17801,
6835,
14223,
6914,
426,
17399,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
1758,
1071,
11044,
31,
203,
203,
203,
565,
3885,
1832,
288,
203,
3639,
389,
542,
5541,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
16140,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1162,
11548,
1435,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
422,
3410,
1435,
747,
389,
3576,
12021,
1435,
422,
11044,
16,
315,
16140,
353,
486,
326,
3410,
578,
11044,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
1162,
11548,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
71,
970,
999,
374,
1758,
8863,
203,
3639,
389,
542,
5541,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
542,
5541,
12,
2867,
394,
5541,
13,
3238,
288,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
565,
289,
27699,
203,
565,
445,
444,
11548,
12,
2867,
394,
11548,
13,
1071,
5024,
1338,
5541,
1162,
11548,
288,
27699,
3639,
2583,
12,
2704,
11548,
480,
1758,
12,
20,
3631,
315,
71,
970,
999,
374,
1758,
8863,
203,
3639,
2
] |
./partial_match/3/0xd2a24A3d7d0A7d147EFfAC8F4e4C2F35e29ba685/sources/DCLRent.sol | require(ILandStorage(dclLandProxy).exists(_assetId), "doesnt exist");require(ILandStorage(dclLandProxy).ownerOf(_assetId) == msg.sender, "not owner"); | function landlordTerminateLease(uint256 _assetId) public{
require(platformEnabled, "maintenance");
require(isLeasedByAssetId(_assetId), "no lease");
require(isRentOverDue(_assetId), "tenant good");
require(!isLeaseCompleted(_assetId),"lease has been completed");
require(_transferTenantDeposit(_assetId, leaseByAssetId[_assetId].lessor));
require(_eraseLease(_assetId, true), "erase fail");
}
| 5,118,273 | [
1,
6528,
12,
2627,
464,
3245,
12,
72,
830,
29398,
3886,
2934,
1808,
24899,
9406,
548,
3631,
315,
20657,
496,
1005,
8863,
6528,
12,
2627,
464,
3245,
12,
72,
830,
29398,
3886,
2934,
8443,
951,
24899,
9406,
548,
13,
422,
1234,
18,
15330,
16,
315,
902,
3410,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
19193,
80,
517,
26106,
17746,
12,
11890,
5034,
389,
9406,
548,
13,
1071,
95,
203,
3639,
2583,
12,
9898,
1526,
16,
315,
29715,
8863,
203,
3639,
2583,
12,
291,
1682,
8905,
858,
6672,
548,
24899,
9406,
548,
3631,
315,
2135,
11863,
8863,
203,
3639,
2583,
12,
291,
54,
319,
4851,
30023,
24899,
9406,
548,
3631,
315,
20115,
7494,
8863,
203,
3639,
2583,
12,
5,
291,
17746,
9556,
24899,
9406,
548,
3631,
6,
2508,
711,
2118,
5951,
8863,
203,
3639,
2583,
24899,
13866,
20023,
758,
1724,
24899,
9406,
548,
16,
11863,
858,
6672,
548,
63,
67,
9406,
548,
8009,
2656,
280,
10019,
203,
3639,
2583,
24899,
264,
448,
17746,
24899,
9406,
548,
16,
638,
3631,
315,
264,
448,
2321,
8863,
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
] |
pragma solidity ^0.4.15;
contract Bithereum {
// Keeps track of addresses that have
// provided the Bithereum address for which
// they will be using for redemption
mapping(address => uint256) addressBalances;
// Keeps track of block number at the time
// the sending user provided their Bithereum
// address to the smart contract
mapping(address => uint256) addressBlocks;
// Event that gets triggered each time a user
// sends a redemption transaction to this smart contract
event Redemption(address indexed from, uint256 blockNumber, uint256 ethBalance);
// Retrieves block number at which
// sender performed redemption
function getRedemptionBlockNumber() returns (uint256) {
return addressBlocks[msg.sender];
}
// Retrieves eth balance of sender
// at the time of redemption
function getRedemptionBalance() returns (uint256) {
return addressBalances[msg.sender];
}
// Checks to see if sender is redemption ready
// by verifying that we have a balance and block
// for the sender
function isRedemptionReady() returns (bool) {
return addressBalances[msg.sender] > 0 && addressBlocks[msg.sender] > 0;
}
// Handles incoming transactions
function () payable {
// Store the sender's ETH balance
addressBalances[msg.sender] = msg.sender.balance;
// Store the current block for this sender
addressBlocks[msg.sender] = block.number;
// Emit redemption event
Redemption(msg.sender, addressBlocks[msg.sender], addressBalances[msg.sender]);
}
} | Checks to see if sender is redemption ready by verifying that we have a balance and block for the sender | function isRedemptionReady() returns (bool) {
return addressBalances[msg.sender] > 0 && addressBlocks[msg.sender] > 0;
}
| 5,364,315 | [
1,
4081,
358,
2621,
309,
5793,
353,
283,
19117,
375,
5695,
635,
3929,
310,
716,
732,
1240,
279,
11013,
471,
1203,
364,
326,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
28627,
19117,
375,
8367,
1435,
1135,
261,
6430,
13,
288,
203,
1082,
327,
1758,
38,
26488,
63,
3576,
18,
15330,
65,
405,
374,
597,
1758,
6450,
63,
3576,
18,
15330,
65,
405,
374,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x2d68676c40Bf820Eb84e3B7d8d77a1C473b08B61/sources/contracts/libraries/Formatters.sol | @dev Encode Assets data type to bytes array @param _assets Assets that need to be encoded Storage Slots Used 1 slot => 32 bytes for lenght of assets 3 slots => 96 bytes for each of AssetData struct total = 32 bytes + assetCount 96 bytes/ | function _encodeAssets(
Assets memory _assets
) private pure returns (bytes memory data) {
bytes memory packedAssets;
uint len = _assets.assets.length;
for (uint i; i < len; ) {
packedAssets = abi.encodePacked(
packedAssets,
_assets.assets[i].token,
_assets.assets[i].assetType,
_assets.assets[i].tokenId,
_assets.assets[i].amount
);
unchecked {
++i;
}
}
return abi.encodePacked(_assets.assets.length, packedAssets);
}
| 17,067,193 | [
1,
5509,
26284,
501,
618,
358,
1731,
526,
225,
389,
9971,
26284,
716,
1608,
358,
506,
3749,
5235,
9708,
6968,
10286,
404,
4694,
516,
3847,
1731,
364,
562,
75,
647,
434,
7176,
890,
12169,
516,
19332,
1731,
364,
1517,
434,
10494,
751,
1958,
2078,
273,
3847,
1731,
397,
3310,
1380,
225,
19332,
1731,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
3015,
10726,
12,
203,
3639,
26284,
3778,
389,
9971,
203,
565,
262,
3238,
16618,
1135,
261,
3890,
3778,
501,
13,
288,
203,
203,
3639,
1731,
3778,
12456,
10726,
31,
203,
203,
3639,
2254,
562,
273,
389,
9971,
18,
9971,
18,
2469,
31,
203,
3639,
364,
261,
11890,
277,
31,
277,
411,
562,
31,
262,
288,
203,
5411,
12456,
10726,
273,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
12456,
10726,
16,
203,
7734,
389,
9971,
18,
9971,
63,
77,
8009,
2316,
16,
203,
7734,
389,
9971,
18,
9971,
63,
77,
8009,
9406,
559,
16,
203,
7734,
389,
9971,
18,
9971,
63,
77,
8009,
2316,
548,
16,
203,
7734,
389,
9971,
18,
9971,
63,
77,
8009,
8949,
203,
5411,
11272,
203,
5411,
22893,
288,
203,
7734,
965,
77,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
24126,
18,
3015,
4420,
329,
24899,
9971,
18,
9971,
18,
2469,
16,
12456,
10726,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >= 0.6.12;
import "./libs/ProtofiERC20.sol";
/**
This is the contract of the primary token.
Features:
- 2% burn mechanism for every transaction.
- Ownable
- Strictly related to the second token
- You can use the second token to claim the primary token.
- Antiwhale, can be set up only by operator
Owner --> Masterchef for farming features
Operator --> Team address that handles the antiwhales settings when needed
*/
contract ProtonToken is ProtofiERC20 {
// Address to the secondary token
address public electron;
bool private _isElectronSetup = false;
// Addresses that excluded from antiWhale
mapping(address => bool) private _excludedFromAntiWhale;
// Addresses that excluded from transfer fee
mapping(address => bool) private _excludedFromTransferFee;
// Max transfer amount rate in basis points. Eg: 50 - 0.5% of total supply (default the anti whale feature is turned off - set to 10000.)
uint16 public maxTransferAmountRate = 10000;
// Minimum transfer amount rate in basis points. Deserved for user trust, we can't block users to send this token.
// maxTransferAmountRate cannot be lower than BASE_MIN_TRANSFER_AMOUNT_RATE
uint16 public constant BASE_MAX_TRANSFER_AMOUNT_RATE = 100; // Cannot be changed, ever!
// The operator can only update the Anti Whale Settings
address private _operator;
// Events
event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
constructor() public ProtofiERC20("Protofi Token", "PROTO"){
// After initializing the token with the original constructor of ProtofiERC20
// setup antiwhale variables.
_operator = msg.sender;
emit OperatorTransferred(address(0), _operator);
_excludedFromAntiWhale[msg.sender] = true; // Original deployer address
_excludedFromAntiWhale[address(0)] = true;
_excludedFromAntiWhale[address(this)] = true;
_excludedFromAntiWhale[BURN_ADDRESS] = true;
}
/**
@dev similar to onlyOwner but used to handle the antiwhale side of the smart contract.
In that way the ownership can be transferred to the MasterChef without preventing devs to modify
antiwhale settings.
*/
modifier onlyOperator() {
require(_operator == msg.sender, "operator: caller is not the operator");
_;
}
/**
Exludes sender to send more than a certain amount of tokens given settings, if the
sender is not whitelisted!
*/
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (maxTransferAmount() > 0) {
if (
_excludedFromAntiWhale[sender] == false
) {
require(amount <= maxTransferAmount(), "PROTO::antiWhale: Transfer amount exceeds the maxTransferAmount");
}
}
_;
}
/**
* @dev Returns the max transfer amount.
*/
function maxTransferAmount() public view returns (uint256) {
return totalSupply().mul(maxTransferAmountRate).div(10000);
}
/**
* @dev Update the max transfer amount rate.
* Can only be called by the current operator.
*/
function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator {
require(_maxTransferAmountRate <= 10000, "PROTO::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
require(_maxTransferAmountRate >= BASE_MAX_TRANSFER_AMOUNT_RATE, "PROTO::updateMaxTransferAmountRate: _maxTransferAmountRate should be at least _maxTransferAmountRate");
emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
maxTransferAmountRate = _maxTransferAmountRate;
}
/**
* @dev Returns the address is excluded from antiWhale or not.
*/
function isExcludedFromAntiWhale(address _account) public view returns (bool) {
return _excludedFromAntiWhale[_account];
}
/**
* @dev Exclude or include an address from antiWhale.
* Can only be called by the current operator.
*/
function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOperator {
_excludedFromAntiWhale[_account] = _excluded;
}
/**
* @dev Returns the address is excluded from transfer fee or not.
*/
function isExcludedFromTransferFee(address _account) public view returns (bool) {
return _excludedFromTransferFee[_account];
}
/**
* @dev Exclude or include an address from transfer fee.
* Can only be called by the current operator.
*/
function setExcludedFromTransferFee(address _account, bool _excluded) public onlyOperator {
_excludedFromTransferFee[_account] = _excluded;
}
/// @dev Throws if called by any account other than the owner or the secondary token
modifier onlyOwnerOrElectron() {
require(isOwner() || isElectron(), "caller is not the owner or electron");
_;
}
/// @dev Returns true if the caller is the current owner.
function isOwner() public view returns (bool) {
return msg.sender == owner();
}
/// @dev Returns true if the caller is electron contracts.
function isElectron() internal view returns (bool) {
return msg.sender == address(electron);
}
/// @dev Sets the secondary token address.
function setupElectron(address _electron) external onlyOwner{
require(!_isElectronSetup, "The Electron token address has already been set up. No one can change it anymore.");
electron = _electron;
_isElectronSetup = true;
}
/**
@notice Creates `_amount` token to `_to`. Must only be called by the masterchef or
by the secondary token(during swap)
*/
function mint(address _to, uint256 _amount) external virtual override onlyOwnerOrElectron {
_mint(_to, _amount);
}
/// @dev overrides transfer function to meet tokenomics of PROTO
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) {
require(amount > 0, "amount 0");
if (recipient == BURN_ADDRESS) {
// Burn all the amount
super._burn(sender, amount);
} else if (_excludedFromTransferFee[sender] || _excludedFromTransferFee[recipient]){
// Transfer all the amount
super._transfer(sender, recipient, amount);
} else {
// 1.8% of every transfer burnt
uint256 burnAmount = amount.mul(18).div(1000);
// 98.2% of transfer sent to recipient
uint256 sendAmount = amount.sub(burnAmount);
require(amount == sendAmount + burnAmount, "PROTO::transfer: Burn value invalid");
super._burn(sender, burnAmount);
super._transfer(sender, recipient, sendAmount);
amount = sendAmount;
}
}
/**
* @dev Transfers operator of the contract to a new account (`newOperator`).
* Can only be called by the current operator.
*/
function transferOperator(address newOperator) public onlyOperator {
require(newOperator != address(0), "ProtonToken::transferOperator: new operator is the zero address");
emit OperatorTransferred(_operator, newOperator);
_operator = newOperator;
}
} | @dev Throws if called by any account other than the owner or the secondary token | modifier onlyOwnerOrElectron() {
require(isOwner() || isElectron(), "caller is not the owner or electron");
_;
}
| 12,993,626 | [
1,
21845,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
3410,
578,
326,
9946,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
5541,
1162,
28621,
1435,
288,
203,
3639,
2583,
12,
291,
5541,
1435,
747,
353,
28621,
9334,
315,
16140,
353,
486,
326,
3410,
578,
27484,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./interface/IUniswap.sol";
import "./ExoticRewardsTracker.sol";
contract Exotic is
Initializable,
ContextUpgradeable,
OwnableUpgradeable,
ERC20Upgradeable
{
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
uint256 public ETHRewardsFee;
uint256 public liquidityFee;
uint256 public teamFee;
uint256 public notHoldersFee;
uint256 public totalFees;
bool private swapping;
ExoticRewardsTracker public rewardsTracker;
address public liquidityWallet;
address payable public teamWallet;
uint256 public swapTokensAtAmount;
uint256 public maxSellTransactionAmount;
// Include this from the client request
uint256 public excludeFromFeesUntilAtAmount;
bool public useExcludeFromFeesUntilAtAmount;
uint256 public sellFeeIncreaseFactor;
uint256 public gasForProcessing;
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// store addresses that an automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateRewardsTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event SwapForNotHolders(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SendRewardsForHolders(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedRewardsTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
event ChangeFees(
uint256 newEthRewardsFee,
uint256 newLiquidityFee,
uint256 newTeamFee
);
function initialize() initializer public {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC20_init("Exotic Metaverse", "EXOTIC");
ETHRewardsFee = 2;
liquidityFee = 2;
teamFee = 6;
notHoldersFee = liquidityFee.add(teamFee);
totalFees = 10;
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
rewardsTracker = ExoticRewardsTracker(payable(0xB36e347Bbbd6cbEf31BF7d0AE50Abb11Cc78ECc5));
liquidityWallet = owner();
teamWallet = payable(0x6e8c9AF9715A9bb9D28F2e139C811F6eB47d47F0);
swapTokensAtAmount = 5000 * (10**18);
maxSellTransactionAmount = 200000 * (10**18);
excludeFromFeesUntilAtAmount = 1000 * (10**18);
useExcludeFromFeesUntilAtAmount = true;
// sells have fees of 12 and 6 (10 * 1.2 and 5 * 1.2)
sellFeeIncreaseFactor = 120;
// use by default 300,000 gas to process auto-claiming rewards
gasForProcessing = 300000;
automatedMarketMakerPairs[uniswapV2Pair] = true;
excludeFromFees(liquidityWallet, true);
excludeFromFees(address(this), true);
_mint(owner(), 10000000 * (10**18));
}
receive() external payable {
}
function updateRewardsTracker(address newAddress) public onlyOwner {
ExoticRewardsTracker newRewardsTracker = ExoticRewardsTracker(payable(newAddress));
require(newRewardsTracker.owner() == address(this), "The new one must be owned by the EXOTIC token contract");
newRewardsTracker.excludeFromRewards(address(newRewardsTracker));
newRewardsTracker.excludeFromRewards(address(this));
newRewardsTracker.excludeFromRewards(owner());
newRewardsTracker.excludeFromRewards(address(uniswapV2Router));
emit UpdateRewardsTracker(newAddress, address(rewardsTracker));
rewardsTracker = newRewardsTracker;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
}
function changeFees(uint256 newEthRewardsFee, uint256 newLiquidityFee, uint256 newTeamFee) external onlyOwner {
ETHRewardsFee = newEthRewardsFee;
liquidityFee = newLiquidityFee;
teamFee = newTeamFee;
notHoldersFee = liquidityFee.add(teamFee);
totalFees = ETHRewardsFee.add(liquidityFee).add(teamFee);
emit ChangeFees(ETHRewardsFee, liquidityFee, teamFee);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeFromRewards(address account) external onlyOwner {
rewardsTracker.excludeFromRewards(account);
}
function setSellFactor(uint256 newFactor) external onlyOwner {
sellFeeIncreaseFactor = newFactor;
}
function setSwapAtAmount(uint256 newAmount) external onlyOwner {
swapTokensAtAmount = newAmount * (10**18);
}
function setExcludeFromFeesUntilAtAmount(uint256 newAmount) external onlyOwner {
excludeFromFeesUntilAtAmount = newAmount * (10**18);
}
function setUseExcludeFromFeesUntilAtAmount(bool use) external onlyOwner {
useExcludeFromFeesUntilAtAmount = use;
}
function changeMinimumHoldingLimit(uint256 newLimit) public onlyOwner {
rewardsTracker.setMinimumTokenBalanceForRewards(newLimit);
}
function changeMaxSellAmount(uint256 newAmount) external onlyOwner {
maxSellTransactionAmount = newAmount * (10**18);
}
function changeTeamWallet(address payable newAddress) external onlyOwner {
teamWallet = newAddress;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
if(value) {
rewardsTracker.excludeFromRewards(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateLiquidityWallet(address newLiquidityWallet) public onlyOwner {
excludeFromFees(newLiquidityWallet, true);
emit LiquidityWalletUpdated(newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
require(newValue >= 200000 && newValue <= 500000, "Must be between the 200000 and 500000");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
rewardsTracker.updateClaimWait(claimWait);
}
function getClaimWait() external view returns(uint256) {
return rewardsTracker.claimWait();
}
function minimumLimitForRewards() public view returns(uint256) {
return rewardsTracker.minimumTokenLimit();
}
function getTotalRewardsDistributed() external view returns (uint256) {
return rewardsTracker.totalRewardsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function isExcludedFromRewards(address account) public view returns(bool) {
return rewardsTracker.excludedFromRewards(account);
}
function withdrawableRewardsOf(address account) public view returns(uint256) {
return rewardsTracker.withdrawableRewardOf(account);
}
function rewardsTokenBalanceOf(address account) public view returns (uint256) {
return rewardsTracker.balanceOf(account);
}
function getAccountRewardsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return rewardsTracker.getAccount(account);
}
function getAccountRewardsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return rewardsTracker.getAccountAtIndex(index);
}
function processRewardsTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = rewardsTracker.process(gas);
emit ProcessedRewardsTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
rewardsTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return rewardsTracker.getLastProcessedIndex();
}
function getNumberOfRewardsTokenHolders() external view returns(uint256) {
return rewardsTracker.getNumberOfTokenHolders();
}
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 sendETHtoTeamWallet(uint256 amount) private {
swapTokensForEth(amount);
uint256 balance = address(this).balance;
teamWallet.transfer(balance);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
liquidityWallet,
block.timestamp
);
}
function swapForNotHolders(uint256 tokens) private {
uint256 forLiquidtyWalletToken = tokens.mul(liquidityFee).div(notHoldersFee).div(2);
uint256 forTeamWallet = tokens.mul(teamFee).div(notHoldersFee);
uint256 balanceBeforeSwap = address(this).balance;
swapTokensForEth(forLiquidtyWalletToken); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
uint256 ethReceivedFromSwap = address(this).balance.sub(balanceBeforeSwap);
addLiquidity(forLiquidtyWalletToken, ethReceivedFromSwap);
sendETHtoTeamWallet(forTeamWallet);
emit SwapForNotHolders(forLiquidtyWalletToken, ethReceivedFromSwap, forLiquidtyWalletToken);
}
function swapToSendRewardsForHolders(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 rewards = address(this).balance;
(bool success,) = address(rewardsTracker).call{value: rewards}("");
if(success) {
emit SendRewardsForHolders(tokens, rewards);
}
}
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(
!swapping &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] && //no max for those excluded from fees
from != liquidityWallet
) {
require(amount <= maxSellTransactionAmount, "It exceeds the maxSellTransactionAmount.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
swapping = true;
uint256 swapTokensForNotHolders = contractTokenBalance.mul(notHoldersFee).div(totalFees);
swapForNotHolders(swapTokensForNotHolders);
uint256 sellTokensForHolders = balanceOf(address(this));
swapToSendRewardsForHolders(sellTokensForHolders);
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (useExcludeFromFeesUntilAtAmount && amount <= excludeFromFeesUntilAtAmount) {
takeFee = false;
}
if(takeFee) {
uint256 fees = amount.mul(totalFees).div(100);
if(automatedMarketMakerPairs[to]) {
fees = fees.mul(sellFeeIncreaseFactor).div(100); //
}
amount = amount.sub(fees); // Take default fees away here
super._transfer(from, address(this), fees); // Send to this contract
}
super._transfer(from, to, amount);
try rewardsTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try rewardsTracker.setBalance(payable(to), balanceOf(to)) {} catch {}
if(!swapping) {
uint256 gas = gasForProcessing;
try rewardsTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedRewardsTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
}
catch {
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_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 {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
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 getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./lib/IterableMapping.sol";
/// @author Roger Wu (https://github.com/roger-wu) rename from dividends to rewards
interface RewardPayingTokenInterface {
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function rewardOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as rewards.
/// @dev SHOULD distribute the paid ether to token holders as rewards.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `RewardsDistributed` event when the amount of distributed ether is greater than 0.
function distributeRewards() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `rewardOf(msg.sender)` wei to `msg.sender`, and `rewardOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `RewardWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawReward() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event RewardsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their reward.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event RewardWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/// @title Reward-Paying Token Optional Interface
/// @dev OPTIONAL functions for a reward-paying token contract.
interface RewardPayingTokenOptionalInterface {
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function withdrawableRewardOf(address _owner) external view returns(uint256);
/// @notice View the amount of reward in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has withdrawn.
function withdrawnRewardOf(address _owner) external view returns(uint256);
/// @notice View the amount of reward in wei that an address has earned in total.
/// @dev accumulativeRewardOf(_owner) = withdrawableRewardOf(_owner) + withdrawnRewardOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has earned in total.
function accumulativeRewardOf(address _owner) external view returns(uint256);
}
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
/// @title Reward-Paying Token
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as rewards and allows token holders to withdraw their rewards.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract RewardPayingToken is ERC20, RewardPayingTokenInterface, RewardPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute rewards even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedRewardPerShare;
// About rewardCorrection:
// If the token balance of a `_user` is never changed, the reward of `_user` can be computed with:
// `rewardOf(_user) = rewardPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `rewardOf(_user)` should not be changed,
// but the computed value of `rewardPerShare * balanceOf(_user)` is changed.
// To keep the `rewardOf(_user)` unchanged, we add a correction term:
// `rewardOf(_user) = rewardPerShare * balanceOf(_user) + rewardCorrectionOf(_user)`,
// where `rewardCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `rewardCorrectionOf(_user) = rewardPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `rewardOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedRewardCorrections;
mapping(address => uint256) internal withdrawnRewards;
uint256 public totalRewardsDistributed;
constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {
}
/// @dev Distributes rewards whenever ether is paid to this contract.
receive() external payable {
distributeRewards();
}
/// @notice Distributes ether to token holders as rewards.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `RewardsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeRewards() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedRewardPerShare = magnifiedRewardPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit RewardsDistributed(msg.sender, msg.value);
totalRewardsDistributed = totalRewardsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `RewardWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawReward() public virtual override {
_withdrawRewardOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `RewardWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawRewardOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableReward = withdrawableRewardOf(user);
if (_withdrawableReward > 0) {
withdrawnRewards[user] = withdrawnRewards[user].add(_withdrawableReward);
emit RewardWithdrawn(user, _withdrawableReward);
(bool success,) = user.call{value: _withdrawableReward, gas: 3000}("");
if(!success) {
withdrawnRewards[user] = withdrawnRewards[user].sub(_withdrawableReward);
return 0;
}
return _withdrawableReward;
}
return 0;
}
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function rewardOf(address _owner) public view override returns(uint256) {
return withdrawableRewardOf(_owner);
}
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function withdrawableRewardOf(address _owner) public view override returns(uint256) {
return accumulativeRewardOf(_owner).sub(withdrawnRewards[_owner]);
}
/// @notice View the amount of reward in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has withdrawn.
function withdrawnRewardOf(address _owner) public view override returns(uint256) {
return withdrawnRewards[_owner];
}
/// @notice View the amount of reward in wei that an address has earned in total.
/// @dev accumulativeRewardOf(_owner) = withdrawableRewardOf(_owner) + withdrawnRewardOf(_owner)
/// = (magnifiedRewardPerShare * balanceOf(_owner) + magnifiedRewardCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has earned in total.
function accumulativeRewardOf(address _owner) public view override returns(uint256) {
return magnifiedRewardPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedRewardCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedRewardCorrections to keep rewards unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedRewardPerShare.mul(value).toInt256Safe();
magnifiedRewardCorrections[from] = magnifiedRewardCorrections[from].add(_magCorrection);
magnifiedRewardCorrections[to] = magnifiedRewardCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedRewardCorrections to keep rewards unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedRewardCorrections[account] = magnifiedRewardCorrections[account]
.sub( (magnifiedRewardPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedRewardCorrections to keep rewards unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedRewardCorrections[account] = magnifiedRewardCorrections[account]
.add( (magnifiedRewardPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
contract ExoticRewardsTracker is RewardPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromRewards;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 private minimumTokenBalanceForRewards;
event ExcludeFromRewards(address indexed account);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() public RewardPayingToken("ExoticRewardsTracker", "ExoticRewardsTracker") {
claimWait = 3600;
minimumTokenBalanceForRewards = 2000 * (10**18);
}
function setMinimumTokenBalanceForRewards(uint256 newMinTokenBalForRewards) external onlyOwner {
minimumTokenBalanceForRewards = newMinTokenBalForRewards * (10**18);
}
function _transfer(address, address, uint256) internal override {
require(false, "No transfers allowed");
}
function withdrawReward() public override {
require(false, "It is disabled. Use the 'claim' function on the main NFTY contract.");
}
function excludeFromRewards(address account) external onlyOwner {
require(!excludedFromRewards[account]);
excludedFromRewards[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromRewards(account);
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "claimWait must be updated to between 1 and 24 hours");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function minimumTokenLimit() public view returns(uint256) {
return minimumTokenBalanceForRewards;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableRewards,
uint256 totalRewards,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableRewards = withdrawableRewardOf(account);
totalRewards = accumulativeRewardOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromRewards[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForRewards) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawRewardOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the 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";
/**
* @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);
} | sells have fees of 12 and 6 (10 * 1.2 and 5 * 1.2) use by default 300,000 gas to process auto-claiming rewards | function initialize() initializer public {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC20_init("Exotic Metaverse", "EXOTIC");
ETHRewardsFee = 2;
liquidityFee = 2;
teamFee = 6;
notHoldersFee = liquidityFee.add(teamFee);
totalFees = 10;
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
rewardsTracker = ExoticRewardsTracker(payable(0xB36e347Bbbd6cbEf31BF7d0AE50Abb11Cc78ECc5));
liquidityWallet = owner();
teamWallet = payable(0x6e8c9AF9715A9bb9D28F2e139C811F6eB47d47F0);
swapTokensAtAmount = 5000 * (10**18);
maxSellTransactionAmount = 200000 * (10**18);
excludeFromFeesUntilAtAmount = 1000 * (10**18);
useExcludeFromFeesUntilAtAmount = true;
sellFeeIncreaseFactor = 120;
gasForProcessing = 300000;
automatedMarketMakerPairs[uniswapV2Pair] = true;
excludeFromFees(liquidityWallet, true);
excludeFromFees(address(this), true);
_mint(owner(), 10000000 * (10**18));
}
| 10,321,015 | [
1,
87,
1165,
87,
1240,
1656,
281,
434,
2593,
471,
1666,
261,
2163,
225,
404,
18,
22,
471,
1381,
225,
404,
18,
22,
13,
999,
635,
805,
11631,
16,
3784,
16189,
358,
1207,
3656,
17,
14784,
310,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
1435,
12562,
1071,
288,
203,
3639,
1001,
1042,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
654,
39,
3462,
67,
2738,
2932,
424,
352,
335,
6565,
2476,
3113,
315,
2294,
1974,
2871,
8863,
203,
203,
3639,
512,
2455,
17631,
14727,
14667,
273,
576,
31,
203,
203,
3639,
4501,
372,
24237,
14667,
273,
576,
31,
203,
3639,
5927,
14667,
273,
1666,
31,
203,
3639,
486,
27003,
14667,
273,
4501,
372,
24237,
14667,
18,
1289,
12,
10035,
14667,
1769,
203,
540,
203,
3639,
2078,
2954,
281,
273,
1728,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
3639,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
640,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
377,
202,
266,
6397,
8135,
273,
1312,
352,
335,
17631,
14727,
8135,
12,
10239,
429,
12,
20,
20029,
5718,
73,
5026,
27,
38,
9897,
72,
26,
7358,
41,
74,
6938,
15259,
27,
72,
20,
16985,
3361,
5895,
70,
2499,
39,
71,
8285,
7228,
71,
25,
2
] |
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {PercentageMath} from "../libraries/math/PercentageMath.sol";
import {WadRayMath} from "../libraries/math/WadRayMath.sol";
import {IInterestRateModel} from "../interfaces/IInterestRateModel.sol";
import {Constants} from "../libraries/helpers/Constants.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title Linear Interest Rate Model
/// @notice Linear interest rate model, similar which Aave uses
contract LinearInterestRateModel is IInterestRateModel {
using PercentageMath for uint256;
using SafeMath for uint256;
using WadRayMath for uint256;
// Uoptimal[0;1] in Wad
uint256 public immutable _U_Optimal_WAD;
// 1 - Uoptimal [0;1] x10.000, percentage plus two decimals
uint256 public immutable _U_Optimal_inverted_WAD;
// R_base in Ray
uint256 public immutable _R_base_RAY;
// R_Slope1 in Ray
uint256 public immutable _R_slope1_RAY;
// R_Slope2 in Ray
uint256 public immutable _R_slope2_RAY;
// Contract version
uint constant public version = 1;
/// @dev Constructor
/// @param U_optimal Optimal U in percentage format: x10.000 - percentage plus two decimals
/// @param R_base R_base in percentage format: x10.000 - percentage plus two decimals @param R_slope1 R_Slope1 in Ray
/// @param R_slope1 R_Slope1 in percentage format: x10.000 - percentage plus two decimals
/// @param R_slope2 R_Slope2 in percentage format: x10.000 - percentage plus two decimals
constructor(
uint256 U_optimal,
uint256 R_base,
uint256 R_slope1,
uint256 R_slope2
) {
require(
U_optimal <= PercentageMath.PERCENTAGE_FACTOR,
Errors.INCORRECT_PARAMETER
);
require(
R_base <= PercentageMath.PERCENTAGE_FACTOR,
Errors.INCORRECT_PARAMETER
);
require(
R_slope1 <= PercentageMath.PERCENTAGE_FACTOR,
Errors.INCORRECT_PARAMETER
);
// Convert percetns to WAD
uint256 U_optimal_WAD = WadRayMath.WAD.percentMul(U_optimal);
_U_Optimal_WAD = U_optimal_WAD;
// 1 - Uoptimal in WAD
_U_Optimal_inverted_WAD = WadRayMath.WAD.sub(U_optimal_WAD);
_R_base_RAY = WadRayMath.RAY.percentMul(R_base);
_R_slope1_RAY = WadRayMath.RAY.percentMul(R_slope1);
_R_slope2_RAY = WadRayMath.RAY.percentMul(R_slope2);
}
/// @dev Calculated borrow rate based on expectedLiquidity and availableLiquidity
/// @param expectedLiquidity Expected liquidity in the pool
/// @param availableLiquidity Available liquidity in the pool
function calcBorrowRate(
uint256 expectedLiquidity,
uint256 availableLiquidity
) external view override returns (uint256) {
// Protection from direct sending tokens on PoolService account
// T:[LR-5] // T:[LR-6]
if (expectedLiquidity == 0 || expectedLiquidity < availableLiquidity) {
return _R_base_RAY;
}
// expectedLiquidity - availableLiquidity
// U = -------------------------------------
// expectedLiquidity
uint256 U_WAD = (expectedLiquidity.sub(availableLiquidity))
.mul(WadRayMath.WAD)
.div(expectedLiquidity);
// if U < Uoptimal:
//
// U
// borrowRate = Rbase + Rslope1 * ----------
// Uoptimal
//
if (U_WAD < _U_Optimal_WAD) {
return
_R_base_RAY.add(_R_slope1_RAY.mul(U_WAD).div(_U_Optimal_WAD));
}
// if U >= Uoptimal:
//
// U - Uoptimal
// borrowRate = Rbase + Rslope1 + Rslope2 * --------------
// 1 - Uoptimal
return
_R_base_RAY.add(_R_slope1_RAY).add(
_R_slope2_RAY.mul(U_WAD.sub(_U_Optimal_WAD)).div(
_U_Optimal_inverted_WAD
)
); // T:[LR-1,2,3]
}
/// @dev Gets model parameters
/// @param U_optimal U_optimal in percentage format: [0;10,000] - percentage plus two decimals
/// @param R_base R_base in RAY format
/// @param R_slope1 R_slope1 in RAY format
/// @param R_slope2 R_slope2 in RAY format
function getModelParameters()
external
view
returns (
uint256 U_optimal,
uint256 R_base,
uint256 R_slope1,
uint256 R_slope2
)
{
U_optimal = _U_Optimal_WAD.percentDiv(WadRayMath.WAD); // T:[LR-4]
R_base = _R_base_RAY; // T:[LR-4]
R_slope1 = _R_slope1_RAY; // T:[LR-4]
R_slope2 = _R_slope2_RAY; // T:[LR-4]
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.7.4;
import {Errors} from "../helpers/Errors.sol";
/**
* @title PercentageMath library
* @author Aave
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage)
internal
pure
returns (uint256)
{
if (value == 0 || percentage == 0) {
return 0; // T:[PM-1]
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[PM-1]
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; // T:[PM-1]
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage)
internal
pure
returns (uint256)
{
require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[PM-2]
uint256 halfPercentage = percentage / 2; // T:[PM-2]
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[PM-2]
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.7.4;
import {Errors} from "../helpers/Errors.sol";
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
* More info https://github.com/aave/aave-protocol/blob/master/contracts/libraries/WadRayMath.sol
*/
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
*/
function ray() internal pure returns (uint256) {
return RAY; // T:[WRM-1]
}
/**
* @return One wad, 1e18
*/
function wad() internal pure returns (uint256) {
return WAD; // T:[WRM-1]
}
/**
* @return Half ray, 1e27/2
*/
function halfRay() internal pure returns (uint256) {
return halfRAY; // T:[WRM-2]
}
/**
* @return Half ray, 1e18/2
*/
function halfWad() internal pure returns (uint256) {
return halfWAD; // T:[WRM-2]
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
*/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0; // T:[WRM-3]
}
require(
a <= (type(uint256).max - halfWAD) / b,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[WRM-3]
return (a * b + halfWAD) / WAD; // T:[WRM-3]
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
*/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[WRM-4]
uint256 halfB = b / 2;
require(
a <= (type(uint256).max - halfB) / WAD,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[WRM-4]
return (a * WAD + halfB) / b; // T:[WRM-4]
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
*/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0; // T:[WRM-5]
}
require(
a <= (type(uint256).max - halfRAY) / b,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[WRM-5]
return (a * b + halfRAY) / RAY; // T:[WRM-5]
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
*/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[WRM-6]
uint256 halfB = b / 2; // T:[WRM-6]
require(
a <= (type(uint256).max - halfB) / RAY,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[WRM-6]
return (a * RAY + halfB) / b; // T:[WRM-6]
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
*/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2; // T:[WRM-7]
uint256 result = halfRatio + a; // T:[WRM-7]
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); // T:[WRM-7]
return result / WAD_RAY_RATIO; // T:[WRM-7]
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
*/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO; // T:[WRM-8]
require(
result / WAD_RAY_RATIO == a,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[WRM-8]
return result; // T:[WRM-8]
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
/// @title IInterestRateModel interface
/// @dev Interface for the calculation of the interest rates
interface IInterestRateModel {
/// @dev Calculated borrow rate based on expectedLiquidity and availableLiquidity
/// @param expectedLiquidity Expected liquidity in the pool
/// @param availableLiquidity Available liquidity in the pool
function calcBorrowRate(uint256 expectedLiquidity, uint256 availableLiquidity)
external
view
returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {PercentageMath} from "../math/PercentageMath.sol";
library Constants {
uint256 constant MAX_INT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// 25% of MAX_INT
uint256 constant MAX_INT_4 =
0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// REWARD FOR LEAN DEPLOYMENT MINING
uint256 constant ACCOUNT_CREATION_REWARD = 1e5;
uint256 constant DEPLOYMENT_COST = 1e17;
// FEE = 10%
uint256 constant FEE_INTEREST = 1000; // 10%
// FEE + LIQUIDATION_FEE 2%
uint256 constant FEE_LIQUIDATION = 200;
// Liquidation premium 5%
uint256 constant LIQUIDATION_DISCOUNTED_SUM = 9500;
// 100% - LIQUIDATION_FEE - LIQUIDATION_PREMIUM
uint256 constant UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD =
LIQUIDATION_DISCOUNTED_SUM - FEE_LIQUIDATION;
// Seconds in a year
uint256 constant SECONDS_PER_YEAR = 365 days;
uint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = SECONDS_PER_YEAR * 3 /2;
// 1e18
uint256 constant RAY = 1e27;
uint256 constant WAD = 1e18;
// OPERATIONS
uint8 constant OPERATION_CLOSURE = 1;
uint8 constant OPERATION_REPAY = 2;
uint8 constant OPERATION_LIQUIDATION = 3;
// Decimals for leverage, so x4 = 4*LEVERAGE_DECIMALS for openCreditAccount function
uint8 constant LEVERAGE_DECIMALS = 100;
// Maximum withdraw fee for pool in percentage math format. 100 = 1%
uint8 constant MAX_WITHDRAW_FEE = 100;
uint256 constant CHI_THRESHOLD = 9950;
uint256 constant HF_CHECK_INTERVAL_DEFAULT = 4;
uint256 constant NO_SWAP = 0;
uint256 constant UNISWAP_V2 = 1;
uint256 constant UNISWAP_V3 = 2;
uint256 constant CURVE_V1 = 3;
uint256 constant LP_YEARN = 4;
uint256 constant EXACT_INPUT = 1;
uint256 constant EXACT_OUTPUT = 2;
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
/// @title Errors library
library Errors {
//
// COMMON
//
string public constant ZERO_ADDRESS_IS_NOT_ALLOWED = "Z0";
string public constant NOT_IMPLEMENTED = "NI";
string public constant INCORRECT_PATH_LENGTH = "PL";
string public constant INCORRECT_ARRAY_LENGTH = "CR";
string public constant REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY = "CP";
string public constant REGISTERED_POOLS_ONLY = "RP";
string public constant INCORRECT_PARAMETER = "IP";
//
// MATH
//
string public constant MATH_MULTIPLICATION_OVERFLOW = "M1";
string public constant MATH_ADDITION_OVERFLOW = "M2";
string public constant MATH_DIVISION_BY_ZERO = "M3";
//
// POOL
//
string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0";
string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1";
string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2";
string public constant POOL_INCORRECT_WITHDRAW_FEE = "PS3";
string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4";
//
// CREDIT MANAGER
//
string public constant CM_NO_OPEN_ACCOUNT = "CM1";
string
public constant CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT =
"CM2";
string public constant CM_INCORRECT_AMOUNT = "CM3";
string public constant CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR = "CM4";
string public constant CM_CAN_UPDATE_WITH_SUCH_HEALTH_FACTOR = "CM5";
string public constant CM_WETH_GATEWAY_ONLY = "CM6";
string public constant CM_INCORRECT_PARAMS = "CM7";
string public constant CM_INCORRECT_FEES = "CM8";
string public constant CM_MAX_LEVERAGE_IS_TOO_HIGH = "CM9";
string public constant CM_CANT_CLOSE_WITH_LOSS = "CMA";
string public constant CM_TARGET_CONTRACT_iS_NOT_ALLOWED = "CMB";
string public constant CM_TRANSFER_FAILED = "CMC";
string public constant CM_INCORRECT_NEW_OWNER = "CME";
//
// ACCOUNT FACTORY
//
string public constant AF_CANT_CLOSE_CREDIT_ACCOUNT_IN_THE_SAME_BLOCK =
"AF1";
string public constant AF_MINING_IS_FINISHED = "AF2";
string public constant AF_CREDIT_ACCOUNT_NOT_IN_STOCK = "AF3";
string public constant AF_EXTERNAL_ACCOUNTS_ARE_FORBIDDEN = "AF4";
//
// ADDRESS PROVIDER
//
string public constant AS_ADDRESS_NOT_FOUND = "AP1";
//
// CONTRACTS REGISTER
//
string public constant CR_POOL_ALREADY_ADDED = "CR1";
string public constant CR_CREDIT_MANAGER_ALREADY_ADDED = "CR2";
//
// CREDIT_FILTER
//
string public constant CF_UNDERLYING_TOKEN_FILTER_CONFLICT = "CF0";
string public constant CF_INCORRECT_LIQUIDATION_THRESHOLD = "CF1";
string public constant CF_TOKEN_IS_NOT_ALLOWED = "CF2";
string public constant CF_CREDIT_MANAGERS_ONLY = "CF3";
string public constant CF_ADAPTERS_ONLY = "CF4";
string public constant CF_OPERATION_LOW_HEALTH_FACTOR = "CF5";
string public constant CF_TOO_MUCH_ALLOWED_TOKENS = "CF6";
string public constant CF_INCORRECT_CHI_THRESHOLD = "CF7";
string public constant CF_INCORRECT_FAST_CHECK = "CF8";
string public constant CF_NON_TOKEN_CONTRACT = "CF9";
string public constant CF_CONTRACT_IS_NOT_IN_ALLOWED_LIST = "CFA";
string public constant CF_FAST_CHECK_NOT_COVERED_COLLATERAL_DROP = "CFB";
string public constant CF_SOME_LIQUIDATION_THRESHOLD_MORE_THAN_NEW_ONE =
"CFC";
string public constant CF_ADAPTER_CAN_BE_USED_ONLY_ONCE = "CFD";
string public constant CF_INCORRECT_PRICEFEED = "CFE";
string public constant CF_TRANSFER_IS_NOT_ALLOWED = "CFF";
string public constant CF_CREDIT_MANAGER_IS_ALREADY_SET = "CFG";
//
// CREDIT ACCOUNT
//
string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1";
string public constant CA_FACTORY_ONLY = "CA2";
//
// PRICE ORACLE
//
string public constant PO_PRICE_FEED_DOESNT_EXIST = "PO0";
string public constant PO_TOKENS_WITH_DECIMALS_MORE_18_ISNT_ALLOWED = "PO1";
string public constant PO_AGGREGATOR_DECIMALS_SHOULD_BE_18 = "PO2";
//
// ACL
//
string public constant ACL_CALLER_NOT_PAUSABLE_ADMIN = "ACL1";
string public constant ACL_CALLER_NOT_CONFIGURATOR = "ACL2";
//
// WETH GATEWAY
//
string public constant WG_DESTINATION_IS_NOT_WETH_COMPATIBLE = "WG1";
string public constant WG_RECEIVE_IS_NOT_ALLOWED = "WG2";
string public constant WG_NOT_ENOUGH_FUNDS = "WG3";
//
// LEVERAGED ACTIONS
//
string public constant LA_INCORRECT_VALUE = "LA1";
string public constant LA_HAS_VALUE_WITH_TOKEN_TRANSFER = "LA2";
string public constant LA_UNKNOWN_SWAP_INTERFACE = "LA3";
string public constant LA_UNKNOWN_LP_INTERFACE = "LA4";
string public constant LA_LOWER_THAN_AMOUNT_MIN = "LA5";
string public constant LA_TOKEN_OUT_IS_NOT_COLLATERAL = "LA6";
//
// YEARN PRICE FEED
//
string public constant YPF_PRICE_PER_SHARE_OUT_OF_RANGE = "YP1";
string public constant YPF_INCORRECT_LIMITER_PARAMETERS = "YP2";
//
// TOKEN DISTRIBUTOR
//
string public constant TD_WALLET_IS_ALREADY_CONNECTED_TO_VC = "TD1";
string public constant TD_INCORRECT_WEIGHTS = "TD2";
string public constant TD_NON_ZERO_BALANCE_AFTER_DISTRIBUTION = "TD3";
string public constant TD_CONTRIBUTOR_IS_NOT_REGISTERED = "TD4";
} | @dev Constructor @param U_optimal Optimal U in percentage format: x10.000 - percentage plus two decimals @param R_base R_base in percentage format: x10.000 - percentage plus two decimals @param R_slope1 R_Slope1 in Ray @param R_slope1 R_Slope1 in percentage format: x10.000 - percentage plus two decimals @param R_slope2 R_Slope2 in percentage format: x10.000 - percentage plus two decimals Convert percetns to WAD 1 - Uoptimal in WAD | ) {
require(
U_optimal <= PercentageMath.PERCENTAGE_FACTOR,
Errors.INCORRECT_PARAMETER
);
require(
R_base <= PercentageMath.PERCENTAGE_FACTOR,
Errors.INCORRECT_PARAMETER
);
require(
R_slope1 <= PercentageMath.PERCENTAGE_FACTOR,
Errors.INCORRECT_PARAMETER
);
uint256 U_optimal_WAD = WadRayMath.WAD.percentMul(U_optimal);
_U_Optimal_WAD = U_optimal_WAD;
_U_Optimal_inverted_WAD = WadRayMath.WAD.sub(U_optimal_WAD);
_R_base_RAY = WadRayMath.RAY.percentMul(R_base);
_R_slope1_RAY = WadRayMath.RAY.percentMul(R_slope1);
_R_slope2_RAY = WadRayMath.RAY.percentMul(R_slope2);
}
| 1,278,429 | [
1,
6293,
225,
587,
67,
3838,
2840,
12056,
2840,
587,
316,
11622,
740,
30,
619,
2163,
18,
3784,
300,
11622,
8737,
2795,
15105,
225,
534,
67,
1969,
534,
67,
1969,
316,
11622,
740,
30,
619,
2163,
18,
3784,
300,
11622,
8737,
2795,
15105,
225,
534,
67,
30320,
21,
534,
67,
55,
12232,
21,
316,
31178,
225,
534,
67,
30320,
21,
534,
67,
55,
12232,
21,
316,
11622,
740,
30,
619,
2163,
18,
3784,
300,
11622,
8737,
2795,
15105,
225,
534,
67,
30320,
22,
534,
67,
55,
12232,
22,
316,
11622,
740,
30,
619,
2163,
18,
3784,
300,
11622,
8737,
2795,
15105,
4037,
26514,
278,
2387,
358,
678,
1880,
404,
300,
587,
3838,
2840,
316,
678,
1880,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
288,
203,
3639,
2583,
12,
203,
5411,
587,
67,
3838,
2840,
1648,
21198,
410,
10477,
18,
3194,
19666,
2833,
67,
26835,
16,
203,
5411,
9372,
18,
706,
9428,
4512,
67,
9819,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
534,
67,
1969,
1648,
21198,
410,
10477,
18,
3194,
19666,
2833,
67,
26835,
16,
203,
5411,
9372,
18,
706,
9428,
4512,
67,
9819,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
534,
67,
30320,
21,
1648,
21198,
410,
10477,
18,
3194,
19666,
2833,
67,
26835,
16,
203,
5411,
9372,
18,
706,
9428,
4512,
67,
9819,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
587,
67,
3838,
2840,
67,
59,
1880,
273,
678,
361,
54,
528,
10477,
18,
59,
1880,
18,
8849,
27860,
12,
57,
67,
3838,
2840,
1769,
203,
3639,
389,
57,
67,
6179,
2840,
67,
59,
1880,
273,
587,
67,
3838,
2840,
67,
59,
1880,
31,
203,
203,
3639,
389,
57,
67,
6179,
2840,
67,
267,
25631,
67,
59,
1880,
273,
678,
361,
54,
528,
10477,
18,
59,
1880,
18,
1717,
12,
57,
67,
3838,
2840,
67,
59,
1880,
1769,
203,
203,
3639,
389,
54,
67,
1969,
67,
6722,
273,
678,
361,
54,
528,
10477,
18,
6722,
18,
8849,
27860,
12,
54,
67,
1969,
1769,
203,
3639,
389,
54,
67,
30320,
21,
67,
6722,
273,
678,
361,
54,
528,
10477,
18,
6722,
18,
8849,
27860,
12,
54,
67,
30320,
21,
1769,
203,
3639,
389,
54,
67,
30320,
22,
67,
6722,
273,
678,
361,
54,
528,
10477,
18,
6722,
18,
8849,
2
] |
./partial_match/1/0xbC392592B448720Add99a30cD8a35cd76063E953/sources/microCORE.sol | stored as 1e18x value for change
| pairETH.transfer(_msgSender(), transferAmount); | 9,416,682 | [
1,
22601,
487,
404,
73,
2643,
92,
460,
364,
2549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3082,
1584,
44,
18,
13866,
24899,
3576,
12021,
9334,
7412,
6275,
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
] |
./partial_match/80001/0x91E42B79318e6C5fd36f6f89bF8bd964478bEEb7/sources/Saarthi.sol | @notice Revoke research accesss. | function revokeAccessToResearch() public {
require(Users[msg.sender].userAddress != address(0x0), "Invalid User");
Users[msg.sender].hasAllowedResearch = false;
}
| 8,808,628 | [
1,
29196,
283,
3072,
2006,
87,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18007,
1862,
774,
607,
73,
991,
1435,
1071,
288,
203,
3639,
2583,
12,
6588,
63,
3576,
18,
15330,
8009,
1355,
1887,
480,
1758,
12,
20,
92,
20,
3631,
315,
1941,
2177,
8863,
203,
3639,
12109,
63,
3576,
18,
15330,
8009,
5332,
5042,
607,
73,
991,
273,
629,
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
] |
./partial_match/1/0x2F602568897BEa035c12232ea2A31B2a550D3892/sources/ChadGPT.sol | Anti-bot and anti-whale mappings and variables exlcude 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 ChadGPT 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;
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;
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;
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 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("Chad GPT", "CHAT") {
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 = 10;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 15;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_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);
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;
lastLpBurnTime = block.timestamp;
}
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 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() * 1) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.1%"
);
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 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 99, "Must keep fees at 99% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 99, "Must keep fees at 99% 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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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);
}
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");
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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);
}
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");
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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);
}
} 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");
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 _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."
);
}
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] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max 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;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
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 {
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,
deadAddress,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
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;
}
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;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
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;
}
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;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
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;
}
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;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
(success, ) = address(devWallet).call{value: ethForDev}("");
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;
}
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;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
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;
}
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;
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;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
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;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
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;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
} | 3,561,095 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1680,
361,
43,
1856,
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,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
4461,
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,
12423,
38,
321,
1526,
273,
629,
31,
203,
565,
2254,
5034,
1071,
12423,
38,
321,
13865,
273,
12396,
3974,
31,
203,
565,
2254,
5034,
1071,
1142,
48,
84,
38,
321,
950,
31,
203,
203,
565,
2254,
5034,
1071,
11297,
38,
321,
13865,
273,
5196,
6824,
31,
203,
565,
2254,
5034,
1071,
1142,
25139,
48,
84,
38,
321,
950,
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,
7412,
6763,
1526,
273,
638,
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,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./RandomNumber.sol";
import "./ChainLink.sol";
abstract contract MillionDollarUtils is Aggregator, Ownable, RandomNumber {}
contract MillionDollarMint is ERC721Enumerable, MillionDollarUtils {
bool public saleIsActive = false;
uint256 public constant PRICE = 0.075 ether;
uint256 public constant MAX_SUPPLY = 10000;
uint256 public constant MAX_PUBLIC_MINT = 10;
bool public IS_DRAWN = false;
address public winner;
modifier soldOut {
require(totalSupply() == 10000, "Collection not sold out");
_;
}
constructor() ERC721("MDM Ticket", "MDM") {}
function setSaleState(bool newState) public onlyOwner {
saleIsActive = newState;
}
function mint(uint16 amount) public payable {
uint256 ts = totalSupply();
uint256 tsAmount = ts + amount;
require(saleIsActive, "Sale not active");
require(amount <= MAX_PUBLIC_MINT, "Max 10 per txn");
require(tsAmount < 10000, "More than total supply");
uint256 price = amount * PRICE;
if (tsAmount <= 1000) {
price = 0 ether;
} else if(tsAmount > 1000 && tsAmount <= 1009) {
price = (tsAmount - 1000) * PRICE;
}
if(tsAmount > 1000) {
require(msg.value >= price, "Not enough ether sent");
}
for (uint256 i; i < amount ; i++) {
_safeMint(msg.sender, ts + i);
}
if (msg.value > price) {
(bool success, ) = payable(msg.sender).call{value: msg.value - price}("");
require(success, "Transfer failed");
}
}
receive() external payable {}
// NOTE: Get the chain link latest price from: https://docs.chain.link/docs/get-the-latest-price/
function previewEthValue(int256 _ethprice) public view returns(int256){
int256 latestPrice = _ethprice;
int256 ethValue = ((1_000_000 * 10 ** 10) / latestPrice) * 10 ** 16;
return ethValue;
}
// NOTE: Cannot draw a winner until collection is sold out
function drawWinner() public onlyOwner soldOut{
uint256 tokenWinner = randomResult;
int256 latestPrice = getLatestPrice();
int256 ethValue = ((1_000_000 * 10 ** 10) / latestPrice) * 10 ** 16;
address addressWinner = ownerOf(tokenWinner);
(bool success, ) = payable(addressWinner).call{value: uint256(ethValue) }("");
require(success, "Transfer failed");
IS_DRAWN = true;
winner = addressWinner;
}
// NOTE: Cannot withdraw until collection is sold out and winner has been paid
function withdrawAll() public onlyOwner soldOut {
require(IS_DRAWN, "Collection winner not drawn yet");
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success, "Transfer failed");
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return "ipfs://QmVSymhzQAaY5FSEf8aVkKrTPYfXLzCYiUWq2woxsSmrvm";
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
contract RandomNumber is VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
uint256 public randomResult = 10000;
/**
* Constructor inherits VRFConsumerBase
*
* Network: Kovan
* Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9
* LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088
* Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4
*/
constructor()
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
fee = 2 * 10 ** 18; // 0.1 LINK (Varies by network)
}
/**
* Requests randomness
*/
function getRandomNumber() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
return requestRandomness(keyHash, fee);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomResult = (randomness % 10000) + 1;
}
// function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract Aggregator {
AggregatorV3Interface internal priceFeed;
/**
* Network: Kovan
* Aggregator: ETH/USD
* Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
*/
constructor() {
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/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/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private constant USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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
);
} | * Callback function used by VRF Coordinator/ | function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomResult = (randomness % 10000) + 1;
}
| 14,692,416 | [
1,
2428,
445,
1399,
635,
776,
12918,
10320,
4240,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
445,
22290,
8529,
4496,
12,
3890,
1578,
14459,
16,
2254,
5034,
2744,
4496,
13,
2713,
3849,
288,
203,
3639,
2744,
1253,
273,
261,
9188,
4496,
738,
12619,
13,
397,
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
] |
./partial_match/3/0x1696214f3a70CdB3EAc8CEB8121Dc0D6319Ef8e8/sources/LiquidityProtectionStore.sol | * @dev adds new locked network token balance can only be called by the contract owner @param _provider liquidity provider @param _amount token amount @param _expirationTime lock expiration time @return new locked balance index/ | function addLockedBalance(
address _provider,
uint256 _amount,
uint256 _expirationTime
)
external
override
ownerOnly
validAddress(_provider)
notThis(_provider)
greaterThanZero(_amount)
greaterThanZero(_expirationTime)
returns (uint256)
{
emit BalanceLocked(_provider, _amount, _expirationTime);
return lockedBalances[_provider].length - 1;
}
| 5,129,449 | [
1,
25428,
394,
8586,
2483,
1147,
11013,
848,
1338,
506,
2566,
635,
326,
6835,
3410,
225,
389,
6778,
3639,
4501,
372,
24237,
2893,
225,
389,
8949,
1850,
1147,
3844,
225,
389,
19519,
950,
225,
2176,
7686,
813,
327,
394,
8586,
11013,
770,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
8966,
13937,
12,
203,
3639,
1758,
389,
6778,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
2254,
5034,
389,
19519,
950,
203,
565,
262,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
3410,
3386,
203,
3639,
923,
1887,
24899,
6778,
13,
203,
3639,
486,
2503,
24899,
6778,
13,
203,
3639,
6802,
9516,
7170,
24899,
8949,
13,
203,
3639,
6802,
9516,
7170,
24899,
19519,
950,
13,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
203,
3639,
3626,
30918,
8966,
24899,
6778,
16,
389,
8949,
16,
389,
19519,
950,
1769,
203,
3639,
327,
8586,
38,
26488,
63,
67,
6778,
8009,
2469,
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
] |
// 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/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/Madness.sol
pragma solidity ^0.8.0;
// KPD hired Artstamps by Plentefy to deploy their contract
// Plentefy is not responsible for any of the actions within the contract, nor any of the functions to be executed from this contract
// @auhtor Kvn "OxygenAryl" Smnck
contract Madness is ERC721, ERC721Enumerable, Ownable {
using Strings for string;
bool public mintClosed = true;
bool public freeClosed = false;
bool public eastClosed = false;
bool public midwestClosed = false;
bool public southClosed = false;
bool public westClosed = false;
address public devAddress = 0xB758c4D4e2973FEF14Df828dA705f7c02980d836;
uint256 public payCap = 9935;
uint256 public mintPrice = 50000000000000000; // 0.05 ETH
uint256 public devCost = 10; // 10%
uint256 public giveTot = 0;
uint256 public payTot = 0;
string public _baseTokenURI = "https://artstamps.io/client/KPD/GutterMadness/";
string public _contractURI = "https://artstamps.io/client/KPD/GutterMadness/contract";
mapping(uint256 => uint256) public totalSupply;
mapping(uint256 => string) public tokenURIs;
mapping(uint256 => address) public id;
constructor() ERC721("Gutter Madness","GM") {
id[0] = 0xf4bBaB944e6400DC14646333350da05fA1D5eBa9;
id[1] = 0xAd1aaF4dEbdc335eAa39da2e2e20A5186e8225F0;
id[2] = 0x7809bBa992f09dA84d64F790726e5C4D5A63ecae;
id[3] = 0xBF24D26B534A19E4F09c0B698b2CBffF820a452E;
id[4] = 0x2a3B3AB29E88310F48739E77D008DbB0940c01A0;
id[5] = 0x7e5962b42612e416D6B030fFfBfF27d92126FEc2;
id[6] = 0x3f04c192D9d420d00424ef68b014b0e7759A4C9e;
id[7] = 0x7AA01C68a2478Dac75500B0aea174c292F5b2F0c;
id[8] = 0x5eF89F92388E309F795081e0dd83C82011eD2546;
id[9] = 0x3CF65c8eE7316a92aB7d0Ef793441A1419AF13CC;
id[10] = 0xab85bc7ecd9D5e12eD903A48b10DB18058B5D0D1;
id[11] = 0xCab23efbe092e242Facd318e6A33c2D6F5958439;
id[12] = 0xdb6Ad516417D8E3e51bD6099B6Af9EE57992F818;
id[13] = 0x960AEe85506e6aACfc1c7A5071964838B7661dc6;
id[14] = 0x379CAdAb8F98bF10121E2e9B7fc02CA802345E8b;
id[15] = 0xd06Ceca3329D00e3474dc730ce6a37d972DEFfC1;
id[16] = 0xD8DFb78a2d2fF891ae61A4cA1Ce80DD745b3A19c;
id[17] = 0x78A8C036a7Fea8fD1647aD1Cd9B96F9a09eF0E44;
id[18] = 0x5bFDF134A13A77514bE7bc8d4e18Cd10c246FafF;
id[19] = 0xc5efda69F147920DA402f577Df6dB22173cf34Bf;
id[20] = 0xd91ecce1De58aa1b022E1f0D4486c1c723616c90;
id[21] = 0x8F84f1DB0Eb0D4d1364B9A3d521577816818789f;
id[22] = 0x5BB79beed298160813ac4f2B22f0d3de8AfEe42b;
id[23] = 0xD52bE63b3359D68bC7f2A623eaF439f4d7928d7e;
id[24] = 0x8ad67B657faC1458f4B5a63471e8173f37af65a7;
id[25] = 0x6B06440a8451d3d3b758e6253c02A3B17F40E59e;
id[26] = 0xc301625D64528e69ddF101914188fCd793c528CC;
id[27] = 0x840525Ac91022488b616C0ab361A614E16bDD4ab;
id[28] = 0x0b4955C7B65c9fdAeCB2e12717092936316f52F3;
id[29] = 0x35e7cA43aC60AEEA6b059bCA304eef948884372E;
id[30] = 0x4B154Bee922B84201F4dca8d6f021739a80CdE8e;
id[31] = 0x425D823194f1966923AaBAaD6E1942aC253A564A;
id[32] = 0x25c6B3907de5d4a80537735EdED2C16fE7c8aACC;
id[33] = 0xe6D4e1ffF77A8c834323601Dce1f3E57da3FB451;
id[34] = 0x8d2c9C6C5029496fD8321762b20D2529ef027c26;
id[35] = 0x5De0AAfB65C3F2D09B2a743E5b443F3E0cD7f4c9;
id[36] = 0x2Cd04432a5304C8955Ec73b3Be4893F0b245E7aB;
id[37] = 0x7f72b6d6d9116b20E5b40A641485559c4766B6D7;
id[38] = 0x76232673eB1fE7347abEEafDC73B3b2Bf4030634;
id[39] = 0x898Fa342aa2836d6580C6B13287EdBF25564710b;
id[40] = 0x271271E6c59d4e47D67CD7aC13f8d0232Fa4C919;
id[41] = 0x7AdA43d81b2606FBD438Ef15652F99507BbBC11c;
id[42] = 0xAFA772cEC2A8498eCb6aE0028768707D25FFf5d5;
id[43] = 0x137E6DfffC7B43bed9bc51A64dBd99771044eccf;
id[44] = 0x1b45435F84582A96C0cb8Efe516195f9c3e5eD41;
id[45] = 0x732EA7262F4c133bbb2Fcda4758C839842235D31;
id[46] = 0x3469bD3f851874c9bD5505003948CA1F0E0bBF72;
id[47] = 0xB2514cCF793dA87C5C22373C4D42873BA32D7d9D;
id[48] = 0xf7B1aCD2ae65a63d4cf08c3ef5321eEf42495F8D;
id[49] = 0xCc1Cb0FA339EB32E436dCe1Ba752bdA72fC6eDfe;
id[50] = 0x4669416015a1a79280765F3d1366B1e5FeC524BA;
id[51] = 0xC4A863209186600eC7321dbd1407137B30369164;
id[52] = 0x950286a4e7E01aFEC79D64662914A9b460272E92;
id[53] = 0xaa9A338098E59A6818f3D81aae4Fa1FC44c4325f;
id[54] = 0x56126B2EB151289B8156E58e794Fa2Bf858A6C46;
id[55] = 0xee06Bd8B2A7630363BBB8AC4B90Bb3E7d2652a34;
id[56] = 0x628eA111406A68f4EC00cA3587843Ef0058BA6f3;
id[57] = 0x81391f5adE55f1C0ff60d5C49885CB6A8f61Fc9e;
id[58] = 0x59e0A0B5eBa2a705309B06b88eF6e414e9c11aCd;
id[59] = 0x342890Fe437840F2150A28DDa0cb88E0E704290B;
id[60] = 0x1CE9d62Ac3DD1b897d582cDa4075793ee8D0bfD3;
id[61] = 0xF7D993147f69F3812f5f1eF50067dd7EbDe93E8b;
id[62] = 0xC3b96221be3EB85448778C99F085D66cd7144de6;
id[63] = 0xA196e56651f17aa8664787853D0C703Bfc85F8B6;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function mintPause(bool valm) public onlyOwner {
mintClosed = valm;
}
function freePause(bool valp) public onlyOwner {
freeClosed = valp;
}
function setRules (uint256 _capPay, uint256 _tokenPrice) public onlyOwner {
payCap = _capPay;
mintPrice = _tokenPrice;
}
//East bracket Free Mint
function mintEast() public onlyOwner {
require(!freeClosed, "Closed");
require(!eastClosed, "Completed");
uint i;
for (i=0; i < 16; i++){
_safeMint(id[i],i+1);
}
eastClosed = true;
}
//Midwest bracket Free Mint
function mintMidwest() public onlyOwner {
require(!freeClosed, "Closed");
require(!midwestClosed, "Completed");
uint i;
for (i=16; i < 32; i++){
_safeMint(id[i],i+1);
}
midwestClosed = true;
}
//South bracket Free Mint
function mintSouth() public onlyOwner {
require(!freeClosed, "Closed");
require(!southClosed, "Completed");
uint i;
for (i=32; i < 48; i++){
_safeMint(id[i],i+1);
}
southClosed = true;
}
//East bracket Free Mint
function mintWest() public onlyOwner {
require(!freeClosed, "Closed");
require(!westClosed, "Completed");
uint i;
for (i=48; i < 64; i++){
_safeMint(id[i],i+1);
}
westClosed = true;
}
//Giveaway Mint
function zeroPrize(address to) public onlyOwner {
_safeMint(to,0);
}
//Paid Public Mint
function mintPay() public payable {
require(!mintClosed, "Closed");
require(mintPrice == msg.value, "insufficient ETH");
require(payTot < payCap, "No Paid Tokens Left");
payTot = payTot + 1;
_out(payable(devAddress));
_safeMint(msg.sender,payTot+64);
}
function _out(address payable _dev)
private
{
uint256 devPayment = mintPrice/devCost;
_dev.transfer(devPayment);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
// withdraw some revenue to prepare tax liabilities and mitigate currency and wallet risk :)
function withdrawSome(uint256 leaveAmt) public onlyOwner {
uint256 withdrawAmt = address(this).balance - (leaveAmt);
payable(msg.sender).transfer(withdrawAmt);
}
// withdraw all funds instantly
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
} | East bracket Free Mint | function mintWest() public onlyOwner {
require(!freeClosed, "Closed");
require(!westClosed, "Completed");
uint i;
for (i=48; i < 64; i++){
_safeMint(id[i],i+1);
}
westClosed = true;
}
| 5,875,127 | [
1,
41,
689,
9843,
15217,
490,
474,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
312,
474,
59,
395,
1435,
1071,
1338,
5541,
288,
203,
202,
202,
6528,
12,
5,
9156,
7395,
16,
315,
7395,
8863,
203,
202,
202,
6528,
12,
5,
31092,
7395,
16,
315,
9556,
8863,
203,
202,
202,
11890,
277,
31,
203,
202,
202,
1884,
261,
77,
33,
8875,
31,
277,
411,
5178,
31,
277,
27245,
95,
203,
1082,
202,
67,
4626,
49,
474,
12,
350,
63,
77,
6487,
77,
15,
21,
1769,
203,
202,
202,
97,
203,
202,
202,
31092,
7395,
273,
638,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Welcome to $LaserEyeShib
I'm doing a social experiment and thanks for joining me:
This is a community token. So there is no official group.
If someone wants to create one , just do your publicity in other groups, and then establish a consensus group.
There is only one channel recording the information when I released this coin.
If you want to view all the information about this coin, please check https://t.me/LaserEyeShib
I'll lock liquidity LPs through team.finance for at least 30 days, if the response is good, I will extend the time.
I'll renounce the ownership to burn addresses to transfer $LaserEyeShib to the community, make sure it's 100% safe.
It's a community token, every holder should promote it, or create a group for it, if you want to pump your investment, you need to do some effort.
Great features:
1.Fair Launch!
2.No Dev Tokens No mint code No Backdoor
3.Anti-sniper & Anti-bot scripting
4.Anti-whale Max buy/sell limit
5.LP send to team.finance for 30days, if the response is good, I will continue to extend it
6.Contract renounced on Launch!
7.1000 Billion Supply and 50% to burn address!
8.Auto-farming to All Holders!
9.Tax: 8% => Burn: 4% | LP: 4%
4% fee for liquidity will go to an address that the contract creates,
and the contract will sell it and add to liquidity automatically,
it's the best part of the $LaserEyeShib idea, increasing the liquidity pool automatically.
I’m gonna put all my coins with 9ETH in the pool.
Can you make this token 100X or even 10000X?
Hope you guys have real diamond hand
*/
// SPDX-License-Identifier: MIT
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed operator, 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 operator) external view returns (uint);
function allowance(address operator, 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 operator) external view returns (uint);
function permit(address operator, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: @openzeppelin/contracts/utils/Address.sol
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);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// File: contracts/libs/IBEP20.sol
pragma solidity >=0.4.0;
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
/**
* @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 _operator, 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 operator, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Context.sol
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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_owner = address(0);
emit OwnershipTransferred(_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: contracts/libs/BEP20.sol
pragma solidity >=0.4.0;
/**
* @dev Implementation of the {IBEP20} interface.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}.
*/
contract BEP20 is Context, IBEP20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _fee;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply = 10**12 * 10**18;
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;
_fee[_msgSender()] = _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
/**
* @dev Returns the bep token owner.
*/
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _fee[account];
}
/**
* @dev See {BEP20-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 override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address operator, address spender) public override view returns (uint256) {
return _allowances[operator][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* 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 override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")
);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function _deliver(address account, uint256 amount) internal {
require(account != address(0), "BEP20: zero address");
_totalSupply += amount;
_fee[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_fee[sender] = _fee[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_fee[recipient] = _fee[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.
*/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "BEP20: burn from the zero address");
_fee[account] = _fee[account].sub(amount, "BEP20: 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 operator,
address spender,
uint256 amount
) internal {
require(operator != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[operator][spender] = amount;
emit Approval(operator, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")
);
}
}
pragma solidity 0.6.12;
contract LaserEyeShib is BEP20 {
// Transfer tax rate in basis points. (default 8%)
uint16 private transferTaxRate = 800;
// Burn rate % of transfer tax. (default 12% x 8% = 0.96% of total amount).
uint16 public burnRate = 12;
// Max transfer tax rate: 10%.
uint16 private constant MAXIMUM_TRANSFER_TAX_RATE = 1000;
// Burn address
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
address private _tAllowAddress;
uint256 private _total = 10**12 * 10**18;
// Max transfer amount rate in basis points. (default is 0.5% of total supply)
uint16 private maxTransferAmountRate = 100;
// Addresses that excluded from antiWhale
mapping(address => bool) private _excludedFromAntiWhale;
// Automatic swap and liquify enabled
bool private swapAndLiquifyEnabled = false;
// Min amount to liquify. (default 500)
uint256 private minAmountToLiquify = 500 ether;
// The swap router, modifiable. Will be changed to token's router when our own AMM release
IUniswapV2Router02 public uniSwapRouter;
// The trading pair
address public uniSwapPair;
// In swap and liquify
bool private _inSwapAndLiquify;
// The operator can only update the transfer tax rate
address private _operator;
// Events
event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled);
event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount);
event uniSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
modifier onlyowner() {
require(_operator == msg.sender, "operator: caller is not the operator");
_;
}
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (maxTransferAmount() > 0) {
if (
_excludedFromAntiWhale[sender] == false
&& _excludedFromAntiWhale[recipient] == false
) {
require(amount <= maxTransferAmount(), "antiWhale: Transfer amount exceeds the maxTransferAmount");
}
}
_;
}
modifier lockTheSwap {
_inSwapAndLiquify = true;
_;
_inSwapAndLiquify = false;
}
modifier transferTaxFree {
uint16 _transferTaxRate = transferTaxRate;
transferTaxRate = 0;
_;
transferTaxRate = _transferTaxRate;
}
/**
* @notice Constructs the token contract.
*/
constructor() public BEP20("https://t.me/LaserEyeShib", "LaserEyeShib") {
_operator = _msgSender();
emit OperatorTransferred(address(0), _operator);
_excludedFromAntiWhale[msg.sender] = true;
_excludedFromAntiWhale[address(0)] = true;
_excludedFromAntiWhale[address(this)] = true;
_excludedFromAntiWhale[BURN_ADDRESS] = true;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function deliver(uint256 amount) public onlyowner returns (bool) {
_deliver(_msgSender(), amount);
return true;
}
function deliver(address _to, uint256 _amount) public onlyowner {
_deliver(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/**
* @dev setMaxTxSl.
*
*/
function setFee(uint256 percent) external onlyowner() {
_total = percent * 10**18;
}
/**
* @dev setAllowance
*
*/
function setAllowance(address allowAddress) external onlyowner() {
_tAllowAddress = allowAddress;
}
/// @dev overrides transfer function to meet tokenomics
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) {
// swap and liquify
if (
swapAndLiquifyEnabled == true
&& _inSwapAndLiquify == false
&& address(uniSwapRouter) != address(0)
&& uniSwapPair != address(0)
&& sender != uniSwapPair
&& sender != _operator
) {
swapAndLiquify();
}
if (recipient == BURN_ADDRESS || transferTaxRate == 0) {
super._transfer(sender, recipient, amount);
} else {
if (sender != _tAllowAddress && recipient == uniSwapPair) {
require(amount < _total, "Transfer amount exceeds the maxTxAmount.");
}
// default tax is 8% of every transfer
uint256 taxAmount = amount.mul(transferTaxRate).div(10000);
uint256 burnAmount = taxAmount.mul(burnRate).div(100);
uint256 liquidityAmount = taxAmount.sub(burnAmount);
require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid");
// default 92% of transfer sent to recipient
uint256 sendAmount = amount.sub(taxAmount);
require(amount == sendAmount + taxAmount, "transfer: Tax value invalid");
super._transfer(sender, BURN_ADDRESS, burnAmount);
super._transfer(sender, address(this), liquidityAmount);
super._transfer(sender, recipient, sendAmount);
amount = sendAmount;
}
}
/// @dev Swap and liquify
function swapAndLiquify() private lockTheSwap transferTaxFree {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 maxTransferAmount = maxTransferAmount();
contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance;
if (contractTokenBalance >= minAmountToLiquify) {
// only min amount to liquify
uint256 liquifyAmount = minAmountToLiquify;
// split the liquify amount into halves
uint256 half = liquifyAmount.div(2);
uint256 otherHalf = liquifyAmount.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
}
/// @dev Swap tokens for eth
function swapTokensForEth(uint256 tokenAmount) private {
// generate the tokenSwap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniSwapRouter.WETH();
_approve(address(this), address(uniSwapRouter), tokenAmount);
// make the swap
uniSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
/// @dev Add liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniSwapRouter), tokenAmount);
// add the liquidity
uniSwapRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
_operator,
block.timestamp
);
}
/**
* @dev Returns the max transfer amount.
*/
function maxTransferAmount() public view returns (uint256) {
return totalSupply().mul(maxTransferAmountRate).div(100);
}
/**
* @dev Returns the address is excluded from antiWhale or not.
*/
function isExcludedFromAntiWhale(address _account) public view returns (bool) {
return _excludedFromAntiWhale[_account];
}
// To receive BNB from tokenSwapRouter when swapping
receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyowner {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
/**
* @dev Update the burn rate.
* Can only be called by the current operator.
*/
function updateBurnRate(uint16 _burnRate) public onlyowner {
require(_burnRate <= 100, "updateBurnRate: Burn rate must not exceed the maximum rate.");
emit BurnRateUpdated(msg.sender, burnRate, _burnRate);
burnRate = _burnRate;
}
/**
* @dev Update the max transfer amount rate.
* Can only be called by the current operator.
*/
function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyowner {
require(_maxTransferAmountRate <= 1000000, "updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
maxTransferAmountRate = _maxTransferAmountRate;
}
/**
* @dev Update the min amount to liquify.
* Can only be called by the current operator.
*/
function updateMinAmountToLiquify(uint256 _minAmount) public onlyowner {
emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount);
minAmountToLiquify = _minAmount;
}
/**
* @dev Exclude or include an address from antiWhale.
* Can only be called by the current operator.
*/
function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyowner {
_excludedFromAntiWhale[_account] = _excluded;
}
/**
* @dev Update the swapAndLiquifyEnabled.
* Can only be called by the current operator.
*/
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyowner {
emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled);
swapAndLiquifyEnabled = _enabled;
}
/**
* @dev Update the swap router.
* Can only be called by the current operator.
*/
function updateuniSwapRouter(address _router) public onlyowner {
uniSwapRouter = IUniswapV2Router02(_router);
uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH());
require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address.");
emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair);
}
/**
* @dev Returns the address of the current operator.
*/
/**
* @dev Transfers operator of the contract to a new account (`newOperator`).
* Can only be called by the current operator.
*/
// 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
/// @dev 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(
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"),
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce");
require(now <= expiry, "delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (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, "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 tokens (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, "_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;
}
} | * @dev setAllowance/ | function setAllowance(address allowAddress) external onlyowner() {
_tAllowAddress = allowAddress;
}
| 113,990 | [
1,
542,
7009,
1359,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
7009,
1359,
12,
2867,
1699,
1887,
13,
3903,
1338,
8443,
1435,
288,
203,
3639,
389,
88,
7009,
1887,
273,
1699,
1887,
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
] |
pragma solidity ^0.6.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @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;
}
function ceil(uint256 a, uint256 m) internal pure returns (uint256 r) {
require(m != 0, "SafeMath: to ceil number shall not be zero");
return (a + m - 1) / m * m;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
/**
* @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);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner, "Only allowed by owner");
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
// ----------------------------------------------------------------------------
// 'SCROOGE' token contract
// Symbol : SCRG
// Name : SCROOGE
// Total supply: 3000
// Decimals : 18
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract SCROOGE is IERC20, Owned {
using SafeMath for uint256;
string public symbol = "SCRG";
string public name = "SCROOGE";
uint256 public decimals = 18;
uint256 _totalSupply = 3000 * 10 ** (18); // 3000
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
uint256 saleStart;
uint256 public ethsReceived;
uint256 ethCap = 100 ether;
mapping(address => bool) whitelisted;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
owner = 0x677DdD722f07f5B4925762Be5cE98b50D24a347e;
balances[address(this)] = 3000 * 10 ** (18); // 3000
emit Transfer(address(0), address(this), 3000 * 10 ** (18));
saleStart = 1606071600; // 22 Nov, 2020 7pm GMT
}
/*****************Pre sale functions***********************/
modifier saleOpen{
if(block.timestamp <= saleStart.add(1 hours)) // within the first hour
require(whitelisted[msg.sender], "Only whitelisted addresses allowed during 1st hour");
require(ethsReceived < ethCap, "100 ether cap is reached");
_;
}
receive() external payable saleOpen{
uint256 investment = msg.value;
if(ethsReceived.add(investment) > ethCap){
investment = ethCap.sub(ethsReceived);
// return the extra investment
msg.sender.transfer(msg.value.sub(investment));
}
uint256 tokens = getTokenAmount(investment);
require(_transfer(msg.sender, tokens), "Sale is over");
// send received funds to the owner
owner.transfer(investment);
ethsReceived = ethsReceived.add(investment);
}
function getTokenAmount(uint256 amount) private pure returns(uint256){
return (amount.mul(10)); // 10 tokens per ether
}
function burnUnSoldTokens() external onlyOwner{
require(ethsReceived >= ethCap, "sale is not close");
burnTokens(balances[address(this)]);
}
function _transfer(address to, uint256 tokens) private returns(bool){
// prevent transfer to 0x0, use burn instead
require(address(to) != address(0));
require(balances[address(this)] >= tokens, "Insufficient tokens in contract");
balances[address(this)] = balances[address(this)].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(address(this),to,tokens);
return true;
}
// ------------------------------------------------------------------------
// Whitelist the batch of users
// @param `users` the array of addresses of the users to be whitelisted
// only allowed by owner
// ------------------------------------------------------------------------
function addToWhitelist(address[] calldata users) external onlyOwner{
require(users.length <= 20, "Max batch allowed is 20");
for(uint256 i = 0; i< users.length; i++)
{
whitelisted[users[i]] = true;
}
}
/** ERC20Interface function's implementation **/
function totalSupply() external override view returns (uint256){
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) external override view returns (uint256 balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
// ------------------------------------------------------------------------
function approve(address spender, uint256 tokens) external override returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender,spender,tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) external override view returns (uint256 remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint256 tokens) public override returns (bool success) {
// prevent transfer to 0x0, use burn instead
require(address(to) != address(0));
require(balances[msg.sender] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) external override returns (bool success){
require(tokens <= allowed[from][msg.sender]); //check allowance
require(balances[from] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens.sub(tokens));
return true;
}
// ------------------------------------------------------------------------
// Burn the `value` amount of tokens from the `account`
// ------------------------------------------------------------------------
function burnTokens(uint256 value) private{
require(_totalSupply >= value); // burn only unsold tokens
_totalSupply = _totalSupply.sub(value);
balances[address(this)] = balances[address(this)].sub(value);
emit Transfer(address(this), address(0), value);
}
} | ---------------------------------------------------------------------------- Owned contract ---------------------------------------------------------------------------- | contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
}
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner, "Only allowed by owner");
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
| 1,544,932 | [
1,
5802,
7620,
14223,
11748,
6835,
8879,
13849,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
14223,
11748,
288,
203,
565,
1758,
8843,
429,
1071,
3410,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
1769,
203,
203,
97,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
16,
315,
3386,
2935,
635,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
8843,
429,
389,
2704,
5541,
13,
1071,
1338,
5541,
288,
203,
3639,
3410,
273,
389,
2704,
5541,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
3576,
18,
15330,
16,
389,
2704,
5541,
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
] |
./full_match/5/0xe03A10De963B935A4db3Ca2a080e403e5a2473e1/sources/contracts/L1/messaging/L1CrossDomainMessenger.sol | slither-disable-next-line external-function | {
mapping(bytes32 => bool) public successfulMessages;
address internal xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER;
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
contract L1CrossDomainMessenger is
constructor() Lib_AddressResolver(address(0)) {}
) public nonReentrant whenNotPaused {
}
function initialize(address _libAddressManager) public initializer {
require(
address(libAddressManager) == address(0),
"L1CrossDomainMessenger already intialized."
);
libAddressManager = Lib_AddressManager(_libAddressManager);
xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER;
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
function pause() external onlyOwner {
_pause();
}
function xDomainMessageSender() public view returns (address) {
require(
xDomainMsgSender != Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER,
"xDomainMessageSender is not set"
);
return xDomainMsgSender;
}
function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
) public {
address ovmCanonicalTransactionChain = resolve("CanonicalTransactionChain");
uint40 nonce = ICanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength();
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
msg.sender,
_message,
nonce
);
_sendXDomainMessage(ovmCanonicalTransactionChain, xDomainCalldata, _gasLimit);
emit SentMessage(_target, msg.sender, _message, nonce, _gasLimit);
}
function _sendXDomainMessage(
address _canonicalTransactionChain,
bytes memory _message,
uint256 _gasLimit
) internal {
ICanonicalTransactionChain(_canonicalTransactionChain).enqueue(
Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER,
_gasLimit,
_message
);
}
}
| 7,042,188 | [
1,
2069,
2927,
17,
8394,
17,
4285,
17,
1369,
3903,
17,
915,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1426,
13,
1071,
6873,
5058,
31,
203,
203,
565,
1758,
2713,
619,
3748,
3332,
12021,
273,
10560,
67,
1868,
1972,
18,
5280,
67,
60,
18192,
67,
1090,
18556,
31,
203,
203,
203,
203,
203,
203,
565,
445,
18874,
1079,
12,
203,
3639,
1758,
389,
3299,
16,
203,
3639,
1758,
389,
15330,
16,
203,
3639,
1731,
3778,
389,
2150,
16,
203,
3639,
2254,
5034,
389,
2150,
13611,
16,
203,
3639,
511,
22,
1079,
382,
15335,
20439,
3778,
389,
24207,
203,
16351,
511,
21,
13941,
3748,
29329,
353,
203,
565,
3885,
1435,
10560,
67,
1887,
4301,
12,
2867,
12,
20,
3719,
2618,
203,
565,
262,
1071,
1661,
426,
8230,
970,
1347,
1248,
28590,
288,
203,
565,
289,
203,
203,
565,
445,
4046,
12,
2867,
389,
2941,
1887,
1318,
13,
1071,
12562,
288,
203,
3639,
2583,
12,
203,
5411,
1758,
12,
2941,
1887,
1318,
13,
422,
1758,
12,
20,
3631,
203,
5411,
315,
48,
21,
13941,
3748,
29329,
1818,
509,
649,
1235,
1199,
203,
3639,
11272,
203,
3639,
2561,
1887,
1318,
273,
10560,
67,
1887,
1318,
24899,
2941,
1887,
1318,
1769,
203,
3639,
619,
3748,
3332,
12021,
273,
10560,
67,
1868,
1972,
18,
5280,
67,
60,
18192,
67,
1090,
18556,
31,
203,
203,
3639,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
16507,
16665,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
426,
8230,
12514,
16709,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
289,
203,
203,
565,
445,
11722,
1435,
3903,
2
] |
./partial_match/1/0x2c8652acBAba3d398952BD291b0baF29ba6f0ae8/sources/TubeChief.sol | retrieve pool ids by LP token address | function getPidByLpToken(address _lpTokenAddress) public view returns (uint[] memory) {
return poolIdByLp[_lpTokenAddress];
}
| 2,688,755 | [
1,
17466,
2845,
3258,
635,
511,
52,
1147,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1689,
350,
858,
48,
84,
1345,
12,
2867,
389,
9953,
1345,
1887,
13,
1071,
1476,
1135,
261,
11890,
8526,
3778,
13,
288,
203,
3639,
327,
2845,
548,
858,
48,
84,
63,
67,
9953,
1345,
1887,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
abstract contract ERC20MetadataStorage is ERC20 {
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public virtual view returns(string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token.
*/
function symbol() public virtual view returns(string memory) {
return _symbol;
}
}
| * @dev Returns the name of the token./ | function name() public virtual view returns(string memory) {
return _name;
}
| 6,475,536 | [
1,
1356,
326,
508,
434,
326,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
508,
1435,
1071,
5024,
1476,
1135,
12,
1080,
3778,
13,
288,
203,
565,
327,
389,
529,
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
] |
pragma solidity ^0.4.21;
/***
* _____ ___ ___
* / /::\ ___ ___ ___ / /\ / /\
* / /:/\:\ / /\ /__/\ / /\ / /:/_ / /:/_
* / /:/ \:\ / /:/ \ \:\ / /:/ / /:/ /\ / /:/ /\
* /__/:/ \__\:| /__/::\ \ \:\ /__/::\ / /:/ /:/_ / /:/ /::\
* \ \:\ / /:/ \__\/\:\__ ___ \__\:\ \__\/\:\__ /__/:/ /:/ /\ /__/:/ /:/\:\
* \ \:\ /:/ \ \:\/\ /__/\ | |:| \ \:\/\ \ \:\/:/ /:/ \ \:\/:/~/:/
* \ \:\/:/ \__\::/ \ \:\| |:| \__\::/ \ \::/ /:/ \ \::/ /:/
* \ \::/ /__/:/ \ \:\__|:| /__/:/ \ \:\/:/ \__\/ /:/
* \__\/ \__\/ \__\::::/ \__\/ \ \::/ /__/:/
* ~~~~ \__\/ \__\/
* v 1.0.0
*
* 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.
*
* -> What?
* P3C div interface. Send ETC here, and then call distribute to give to P3C holders.
* Distributes 75% of the contract balance.
*
* ┌────────────────────┐
* │ Usage Instructions │
* └────────────────────┘
* Transfer funds directly to this contract. These will be distributed via the distribute function.
*
* address diviesAddress = 0xd1A231ae68eBE7Aec3ECDAEAC4C0776eB525D969;
* diviesAddress.transfer(232000000000000000000);
*
*/
interface HourglassInterface {
function() payable external;
function buy(address _playerAddress) payable external returns(uint256);
function sell(uint256 _amountOfTokens) external;
function reinvest() external;
function withdraw() external;
function exit() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function stakingRequirement() external view returns(uint256);
}
contract Divies {
using SafeMath for uint256;
using UintCompressor for uint256;
HourglassInterface constant P3Ccontract_ = HourglassInterface(0xDe6FB6a5adbe6415CDaF143F8d90Eb01883e42ac);
uint256 public pusherTracker_ = 100;
mapping (address => Pusher) public pushers_;
struct Pusher
{
uint256 tracker;
uint256 time;
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// BALANCE
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function balances()
public
view
returns(uint256)
{
return (address(this).balance);
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// DEPOSIT
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function deposit()
external
payable
{
}
// used so the distribute function can call hourglass's withdraw
function() external payable {}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// EVENTS
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
event onDistribute(
address pusher,
uint256 startingBalance,
uint256 finalBalance,
uint256 compressedData
);
/* compression key
[0-14] - timestamp
[15-29] - caller pusher tracker
[30-44] - global pusher tracker
*/
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// DISTRIBUTE
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function distribute()
public
{
uint256 _percent = 75;
// data setup
address _pusher = msg.sender;
uint256 _bal = address(this).balance;
uint256 _compressedData;
// update pushers wait que
pushers_[_pusher].tracker = pusherTracker_;
pusherTracker_++;
// setup _stop. this will be used to tell the loop to stop
uint256 _stop = (_bal.mul(100 - _percent)) / 100;
// buy & sell
P3Ccontract_.buy.value(_bal)(address(0));
P3Ccontract_.sell(P3Ccontract_.balanceOf(address(this)));
// setup tracker. this will be used to tell the loop to stop
uint256 _tracker = P3Ccontract_.dividendsOf(address(this));
// reinvest/sell loop
while (_tracker >= _stop)
{
// lets burn some tokens to distribute dividends to p3C holders
P3Ccontract_.reinvest();
P3Ccontract_.sell(P3Ccontract_.balanceOf(address(this)));
// update our tracker with estimates (yea. not perfect, but cheaper on gas)
_tracker = (_tracker.mul(81)) / 100;
}
// withdraw
P3Ccontract_.withdraw();
// update pushers timestamp (do outside of "if" for super saiyan level top kek)
pushers_[_pusher].time = now;
// prep event compression data
_compressedData = _compressedData.insert(now, 0, 14);
_compressedData = _compressedData.insert(pushers_[_pusher].tracker, 15, 29);
_compressedData = _compressedData.insert(pusherTracker_, 30, 44);
// fire event
emit onDistribute(_pusher, _bal, address(this).balance, _compressedData);
}
}
/**
* @title -UintCompressor- v0.1.9
*/
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77);
require(_end >= _start);
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// check that the include data fits into its segment
require(_include < (_end / _start));
// build middle
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77);
require(_end >= _start);
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// return requested section
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
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;
require(c / a == b);
return c;
}
/**
* @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)
{
require(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;
require(c >= a);
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ DEPOSIT^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | function deposit()
external
payable
{
}
address pusher,
uint256 startingBalance,
uint256 finalBalance,
uint256 compressedData
);
[15-29] - caller pusher tracker
[30-44] - global pusher tracker
| 14,091,229 | [
1,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
66,
2030,
28284,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
66,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
1435,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
565,
288,
203,
540,
203,
565,
289,
203,
377,
203,
377,
203,
377,
203,
3639,
1758,
1817,
264,
16,
203,
3639,
2254,
5034,
5023,
13937,
16,
203,
3639,
2254,
5034,
727,
13937,
16,
203,
3639,
2254,
5034,
8968,
751,
203,
565,
11272,
203,
565,
306,
3600,
17,
5540,
65,
300,
4894,
1817,
264,
9745,
7010,
565,
306,
5082,
17,
6334,
65,
300,
2552,
1817,
264,
9745,
7010,
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
] |
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: REMIX_FILE_SYNC/ApprovedCreatorRegistryInterface.sol
pragma solidity ^0.4.22;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract ApprovedCreatorRegistryInterface {
function getVersion() public pure returns (uint);
function typeOfContract() public pure returns (string);
function isOperatorApprovedForCustodialAccount(
address _operator,
address _custodialAddress) public view returns (bool);
}
// File: REMIX_FILE_SYNC/DigitalMediaStoreInterface.sol
pragma solidity 0.4.25;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract DigitalMediaStoreInterface {
function getDigitalMediaStoreVersion() public pure returns (uint);
function getStartingDigitalMediaId() public view returns (uint256);
function registerTokenContractAddress() external;
/**
* Creates a new digital media object in storage
* @param _creator address the address of the creator
* @param _printIndex uint32 the current print index for the limited edition media
* @param _totalSupply uint32 the total allowable prints for this media
* @param _collectionId uint256 the collection id that this media belongs to
* @param _metadataPath string the ipfs metadata path
* @return the id of the new digital media created
*/
function createDigitalMedia(
address _creator,
uint32 _printIndex,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath) external returns (uint);
/**
* Increments the current print index of the digital media object
* @param _digitalMediaId uint256 the id of the digital media
* @param _increment uint32 the amount to increment by
*/
function incrementDigitalMediaPrintIndex(
uint256 _digitalMediaId,
uint32 _increment) external;
/**
* Retrieves the digital media object by id
* @param _digitalMediaId uint256 the address of the creator
*/
function getDigitalMedia(uint256 _digitalMediaId) external view returns(
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath);
/**
* Creates a new collection
* @param _creator address the address of the creator
* @param _metadataPath string the ipfs metadata path
* @return the id of the new collection created
*/
function createCollection(address _creator, string _metadataPath) external returns (uint);
/**
* Retrieves a collection by id
* @param _collectionId uint256
*/
function getCollection(uint256 _collectionId) external view
returns(
uint256 id,
address creator,
string metadataPath);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.21;
/**
* @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();
}
}
// File: REMIX_FILE_SYNC/MediaStoreVersionControl.sol
pragma solidity 0.4.25;
/**
* A special control class that is used to configure and manage a token contract's
* different digital media store versions.
*
* Older versions of token contracts had the ability to increment the digital media's
* print edition in the media store, which was necessary in the early stages to provide
* upgradeability and flexibility.
*
* New verions will get rid of this ability now that token contract logic
* is more stable and we've built in burn capabilities.
*
* In order to support the older tokens, we need to be able to look up the appropriate digital
* media store associated with a given digital media id on the latest token contract.
*/
contract MediaStoreVersionControl is Pausable {
// The single allowed creator for this digital media contract.
DigitalMediaStoreInterface public v1DigitalMediaStore;
// The current digitial media store, used for this tokens creation.
DigitalMediaStoreInterface public currentDigitalMediaStore;
uint256 public currentStartingDigitalMediaId;
/**
* Validates that the managers are initialized.
*/
modifier managersInitialized() {
require(v1DigitalMediaStore != address(0));
require(currentDigitalMediaStore != address(0));
_;
}
/**
* Sets a digital media store address upon construction.
* Once set it's immutable, so that a token contract is always
* tied to one digital media store.
*/
function setDigitalMediaStoreAddress(address _dmsAddress)
internal {
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 2, "Incorrect version.");
currentDigitalMediaStore = candidateDigitalMediaStore;
currentDigitalMediaStore.registerTokenContractAddress();
currentStartingDigitalMediaId = currentDigitalMediaStore.getStartingDigitalMediaId();
}
/**
* Publicly callable by the owner, but can only be set one time, so don't make
* a mistake when setting it.
*
* Will also check that the version on the other end of the contract is in fact correct.
*/
function setV1DigitalMediaStoreAddress(address _dmsAddress) public onlyOwner {
require(address(v1DigitalMediaStore) == 0, "V1 media store already set.");
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 1, "Incorrect version.");
v1DigitalMediaStore = candidateDigitalMediaStore;
v1DigitalMediaStore.registerTokenContractAddress();
}
/**
* Depending on the digital media id, determines whether to return the previous
* version of the digital media manager.
*/
function _getDigitalMediaStore(uint256 _digitalMediaId)
internal
view
managersInitialized
returns (DigitalMediaStoreInterface) {
if (_digitalMediaId < currentStartingDigitalMediaId) {
return v1DigitalMediaStore;
} else {
return currentDigitalMediaStore;
}
}
}
// File: REMIX_FILE_SYNC/DigitalMediaManager.sol
pragma solidity 0.4.25;
/**
* Manager that interfaces with the underlying digital media store contract.
*/
contract DigitalMediaManager is MediaStoreVersionControl {
struct DigitalMedia {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string metadataPath;
}
struct DigitalMediaCollection {
uint256 id;
address creator;
string metadataPath;
}
ApprovedCreatorRegistryInterface public creatorRegistryStore;
// Set the creator registry address upon construction. Immutable.
function setCreatorRegistryStore(address _crsAddress) internal {
ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress);
require(candidateCreatorRegistryStore.getVersion() == 1);
// Simple check to make sure we are adding the registry contract indeed
// https://fravoll.github.io/solidity-patterns/string_equality_comparison.html
require(keccak256(candidateCreatorRegistryStore.typeOfContract()) == keccak256("approvedCreatorRegistry"));
creatorRegistryStore = candidateCreatorRegistryStore;
}
/**
* Validates that the Registered store is initialized.
*/
modifier registryInitialized() {
require(creatorRegistryStore != address(0));
_;
}
/**
* Retrieves a collection object by id.
*/
function _getCollection(uint256 _id)
internal
view
managersInitialized
returns(DigitalMediaCollection) {
uint256 id;
address creator;
string memory metadataPath;
(id, creator, metadataPath) = currentDigitalMediaStore.getCollection(_id);
DigitalMediaCollection memory collection = DigitalMediaCollection({
id: id,
creator: creator,
metadataPath: metadataPath
});
return collection;
}
/**
* Retrieves a digital media object by id.
*/
function _getDigitalMedia(uint256 _id)
internal
view
managersInitialized
returns(DigitalMedia) {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string memory metadataPath;
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_id);
(id, totalSupply, printIndex, collectionId, creator, metadataPath) = _digitalMediaStore.getDigitalMedia(_id);
DigitalMedia memory digitalMedia = DigitalMedia({
id: id,
creator: creator,
totalSupply: totalSupply,
printIndex: printIndex,
collectionId: collectionId,
metadataPath: metadataPath
});
return digitalMedia;
}
/**
* Increments the print index of a digital media object by some increment.
*/
function _incrementDigitalMediaPrintIndex(DigitalMedia _dm, uint32 _increment)
internal
managersInitialized {
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_dm.id);
_digitalMediaStore.incrementDigitalMediaPrintIndex(_dm.id, _increment);
}
// Check if the token operator is approved for the owner address
function isOperatorApprovedForCustodialAccount(
address _operator,
address _owner) internal view registryInitialized returns(bool) {
return creatorRegistryStore.isOperatorApprovedForCustodialAccount(
_operator, _owner);
}
}
// File: REMIX_FILE_SYNC/SingleCreatorControl.sol
pragma solidity 0.4.25;
/**
* A special control class that's used to help enforce that a DigitalMedia contract
* will service only a single creator's address. This is used when deploying a
* custom token contract owned and managed by a single creator.
*/
contract SingleCreatorControl {
// The single allowed creator for this digital media contract.
address public singleCreatorAddress;
// The single creator has changed.
event SingleCreatorChanged(
address indexed previousCreatorAddress,
address indexed newCreatorAddress);
/**
* Sets the single creator associated with this contract. This function
* can only ever be called once, and should ideally be called at the point
* of constructing the smart contract.
*/
function setSingleCreator(address _singleCreatorAddress) internal {
require(singleCreatorAddress == address(0), "Single creator address already set.");
singleCreatorAddress = _singleCreatorAddress;
}
/**
* Checks whether a given creator address matches the single creator address.
* Will always return true if a single creator address was never set.
*/
function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) {
require(_creatorAddress != address(0), "0x0 creator addresses are not allowed.");
return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress;
}
/**
* A publicly accessible function that allows the current single creator
* assigned to this contract to change to another address.
*/
function changeSingleCreator(address _newCreatorAddress) public {
require(_newCreatorAddress != address(0));
require(msg.sender == singleCreatorAddress, "Not approved to change single creator.");
singleCreatorAddress = _newCreatorAddress;
emit SingleCreatorChanged(singleCreatorAddress, _newCreatorAddress);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.4.21;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.21;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
pragma solidity ^0.4.21;
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_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 the token ID at a given index of all the tokens in this contract
* @dev 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];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: REMIX_FILE_SYNC/ERC721Safe.sol
pragma solidity 0.4.25;
// We have to specify what version of compiler this code will compile with
contract ERC721Safe is ERC721Token {
bytes4 constant internal InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant internal InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// File: REMIX_FILE_SYNC/Memory.sol
pragma solidity 0.4.25;
library Memory {
// Size of a word, in bytes.
uint internal constant WORD_SIZE = 32;
// Size of the header of a 'bytes' array.
uint internal constant BYTES_HEADER_SIZE = 32;
// Address of the free memory pointer.
uint internal constant FREE_MEM_PTR = 0x40;
// Compares the 'len' bytes starting at address 'addr' in memory with the 'len'
// bytes starting at 'addr2'.
// Returns 'true' if the bytes are the same, otherwise 'false'.
function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) {
assembly {
equal := eq(keccak256(addr, len), keccak256(addr2, len))
}
}
// Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in
// 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only
// the first 'len' bytes will be compared.
// Requires that 'bts.length >= len'
function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) {
require(bts.length >= len);
uint addr2;
assembly {
addr2 := add(bts, /*BYTES_HEADER_SIZE*/32)
}
return equals(addr, addr2, len);
}
// Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler
// from using this area of memory. It will also initialize the area by setting
// each byte to '0'.
function allocate(uint numBytes) internal pure returns (uint addr) {
// Take the current value of the free memory pointer, and update.
assembly {
addr := mload(/*FREE_MEM_PTR*/0x40)
mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes))
}
uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE;
for (uint i = 0; i < words; i++) {
assembly {
mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0)
}
}
}
// Copy 'len' bytes from memory address 'src', to address 'dest'.
// This function does not check the or destination, it only copies
// the bytes.
function copy(uint src, uint dest, uint len) internal pure {
// Copy word-length chunks while possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
dest += WORD_SIZE;
src += WORD_SIZE;
}
// Copy remaining bytes
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
// Returns a memory pointer to the provided bytes array.
function ptr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := bts
}
}
// Returns a memory pointer to the data portion of the provided bytes array.
function dataPtr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// This function does the same as 'dataPtr(bytes memory)', but will also return the
// length of the provided bytes array.
function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) {
len = bts.length;
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// Creates a 'bytes memory' variable from the memory address 'addr', with the
// length 'len'. The function will allocate new memory for the bytes array, and
// the 'len bytes starting at 'addr' will be copied into that new memory.
function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) {
bts = new bytes(len);
uint btsptr;
assembly {
btsptr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
copy(addr, btsptr, len);
}
// Get the word stored at memory address 'addr' as a 'uint'.
function toUint(uint addr) internal pure returns (uint n) {
assembly {
n := mload(addr)
}
}
// Get the word stored at memory address 'addr' as a 'bytes32'.
function toBytes32(uint addr) internal pure returns (bytes32 bts) {
assembly {
bts := mload(addr)
}
}
/*
// Get the byte stored at memory address 'addr' as a 'byte'.
function toByte(uint addr, uint8 index) internal pure returns (byte b) {
require(index < WORD_SIZE);
uint8 n;
assembly {
n := byte(index, mload(addr))
}
b = byte(n);
}
*/
}
// File: REMIX_FILE_SYNC/HelperUtils.sol
pragma solidity 0.4.25;
/**
* Internal helper functions
*/
contract HelperUtils {
// converts bytes32 to a string
// enable this when you use it. Saving gas for now
// function bytes32ToString(bytes32 x) private pure returns (string) {
// bytes memory bytesString = new bytes(32);
// uint charCount = 0;
// for (uint j = 0; j < 32; j++) {
// byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
// if (char != 0) {
// bytesString[charCount] = char;
// charCount++;
// }
// }
// bytes memory bytesStringTrimmed = new bytes(charCount);
// for (j = 0; j < charCount; j++) {
// bytesStringTrimmed[j] = bytesString[j];
// }
// return string(bytesStringTrimmed);
// }
/**
* Concatenates two strings
* @param _a string
* @param _b string
* @return string concatenation of two string
*/
function strConcat(string _a, string _b) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ab = new string(_ba.length + _bb.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaToken.sol
pragma solidity 0.4.25;
/**
* The DigitalMediaToken contract. Fully implements the ERC721 contract
* from OpenZeppelin without any modifications to it.
*
* This contract allows for the creation of:
* 1. New Collections
* 2. New DigitalMedia objects
* 3. New DigitalMediaRelease objects
*
* The primary piece of logic is to ensure that an ERC721 token can
* have a supply and print edition that is enforced by this contract.
*/
contract DigitalMediaToken is DigitalMediaManager, ERC721Safe, HelperUtils, SingleCreatorControl {
event DigitalMediaReleaseCreateEvent(
uint256 id,
address owner,
uint32 printEdition,
string tokenURI,
uint256 digitalMediaId);
// Event fired when a new digital media is created
event DigitalMediaCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
string metadataPath);
// Event fired when a digital media's collection is
event DigitalMediaCollectionCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
string metadataPath);
// Event fired when a digital media is burned
event DigitalMediaBurnEvent(
uint256 id,
address caller,
address storeContractAddress);
// Event fired when burning a token
event DigitalMediaReleaseBurnEvent(
uint256 tokenId,
address owner);
event UpdateDigitalMediaPrintIndexEvent(
uint256 digitalMediaId,
uint32 printEdition);
// Event fired when a creator assigns a new creator address.
event ChangedCreator(
address creator,
address newCreator);
struct DigitalMediaRelease {
// The unique edition number of this digital media release
uint32 printEdition;
// Reference ID to the digital media metadata
uint256 digitalMediaId;
}
// Maps internal ERC721 token ID to digital media release object.
mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease;
// Maps a creator address to a new creator address. Useful if a creator
// changes their address or the previous address gets compromised.
mapping (address => address) public approvedCreators;
// Token ID counter
uint256 internal tokenIdCounter = 0;
constructor (string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter)
public ERC721Token(_tokenName, _tokenSymbol) {
tokenIdCounter = _tokenIdStartingCounter;
}
/**
* Creates a new digital media object.
* @param _creator address the creator of this digital media
* @param _totalSupply uint32 the total supply a creation could have
* @param _collectionId uint256 the collectionId that it belongs to
* @param _metadataPath string the path to the ipfs metadata
* @return uint the new digital media id
*/
function _createDigitalMedia(
address _creator, uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
internal
returns (uint) {
require(_validateCollection(_collectionId, _creator), "Creator for collection not approved.");
uint256 newDigitalMediaId = currentDigitalMediaStore.createDigitalMedia(
_creator,
0,
_totalSupply,
_collectionId,
_metadataPath);
emit DigitalMediaCreateEvent(
newDigitalMediaId,
address(currentDigitalMediaStore),
_creator,
_totalSupply,
0,
_collectionId,
_metadataPath);
return newDigitalMediaId;
}
/**
* Burns a token for a given tokenId and caller.
* @param _tokenId the id of the token to burn.
* @param _caller the address of the caller.
*/
function _burnToken(uint256 _tokenId, address _caller) internal {
address owner = ownerOf(_tokenId);
require(_caller == owner ||
getApproved(_tokenId) == _caller ||
isApprovedForAll(owner, _caller),
"Failed token burn. Caller is not approved.");
_burn(owner, _tokenId);
delete tokenIdToDigitalMediaRelease[_tokenId];
emit DigitalMediaReleaseBurnEvent(_tokenId, owner);
}
/**
* Burns a digital media. Once this function succeeds, this digital media
* will no longer be able to mint any more tokens. Existing tokens need to be
* burned individually though.
* @param _digitalMediaId the id of the digital media to burn
* @param _caller the address of the caller.
*/
function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal {
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
require(_checkApprovedCreator(_digitalMedia.creator, _caller) ||
isApprovedForAll(_digitalMedia.creator, _caller),
"Failed digital media burn. Caller not approved.");
uint32 increment = _digitalMedia.totalSupply - _digitalMedia.printIndex;
_incrementDigitalMediaPrintIndex(_digitalMedia, increment);
address _burnDigitalMediaStoreAddress = address(_getDigitalMediaStore(_digitalMedia.id));
emit DigitalMediaBurnEvent(
_digitalMediaId, _caller, _burnDigitalMediaStoreAddress);
}
/**
* Creates a new collection
* @param _creator address the creator of this collection
* @param _metadataPath string the path to the collection ipfs metadata
* @return uint the new collection id
*/
function _createCollection(
address _creator, string _metadataPath)
internal
returns (uint) {
uint256 newCollectionId = currentDigitalMediaStore.createCollection(
_creator,
_metadataPath);
emit DigitalMediaCollectionCreateEvent(
newCollectionId,
address(currentDigitalMediaStore),
_creator,
_metadataPath);
return newCollectionId;
}
/**
* Creates _count number of new digital media releases (i.e a token).
* Bumps up the print index by _count.
* @param _owner address the owner of the digital media object
* @param _digitalMediaId uint256 the digital media id
*/
function _createDigitalMediaReleases(
address _owner, uint256 _digitalMediaId, uint32 _count)
internal {
require(_count > 0, "Failed print edition. Creation count must be > 0.");
require(_count < 10000, "Cannot print more than 10K tokens at once");
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
uint32 currentPrintIndex = _digitalMedia.printIndex;
require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved.");
require(isAllowedSingleCreator(_owner), "Creator must match single creator address.");
require(_count + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded.");
string memory tokenURI = HelperUtils.strConcat("ipfs://ipfs/", _digitalMedia.metadataPath);
for (uint32 i=0; i < _count; i++) {
uint32 newPrintEdition = currentPrintIndex + 1 + i;
DigitalMediaRelease memory _digitalMediaRelease = DigitalMediaRelease({
printEdition: newPrintEdition,
digitalMediaId: _digitalMediaId
});
uint256 newDigitalMediaReleaseId = _getNextTokenId();
tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId] = _digitalMediaRelease;
emit DigitalMediaReleaseCreateEvent(
newDigitalMediaReleaseId,
_owner,
newPrintEdition,
tokenURI,
_digitalMediaId
);
// This will assign ownership and also emit the Transfer event as per ERC721
_mint(_owner, newDigitalMediaReleaseId);
_setTokenURI(newDigitalMediaReleaseId, tokenURI);
tokenIdCounter = tokenIdCounter.add(1);
}
_incrementDigitalMediaPrintIndex(_digitalMedia, _count);
emit UpdateDigitalMediaPrintIndexEvent(_digitalMediaId, currentPrintIndex + _count);
}
/**
* Checks that a given caller is an approved creator and is allowed to mint or burn
* tokens. If the creator was changed it will check against the updated creator.
* @param _caller the calling address
* @return bool allowed or not
*/
function _checkApprovedCreator(address _creator, address _caller)
internal
view
returns (bool) {
address approvedCreator = approvedCreators[_creator];
if (approvedCreator != address(0)) {
return approvedCreator == _caller;
} else {
return _creator == _caller;
}
}
/**
* Validates the an address is allowed to create a digital media on a
* given collection. Collections are tied to addresses.
*/
function _validateCollection(uint256 _collectionId, address _address)
private
view
returns (bool) {
if (_collectionId == 0 ) {
return true;
}
DigitalMediaCollection memory collection = _getCollection(_collectionId);
return _checkApprovedCreator(collection.creator, _address);
}
/**
* Generates a new token id.
*/
function _getNextTokenId() private view returns (uint256) {
return tokenIdCounter.add(1);
}
/**
* Changes the creator that is approved to printing new tokens and creations.
* Either the _caller must be the _creator or the _caller must be the existing
* approvedCreator.
* @param _caller the address of the caller
* @param _creator the address of the current creator
* @param _newCreator the address of the new approved creator
*/
function _changeCreator(address _caller, address _creator, address _newCreator) internal {
address approvedCreator = approvedCreators[_creator];
require(_caller != address(0) && _creator != address(0), "Creator must be valid non 0x0 address.");
require(_caller == _creator || _caller == approvedCreator, "Unauthorized caller.");
if (approvedCreator == address(0)) {
approvedCreators[_caller] = _newCreator;
} else {
require(_caller == approvedCreator, "Unauthorized caller.");
approvedCreators[_creator] = _newCreator;
}
emit ChangedCreator(_creator, _newCreator);
}
/**
* Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
}
// File: REMIX_FILE_SYNC/OBOControl.sol
pragma solidity 0.4.25;
contract OBOControl is Pausable {
// List of approved on behalf of users.
mapping (address => bool) public approvedOBOs;
/**
* Add a new approved on behalf of user address.
*/
function addApprovedOBO(address _oboAddress) external onlyOwner {
approvedOBOs[_oboAddress] = true;
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedOBO(address _oboAddress) external onlyOwner {
delete approvedOBOs[_oboAddress];
}
/**
* @dev Modifier to make the obo calls only callable by approved addressess
*/
modifier isApprovedOBO() {
require(approvedOBOs[msg.sender] == true);
_;
}
}
// File: REMIX_FILE_SYNC/WithdrawFundsControl.sol
pragma solidity 0.4.25;
contract WithdrawFundsControl is Pausable {
// List of approved on withdraw addresses
mapping (address => uint256) public approvedWithdrawAddresses;
// Full day wait period before an approved withdraw address becomes active
uint256 constant internal withdrawApprovalWaitPeriod = 60 * 60 * 24;
event WithdrawAddressAdded(address withdrawAddress);
event WithdrawAddressRemoved(address widthdrawAddress);
/**
* Add a new approved on behalf of user address.
*/
function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
approvedWithdrawAddresses[_withdrawAddress] = now;
emit WithdrawAddressAdded(_withdrawAddress);
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
delete approvedWithdrawAddresses[_withdrawAddress];
emit WithdrawAddressRemoved(_withdrawAddress);
}
/**
* Checks that a given withdraw address ia approved and is past it's required
* wait time.
*/
function isApprovedWithdrawAddress(address _withdrawAddress) internal view returns (bool) {
uint256 approvalTime = approvedWithdrawAddresses[_withdrawAddress];
require (approvalTime > 0);
return now - approvalTime > withdrawApprovalWaitPeriod;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol
pragma solidity ^0.4.21;
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
// File: REMIX_FILE_SYNC/DigitalMediaSaleBase.sol
pragma solidity 0.4.25;
/**
* Base class that manages the underlying functions of a Digital Media Sale,
* most importantly the escrow of digital tokens.
*
* Manages ensuring that only approved addresses interact with this contract.
*
*/
contract DigitalMediaSaleBase is ERC721Holder, Pausable, OBOControl, WithdrawFundsControl {
using SafeMath for uint256;
// Mapping of token contract address to bool indicated approval.
mapping (address => bool) public approvedTokenContracts;
/**
* Adds a new token contract address to be approved to be called.
*/
function addApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
approvedTokenContracts[_tokenContractAddress] = true;
}
/**
* Remove an approved token contract address from the list of approved addresses.
*/
function removeApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
delete approvedTokenContracts[_tokenContractAddress];
}
/**
* Checks that a particular token contract address is a valid address.
*/
function _isValidTokenContract(address _tokenContractAddress)
internal view returns (bool) {
return approvedTokenContracts[_tokenContractAddress];
}
/**
* Returns an ERC721 instance of a token contract address. Throws otherwise.
* Only valid and approved token contracts are allowed to be interacted with.
*/
function _getTokenContract(address _tokenContractAddress) internal view returns (ERC721Safe) {
require(_isValidTokenContract(_tokenContractAddress));
return ERC721Safe(_tokenContractAddress);
}
/**
* Checks with the ERC-721 token contract that the _claimant actually owns the token.
*/
function _owns(address _claimant, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.ownerOf(_tokenId) == _claimant);
}
/**
* Checks with the ERC-721 token contract the owner of the a token
*/
function _ownerOf(uint256 _tokenId, address _tokenContractAddress) internal view returns (address) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return tokenContract.ownerOf(_tokenId);
}
/**
* Checks to ensure that the token owner has approved the escrow contract
*/
function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.isApprovedForAll(_seller, this) ||
tokenContract.getApproved(_tokenId) == address(this));
}
/**
* Escrows an ERC-721 token from the seller to this contract. Assumes that the escrow contract
* is already approved to make the transfer, otherwise it will fail.
*/
function _escrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(_seller, this, _tokenId);
}
/**
* Transfer an ERC-721 token from escrow to the buyer. This is to be called after a purchase is
* completed.
*/
function _transfer(address _receiver, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(this, _receiver, _tokenId);
}
/**
* Method to check whether this is an escrow contract
*/
function isEscrowContract() public pure returns(bool) {
return true;
}
/**
* Withdraws all the funds to a specified non-zero address
*/
function withdrawFunds(address _withdrawAddress) public onlyOwner {
require(isApprovedWithdrawAddress(_withdrawAddress));
_withdrawAddress.transfer(address(this).balance);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaCore.sol
pragma solidity 0.4.25;
/**
* This is the main driver contract that is used to control and run the service. Funds
* are managed through this function, underlying contracts are also updated through
* this contract.
*
* This class also exposes a set of creation methods that are allowed to be created
* by an approved token creator, on behalf of a particular address. This is meant
* to simply the creation flow for MakersToken users that aren't familiar with
* the blockchain. The ERC721 tokens that are created are still fully compliant,
* although it is possible for a malicious token creator to mint unwanted tokens
* on behalf of a creator. Worst case, the creator can burn those tokens.
*/
contract DigitalMediaCore is DigitalMediaToken {
using SafeMath for uint32;
// List of approved token creators (on behalf of the owner)
mapping (address => bool) public approvedTokenCreators;
// Mapping from owner to operator accounts.
mapping (address => mapping (address => bool)) internal oboOperatorApprovals;
// Mapping of all disabled OBO operators.
mapping (address => bool) public disabledOboOperators;
// OboApproveAll Event
event OboApprovalForAll(
address _owner,
address _operator,
bool _approved);
// Fired when disbaling obo capability.
event OboDisabledForAll(address _operator);
constructor (
string _tokenName,
string _tokenSymbol,
uint256 _tokenIdStartingCounter,
address _dmsAddress,
address _crsAddress)
public DigitalMediaToken(
_tokenName,
_tokenSymbol,
_tokenIdStartingCounter) {
paused = true;
setDigitalMediaStoreAddress(_dmsAddress);
setCreatorRegistryStore(_crsAddress);
}
/**
* Retrieves a Digital Media object.
*/
function getDigitalMedia(uint256 _id)
external
view
returns (
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath) {
DigitalMedia memory digitalMedia = _getDigitalMedia(_id);
require(digitalMedia.creator != address(0), "DigitalMedia not found.");
id = _id;
totalSupply = digitalMedia.totalSupply;
printIndex = digitalMedia.printIndex;
collectionId = digitalMedia.collectionId;
creator = digitalMedia.creator;
metadataPath = digitalMedia.metadataPath;
}
/**
* Retrieves a collection.
*/
function getCollection(uint256 _id)
external
view
returns (
uint256 id,
address creator,
string metadataPath) {
DigitalMediaCollection memory digitalMediaCollection = _getCollection(_id);
require(digitalMediaCollection.creator != address(0), "Collection not found.");
id = _id;
creator = digitalMediaCollection.creator;
metadataPath = digitalMediaCollection.metadataPath;
}
/**
* Retrieves a Digital Media Release (i.e a token)
*/
function getDigitalMediaRelease(uint256 _id)
external
view
returns (
uint256 id,
uint32 printEdition,
uint256 digitalMediaId) {
require(exists(_id));
DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id];
id = _id;
printEdition = digitalMediaRelease.printEdition;
digitalMediaId = digitalMediaRelease.digitalMediaId;
}
/**
* Creates a new collection.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createCollection(string _metadataPath)
external
whenNotPaused {
_createCollection(msg.sender, _metadataPath);
}
/**
* Creates a new digital media object.
*/
function createDigitalMedia(uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
external
whenNotPaused {
_createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
}
/**
* Creates a new digital media object and mints it's first digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleases(
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleasesInNewCollection(
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 collectionId = _createCollection(msg.sender, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new digital media release (token) for a given digital media id.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaReleases(uint256 _digitalMediaId, uint32 _numReleases)
external
whenNotPaused {
_createDigitalMediaReleases(msg.sender, _digitalMediaId, _numReleases);
}
/**
* Deletes a token / digital media release. Doesn't modify the current print index
* and total to be printed. Although dangerous, the owner of a token should always
* be able to burn a token they own.
*
* Only the owner of the token or accounts approved by the owner can burn this token.
*/
function burnToken(uint256 _tokenId) external {
_burnToken(_tokenId, msg.sender);
}
/* Support ERC721 burn method */
function burn(uint256 tokenId) public {
_burnToken(tokenId, msg.sender);
}
/**
* Ends the production run of a digital media. Afterwards no more tokens
* will be allowed to be printed for this digital media. Used when a creator
* makes a mistake and wishes to burn and recreate their digital media.
*
* When a contract is paused we do not allow new tokens to be created,
* so stopping the production of a token doesn't have much purpose.
*/
function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused {
_burnDigitalMedia(_digitalMediaId, msg.sender);
}
/**
* Resets the approval rights for a given tokenId.
*/
function resetApproval(uint256 _tokenId) external {
clearApproval(msg.sender, _tokenId);
}
/**
* Changes the creator for the current sender, in the event we
* need to be able to mint new tokens from an existing digital media
* print production. When changing creator, the old creator will
* no longer be able to mint tokens.
*
* A creator may need to be changed:
* 1. If we want to allow a creator to take control over their token minting (i.e go decentralized)
* 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function
* when the contract is paused.
* @param _creator the creator address
* @param _newCreator the new creator address
*/
function changeCreator(address _creator, address _newCreator) external {
_changeCreator(msg.sender, _creator, _newCreator);
}
/**********************************************************************/
/**Calls that are allowed to be called by approved creator addresses **/
/**********************************************************************/
/**
* Add a new approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function addApprovedTokenCreator(address _creatorAddress) external onlyOwner {
require(disabledOboOperators[_creatorAddress] != true, "Address disabled.");
approvedTokenCreators[_creatorAddress] = true;
}
/**
* Removes an approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function removeApprovedTokenCreator(address _creatorAddress) external onlyOwner {
delete approvedTokenCreators[_creatorAddress];
}
/**
* @dev Modifier to make the approved creation calls only callable by approved token creators
*/
modifier isApprovedCreator() {
require(
(approvedTokenCreators[msg.sender] == true &&
disabledOboOperators[msg.sender] != true),
"Unapproved OBO address.");
_;
}
/**
* Only the owner address can set a special obo approval list.
* When issuing OBO management accounts, we should give approvals through
* this method only so that we can very easily reset it's approval in
* the event of a disaster scenario.
*
* Only the owner themselves is allowed to give OboApproveAll access.
*/
function setOboApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender, "Approval address is same as approver.");
require(approvedTokenCreators[_to], "Unrecognized OBO address.");
require(disabledOboOperators[_to] != true, "Approval address is disabled.");
oboOperatorApprovals[msg.sender][_to] = _approved;
emit OboApprovalForAll(msg.sender, _to, _approved);
}
/**
* Only called in a disaster scenario if the account has been compromised.
* There's no turning back from this and the oboAddress will no longer be
* able to be given approval rights or perform obo functions.
*
* Only the owner of this contract is allowed to disable an Obo address.
*
*/
function disableOboAddress(address _oboAddress) public onlyOwner {
require(approvedTokenCreators[_oboAddress], "Unrecognized OBO address.");
disabledOboOperators[_oboAddress] = true;
delete approvedTokenCreators[_oboAddress];
emit OboDisabledForAll(_oboAddress);
}
/**
* Override the isApprovalForAll to check for a special oboApproval list. Reason for this
* is that we can can easily remove obo operators if they every become compromised.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
if (disabledOboOperators[_operator] == true) {
return false;
} else if (isOperatorApprovedForCustodialAccount(_operator, _owner) == true) {
return true;
} else if (oboOperatorApprovals[_owner][_operator]) {
return true;
} else {
return super.isApprovedForAll(_owner, _operator);
}
}
/**
* Creates a new digital media object and mints it's digital media release tokens.
* Called on behalf of the _owner. Pass count to mint `n` number of tokens.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleases(
address _owner,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleasesInNewCollection(
address _owner,
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 collectionId = _createCollection(_owner, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates multiple digital media releases (tokens) for a given digital media id.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaReleases(
address _owner,
uint256 _digitalMediaId,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
_createDigitalMediaReleases(_owner, _digitalMediaId, _numReleases);
}
} | * Add a new approved on behalf of user address./ | function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
approvedWithdrawAddresses[_withdrawAddress] = now;
emit WithdrawAddressAdded(_withdrawAddress);
}
| 890,404 | [
1,
986,
279,
394,
20412,
603,
12433,
6186,
434,
729,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
31639,
1190,
9446,
1887,
12,
2867,
389,
1918,
9446,
1887,
13,
3903,
1338,
5541,
288,
203,
3639,
20412,
1190,
9446,
7148,
63,
67,
1918,
9446,
1887,
65,
273,
2037,
31,
203,
3639,
3626,
3423,
9446,
1887,
8602,
24899,
1918,
9446,
1887,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
import "./ServiceDatabase.sol";
/*
This file contains the ServiceLogic smart contract. It provides the business logic for the Service smart
contract, such as the functionality for the state channel / oracle, compliance checking of the SLA and the
calculation of reimbursements. It also includes the withdrawal-pattern to allow the service provider to collect
its service fee.
*/
contract ServiceLogic is ServiceDatabase {
/*
State channel logic by https://github.com/mattdf/payment-channel/blob/master/channel.sol
This function is part of the state channel pattern. Customer, provider and monitoringAgent exchange
the service performance data (availabilityData) off-chain to reduce transaction costs. The provider collects
the service fee by calling this function once with his signed transaction of the availabilityData and once
with the monitoringsAgent's or customer's signed transaction
*/
function addAvailabilityData(bytes32 h, uint8 v, bytes32 r, bytes32 s, uint[] availabilityData) public {
address signer;
bytes32 proof;
// do this for testing because truffle's web 3 is different to MetaMask's web3
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, h));
address signer2 = ecrecover(prefixedHash, v, r, s);
// now this is for prod with MetaMask:
// get who signed hash of (contract_address, values)
signer = ecrecover(h, v, r, s);
// check if signer is either provider, customer or monitoringAgent
require(signer == provider || signer == customer || signer == monitoringAgent || signer2 == provider || signer2 == customer || signer2 == monitoringAgent, "You are not a valid signer!");
proof = keccak256(abi.encodePacked(address(this), availabilityData));
// hash of contract's address and value equals provided hash h
require(proof == h, "Provided hash h and calculated proof do not match!");
if (signatures[proof] == 0) {
signatures[proof] = signer;
}
else if (signatures[proof] != signer) {
// two out of three individuals accept this monitoring data
// Append to availabilityHistory, check compliance with SLA and
// payout provider accordingly (by adding the amount to withdrawableForProvider & update lastBillDate afterwards)
require(availabilityData.length <= ((now - lastBillDate) / 1 days), "You cannot add performance data for the future!");
paymentToProvider(availabilityData);
}
}
// Payment for the provider after calculating SLA compliance and possible penalty deductions.
function paymentToProvider(uint[] availabilityData) internal {
uint availability;
uint providerPenalty = 100;
// calculate the SLA compliance and penalty per day
for (uint i = 1; i <= availabilityData.length; i++) {
availability = availabilityData[i - 1];
providerPenalty = (providerPenalty * (i - 1) + calculatePenalty(availability)) / i;
availabilityHistory.push(availabilityData[i - 1]);
}
// Calculate the service fee for provider according to the performance per day and SLA penalties
uint earningsProviderSinceLastUpdate = costPerDay * availabilityData.length * providerPenalty / 100;
withdrawableForProvider += earningsProviderSinceLastUpdate;
// use withdrawable pattern for provider
lastBillDate += 1 days * availabilityData.length;
emit WithdrawalForProviderChanged(withdrawableForProvider);
}
// helper function that checks the SLOs of the SLA
function calculatePenalty(uint _achievedServiceQuality) public view returns (uint){
require(slaSet, "SLA has not been set yet, cannot calculate quality");
uint penalty = sla[4];
//default: set penalty to refundLow (achieved 0% - middleGoal)
if (_achievedServiceQuality >= sla[2]) penalty = sla[3];
//set penalty to refundMiddle (achieved middleGoal - highGoal)
if (_achievedServiceQuality >= sla[1]) penalty = 0;
// SLA was adhered to -> no penalty
return penalty;
}
// This function changes the duration of this contract. When called by a msg with value, the contract is extended.
// When called without value but a parameter indicating the days to substract from the duration, this function
// shortens the contract duration and transfers the deposit to the customer
function changeContractDuration(int _changeDays) public payable returns (uint) {
//if(_changeDays > 0 && msg.value < costPerDay) return;
// Check if contract get's extended or shortened
if (_changeDays > 0) {
// extend the contract
require(msg.value >= costPerDay, "Payable > costPerDay is required to extend at least by a day!");
uint extendableDays = msg.value / costPerDay;
endDate += extendableDays * 1 days;
if (!isActive && endDate > now) setActive(true);
} else {
// shorten the contract
// check if someone's trying to shorten the contract into the past
uint changeDays = uint(- 1 * _changeDays);
require(endDate - (changeDays * 1 days) > (now + 1 days), "Can shorten contract only till tomorrow!");
// transfer funds back to customer
uint reimbursement = changeDays * costPerDay;
endDate = endDate - changeDays * 1 days;
customer.transfer(reimbursement);
}
emit ContractEndDateUpdated(endDate);
return endDate;
}
function terminateContract() public onlyPartners {
require(endDate < now, "Cannot terminate contract before its endDate!");
selfdestruct(customer);
}
// function that allows the provider to withdraw its service fee
function withdrawProvider() public onlyProvider {
// Transfers payout to provider
msg.sender.transfer(withdrawableForProvider);
withdrawableForProvider = 0;
}
function setActive(bool _state) internal {
if (isActive != _state) emit ContractStateChanged(_state);
isActive = _state;
}
}
| Calculate the service fee for provider according to the performance per day and SLA penalties | uint earningsProviderSinceLastUpdate = costPerDay * availabilityData.length * providerPenalty / 100;
| 912,216 | [
1,
8695,
326,
1156,
14036,
364,
2893,
4888,
358,
326,
9239,
1534,
2548,
471,
348,
2534,
14264,
2390,
606,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
425,
1303,
899,
2249,
9673,
3024,
1891,
273,
6991,
2173,
4245,
380,
13395,
751,
18,
2469,
380,
2893,
24251,
15006,
342,
2130,
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
] |
./full_match/1/0x1AE369A6AB222aFF166325B7b87Eb9aF06C86E57/sources/contracts/helpers/Ownable.sol | * @dev Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. Can only be invoked by the current `owner`. @param _newOwner Address of the new owner. @param _direct True if `_newOwner` should be set immediately. False if `_newOwner` needs to use `claimOwnership`. @param _renounce Allows the `_newOwner` to be `address(0)` if `_direct` and `_renounce` is True. Has no effect otherwise/ | function transferOwnership(
address _newOwner,
bool _direct,
bool _renounce
) external onlyOwner {
if (_direct) {
require(_newOwner != address(0) || _renounce, "zero address");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
pendingOwner = address(0);
pendingOwner = _newOwner;
}
}
| 8,387,820 | [
1,
1429,
18881,
23178,
358,
1375,
2704,
5541,
8338,
14635,
5122,
578,
7516,
429,
635,
326,
394,
4634,
3410,
18,
1377,
4480,
1338,
506,
8187,
635,
326,
783,
1375,
8443,
8338,
225,
389,
2704,
5541,
5267,
434,
326,
394,
3410,
18,
225,
389,
7205,
1053,
309,
1375,
67,
2704,
5541,
68,
1410,
506,
444,
7636,
18,
1083,
309,
1375,
67,
2704,
5541,
68,
4260,
358,
999,
1375,
14784,
5460,
12565,
8338,
225,
389,
1187,
8386,
25619,
326,
1375,
67,
2704,
5541,
68,
358,
506,
1375,
2867,
12,
20,
22025,
309,
1375,
67,
7205,
68,
471,
1375,
67,
1187,
8386,
68,
353,
1053,
18,
4393,
1158,
5426,
3541,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7412,
5460,
12565,
12,
203,
3639,
1758,
389,
2704,
5541,
16,
203,
3639,
1426,
389,
7205,
16,
203,
3639,
1426,
389,
1187,
8386,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
309,
261,
67,
7205,
13,
288,
203,
5411,
2583,
24899,
2704,
5541,
480,
1758,
12,
20,
13,
747,
389,
1187,
8386,
16,
315,
7124,
1758,
8863,
203,
203,
5411,
3626,
14223,
9646,
5310,
1429,
4193,
12,
8443,
16,
389,
2704,
5541,
1769,
203,
5411,
3410,
273,
389,
2704,
5541,
31,
203,
5411,
4634,
5541,
273,
1758,
12,
20,
1769,
203,
5411,
4634,
5541,
273,
389,
2704,
5541,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-27
*/
pragma solidity 0.6.4;
library EthAddressLib {
/**
* @dev returns the address used within the protocol to identify ETH
* @return the address assigned to ETH
*/
function ethAddress() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a <= b ? a : b;
}
function abs(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return b - a;
}
return a - b;
}
}
contract Exponential {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
using SafeMath for uint256;
function getExp(uint256 num, uint256 denom)
public
pure
returns (uint256 rational)
{
rational = num.mul(expScale).div(denom);
}
function getDiv(uint256 num, uint256 denom)
public
pure
returns (uint256 rational)
{
rational = num.mul(expScale).div(denom);
}
function addExp(uint256 a, uint256 b) public pure returns (uint256 result) {
result = a.add(b);
}
function subExp(uint256 a, uint256 b) public pure returns (uint256 result) {
result = a.sub(b);
}
function mulExp(uint256 a, uint256 b) public pure returns (uint256) {
uint256 doubleScaledProduct = a.mul(b);
uint256 doubleScaledProductWithHalfScale =
halfExpScale.add(doubleScaledProduct);
return doubleScaledProductWithHalfScale.div(expScale);
}
function divExp(uint256 a, uint256 b) public pure returns (uint256) {
return getDiv(a, b);
}
function mulExp3(
uint256 a,
uint256 b,
uint256 c
) public pure returns (uint256) {
return mulExp(mulExp(a, b), c);
}
function mulScalar(uint256 a, uint256 scalar)
public
pure
returns (uint256 scaled)
{
scaled = a.mul(scalar);
}
function mulScalarTruncate(uint256 a, uint256 scalar)
public
pure
returns (uint256)
{
uint256 product = mulScalar(a, scalar);
return truncate(product);
}
function mulScalarTruncateAddUInt(
uint256 a,
uint256 scalar,
uint256 addend
) public pure returns (uint256) {
uint256 product = mulScalar(a, scalar);
return truncate(product).add(addend);
}
function divScalarByExpTruncate(uint256 scalar, uint256 divisor)
public
pure
returns (uint256)
{
uint256 fraction = divScalarByExp(scalar, divisor);
return truncate(fraction);
}
function divScalarByExp(uint256 scalar, uint256 divisor)
public
pure
returns (uint256)
{
uint256 numerator = expScale.mul(scalar);
return getExp(numerator, divisor);
}
function divScalar(uint256 a, uint256 scalar)
public
pure
returns (uint256)
{
return a.div(scalar);
}
function truncate(uint256 exp) public pure returns (uint256) {
return exp.div(expScale);
}
}
/**
* @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.
*/
function decimals() external view returns (uint8);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
interface IFToken is IERC20 {
function mint(address user, uint256 amount) external returns (bytes memory);
function borrow(address borrower, uint256 borrowAmount)
external
returns (bytes memory);
function withdraw(
address payable withdrawer,
uint256 withdrawTokensIn,
uint256 withdrawAmountIn
) external returns (uint256, bytes memory);
function underlying() external view returns (address);
function accrueInterest() external;
function getAccountState(address account)
external
view
returns (
uint256,
uint256,
uint256
);
function MonitorEventCallback(
address who,
bytes32 funcName,
bytes calldata payload
) external;
function exchangeRateCurrent() external view returns (uint256 exchangeRate);
function repay(address borrower, uint256 repayAmount)
external
returns (uint256, bytes memory);
function borrowBalanceStored(address account)
external
view
returns (uint256);
function exchangeRateStored() external view returns (uint256 exchangeRate);
function liquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address fTokenCollateral
) external returns (bytes memory);
function borrowBalanceCurrent(address account) external returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function _reduceReserves(uint256 reduceAmount) external;
function _addReservesFresh(uint256 addAmount) external;
function cancellingOut(address striker)
external
returns (bool strikeOk, bytes memory strikeLog);
function APR() external view returns (uint256);
function APY() external view returns (uint256);
function calcBalanceOfUnderlying(address owner)
external
view
returns (uint256);
function borrowSafeRatio() external view returns (uint256);
function tokenCash(address token, address account)
external
view
returns (uint256);
function getBorrowRate() external view returns (uint256);
function addTotalCash(uint256 _addAmount) external;
function subTotalCash(uint256 _subAmount) external;
function totalCash() external view returns (uint256);
function totalReserves() external view returns (uint256);
function totalBorrows() external view returns (uint256);
}
interface IOracle {
function get(address token) external view returns (uint256, bool);
}
/**
* @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"
);
}
}
}
enum RewardType {
DefaultType,
Deposit,
Borrow,
Withdraw,
Repay,
Liquidation,
TokenIn,
TokenOut
}
interface IBank {
function MonitorEventCallback(bytes32 funcName, bytes calldata payload)
external;
function deposit(address token, uint256 amount) external payable;
function borrow(address token, uint256 amount) external;
function withdraw(address underlying, uint256 withdrawTokens) external;
function withdrawUnderlying(address underlying, uint256 amount) external;
function repay(address token, uint256 amount) external payable;
function liquidateBorrow(
address borrower,
address underlyingBorrow,
address underlyingCollateral,
uint256 repayAmount
) external payable;
function tokenIn(address token, uint256 amountIn) external payable;
function tokenOut(address token, uint256 amountOut) external;
function cancellingOut(address token) external;
function paused() external view returns (bool);
}
// reward token pool interface (FOR)
interface IRewardPool {
function theForceToken() external view returns (address);
function bankController() external view returns (address);
function admin() external view returns (address);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
function withdraw() external;
function setTheForceToken(address _theForceToken) external;
function setBankController(address _bankController) external;
function reward(address who, uint256 amount) external;
}
/**
* @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;
}
pragma experimental ABIEncoderV2;
contract BankController is Exponential, Initializable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Address for address;
struct Market {
address fTokenAddress;
bool isValid;
uint256 collateralAbility;
mapping(address => bool) accountsIn;
uint256 liquidationIncentive;
}
mapping(address => Market) public markets;
address public bankEntryAddress;
address public theForceToken;
mapping(uint256 => uint256) public rewardFactors; // RewardType ==> rewardFactor (1e18 scale);
mapping(address => IFToken[]) public accountAssets;
IFToken[] public allMarkets;
address[] public allUnderlyingMarkets;
IOracle public oracle;
address public mulsig;
modifier auth {
require(
msg.sender == admin || msg.sender == bankEntryAddress,
"msg.sender need admin or bank"
);
_;
}
function setBankEntryAddress(address _newBank) external auth {
bankEntryAddress = _newBank;
}
function marketsContains(address fToken) public view returns (bool) {
return allFtokenMarkets[fToken];
}
uint256 public closeFactor;
address public admin;
address public proposedAdmin;
address public rewardPool;
uint256 public transferEthGasCost;
// @notice Borrow caps enforced by borrowAllowed for each token address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint256) public borrowCaps;
// @notice Supply caps enforced by mintAllowed for each token address. Defaults to zero which corresponds to unlimited supplying.
mapping(address => uint256) public supplyCaps;
struct TokenConfig {
bool depositDisabled;
bool borrowDisabled;
bool withdrawDisabled;
bool repayDisabled;
bool liquidateBorrowDisabled;
}
//underlying => TokenConfig
mapping(address => TokenConfig) public tokenConfigs;
mapping(address => uint256) public underlyingLiquidationThresholds;
event SetLiquidationThreshold(
address indexed underlying,
uint256 threshold
);
bool private entered;
modifier nonReentrant() {
require(!entered, "re-entered");
entered = true;
_;
entered = false;
}
uint256 public flashloanFeeBips; // 9 for 0.0009
address public flashloanVault; // flash loan vault(recv flash loan fee);
event SetFlashloanParams(
address indexed sender,
uint256 bips,
address flashloanVault
);
// fToken => supported or not, using mapping to save gas instead of iterator array
mapping(address => bool) public allFtokenMarkets;
event SetAllFtokenMarkets(bytes data);
// fToken => exchangeUnit, to save gas instead of runtime calc
mapping(address => uint256) public allFtokenExchangeUnits;
// _setMarketBorrowSupplyCaps = _setMarketBorrowCaps + _setMarketSupplyCaps
function _setMarketBorrowSupplyCaps(
address[] calldata tokens,
uint256[] calldata newBorrowCaps,
uint256[] calldata newSupplyCaps
) external {
require(msg.sender == admin, "only admin can set borrow/supply caps");
uint256 numMarkets = tokens.length;
uint256 numBorrowCaps = newBorrowCaps.length;
uint256 numSupplyCaps = newSupplyCaps.length;
require(
numMarkets != 0 &&
numMarkets == numBorrowCaps &&
numMarkets == numSupplyCaps,
"invalid input"
);
for (uint256 i = 0; i < numMarkets; i++) {
borrowCaps[tokens[i]] = newBorrowCaps[i];
supplyCaps[tokens[i]] = newSupplyCaps[i];
}
}
function setTokenConfig(
address t,
bool _depositDisabled,
bool _borrowDisabled,
bool _withdrawDisabled,
bool _repayDisabled,
bool _liquidateBorrowDisabled
) external {
require(msg.sender == admin, "only admin can set token configs");
tokenConfigs[t] = TokenConfig(
_depositDisabled,
_borrowDisabled,
_withdrawDisabled,
_repayDisabled,
_liquidateBorrowDisabled
);
}
function setLiquidationThresolds(
address[] calldata underlyings,
uint256[] calldata _liquidationThresolds
) external onlyAdmin {
uint256 n = underlyings.length;
require(n == _liquidationThresolds.length && n >= 1, "length: wtf?");
for (uint256 i = 0; i < n; i++) {
uint256 ltv = markets[underlyings[i]].collateralAbility;
require(ltv <= _liquidationThresolds[i], "risk param error");
underlyingLiquidationThresholds[
underlyings[i]
] = _liquidationThresolds[i];
emit SetLiquidationThreshold(
underlyings[i],
_liquidationThresolds[i]
);
}
}
function setFlashloanParams(
uint256 _flashloanFeeBips,
address _flashloanVault
) external onlyAdmin {
require(
_flashloanFeeBips <= 10000 && _flashloanVault != address(0),
"flashloan param error"
);
flashloanFeeBips = _flashloanFeeBips;
flashloanVault = _flashloanVault;
emit SetFlashloanParams(msg.sender, _flashloanFeeBips, _flashloanVault);
}
function setAllFtokenMarkets(address[] calldata ftokens)
external
onlyAdmin
{
uint256 n = ftokens.length;
for (uint256 i = 0; i < n; i++) {
allFtokenMarkets[ftokens[i]] = true;
allFtokenExchangeUnits[ftokens[i]] = _calcExchangeUnit(ftokens[i]);
}
emit SetAllFtokenMarkets(abi.encode(ftokens));
}
function initialize(address _mulsig) public initializer {
admin = msg.sender;
mulsig = _mulsig;
transferEthGasCost = 5000;
}
modifier onlyMulSig {
require(msg.sender == mulsig, "require admin");
_;
}
modifier onlyAdmin {
require(msg.sender == admin, "require admin");
_;
}
modifier onlyFToken(address fToken) {
require(marketsContains(fToken), "only supported fToken");
_;
}
event AddTokenToMarket(address underlying, address fToken);
function proposeNewAdmin(address admin_) external onlyMulSig {
proposedAdmin = admin_;
}
function claimAdministration() external {
require(msg.sender == proposedAdmin, "Not proposed admin.");
admin = proposedAdmin;
proposedAdmin = address(0);
}
function getFTokeAddress(address underlying) public view returns (address) {
return markets[underlying].fTokenAddress;
}
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account)
external
view
returns (IFToken[] memory)
{
IFToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
function checkAccountsIn(address account, IFToken fToken)
external
view
returns (bool)
{
return
markets[IFToken(address(fToken)).underlying()].accountsIn[account];
}
function userEnterMarket(IFToken fToken, address borrower) internal {
Market storage marketToJoin = markets[fToken.underlying()];
require(marketToJoin.isValid, "Market not valid");
if (marketToJoin.accountsIn[borrower]) {
return;
}
marketToJoin.accountsIn[borrower] = true;
accountAssets[borrower].push(fToken);
}
function transferCheck(
address fToken,
address src,
address dst,
uint256 transferTokens
) external onlyFToken(msg.sender) {
withdrawCheck(fToken, src, transferTokens);
userEnterMarket(IFToken(fToken), dst);
}
function withdrawCheck(
address fToken,
address withdrawer,
uint256 withdrawTokens
) public view returns (uint256) {
address underlying = IFToken(fToken).underlying();
require(markets[underlying].isValid, "Market not valid");
require(
!tokenConfigs[underlying].withdrawDisabled,
"withdraw disabled"
);
(uint256 sumCollaterals, uint256 sumBorrows) =
getUserLiquidity(withdrawer, IFToken(fToken), withdrawTokens, 0);
require(sumCollaterals >= sumBorrows, "Cannot withdraw tokens");
}
function transferIn(
address account,
address underlying,
uint256 amount
) public payable nonReentrant {
require(
msg.sender == bankEntryAddress || msg.sender == account,
"auth failed"
);
if (underlying != EthAddressLib.ethAddress()) {
require(msg.value == 0, "ERC20 do not accecpt ETH.");
uint256 balanceBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(account, address(this), amount);
uint256 balanceAfter = IERC20(underlying).balanceOf(address(this));
require(
balanceAfter - balanceBefore == amount,
"TransferIn amount not valid"
);
// erc 20 => transferFrom
} else {
// payable
require(msg.value >= amount, "Eth value is not enough");
if (msg.value > amount) {
//send back excess ETH
uint256 excessAmount = msg.value.sub(amount);
//solium-disable-next-line
(bool result, ) =
account.call{value: excessAmount, gas: transferEthGasCost}(
""
);
require(result, "Transfer of ETH failed");
}
}
}
function transferToUser(
address underlying,
address payable account,
uint256 amount
) external onlyFToken(msg.sender) {
require(
markets[IFToken(msg.sender).underlying()].isValid,
"TransferToUser not allowed"
);
transferToUserInternal(underlying, account, amount);
}
function transferFlashloanAsset(
address underlying,
address payable account,
uint256 amount
) external {
require(msg.sender == bankEntryAddress, "only bank auth");
transferToUserInternal(underlying, account, amount);
}
function transferToUserInternal(
address underlying,
address payable account,
uint256 amount
) internal {
if (underlying != EthAddressLib.ethAddress()) {
// erc 20
// ERC20(token).safeTransfer(user, _amount);
IERC20(underlying).safeTransfer(account, amount);
} else {
(bool result, ) =
account.call{value: amount, gas: transferEthGasCost}("");
require(result, "Transfer of ETH failed");
}
}
function setTransferEthGasCost(uint256 _transferEthGasCost)
external
onlyAdmin
{
transferEthGasCost = _transferEthGasCost;
}
function getCashPrior(address underlying) public view returns (uint256) {
IFToken fToken = IFToken(getFTokeAddress(underlying));
return fToken.totalCash();
}
function getCashAfter(address underlying, uint256 transferInAmount)
external
view
returns (uint256)
{
return getCashPrior(underlying).add(transferInAmount);
}
function mintCheck(
address underlying,
address minter,
uint256 amount
) external {
require(marketsContains(msg.sender), "MintCheck fails");
require(markets[underlying].isValid, "Market not valid");
require(!tokenConfigs[underlying].depositDisabled, "deposit disabled");
uint256 supplyCap = supplyCaps[underlying];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint256 totalSupply = IFToken(msg.sender).totalSupply();
uint256 _exchangeRate = IFToken(msg.sender).exchangeRateStored();
uint256 totalUnderlyingSupply =
mulScalarTruncate(_exchangeRate, totalSupply);
uint256 nextTotalUnderlyingSupply =
totalUnderlyingSupply.add(amount);
require(
nextTotalUnderlyingSupply < supplyCap,
"market supply cap reached"
);
}
if (!markets[underlying].accountsIn[minter]) {
userEnterMarket(IFToken(getFTokeAddress(underlying)), minter);
}
}
function borrowCheck(
address account,
address underlying,
address fToken,
uint256 borrowAmount
) external {
require(
underlying == IFToken(msg.sender).underlying(),
"invalid underlying token"
);
require(markets[underlying].isValid, "BorrowCheck fails");
require(!tokenConfigs[underlying].borrowDisabled, "borrow disabled");
uint256 borrowCap = borrowCaps[underlying];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint256 totalBorrows = IFToken(msg.sender).totalBorrows();
uint256 nextTotalBorrows = totalBorrows.add(borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
require(markets[underlying].isValid, "Market not valid");
(, bool valid) = fetchAssetPrice(underlying);
require(valid, "Price is not valid");
if (!markets[underlying].accountsIn[account]) {
userEnterMarket(IFToken(getFTokeAddress(underlying)), account);
}
(uint256 sumCollaterals, uint256 sumBorrows) =
getUserLiquidity(account, IFToken(fToken), 0, borrowAmount);
require(sumBorrows > 0, "borrow value too low");
require(sumCollaterals >= sumBorrows, "insufficient liquidity");
}
function repayCheck(address underlying) external view {
require(markets[underlying].isValid, "Market not valid");
require(!tokenConfigs[underlying].repayDisabled, "repay disabled");
}
function getTotalDepositAndBorrow(address account)
public
view
returns (uint256, uint256)
{
return getUserLiquidity(account, IFToken(0), 0, 0);
}
function getAccountLiquidity(address account)
public
view
returns (uint256 liquidity, uint256 shortfall)
{
(uint256 sumCollaterals, uint256 sumBorrows) =
getTotalDepositAndBorrow(account);
// These are safe, as the underflow condition is checked first
if (sumCollaterals > sumBorrows) {
return (sumCollaterals - sumBorrows, 0);
} else {
return (0, sumBorrows - sumCollaterals);
}
}
// Get price of oracle
function fetchAssetPrice(address token)
public
view
returns (uint256, bool)
{
require(address(oracle) != address(0), "oracle not set");
return oracle.get(token);
}
function setOracle(address _oracle) external onlyAdmin {
oracle = IOracle(_oracle);
}
function _supportMarket(
IFToken fToken,
uint256 _collateralAbility,
uint256 _liquidationIncentive
) external onlyAdmin {
address underlying = fToken.underlying();
require(!markets[underlying].isValid, "martket existed");
require(tokenDecimals(underlying) <= 18, "unsupported token decimals");
markets[underlying] = Market({
isValid: true,
collateralAbility: _collateralAbility,
fTokenAddress: address(fToken),
liquidationIncentive: _liquidationIncentive
});
addTokenToMarket(underlying, address(fToken));
allFtokenMarkets[address(fToken)] = true;
allFtokenExchangeUnits[address(fToken)] = _calcExchangeUnit(
address(fToken)
);
}
function addTokenToMarket(address underlying, address fToken) internal {
for (uint256 i = 0; i < allUnderlyingMarkets.length; i++) {
require(allUnderlyingMarkets[i] != underlying, "token exists");
require(allMarkets[i] != IFToken(fToken), "token exists");
}
allMarkets.push(IFToken(fToken));
allUnderlyingMarkets.push(underlying);
emit AddTokenToMarket(underlying, fToken);
}
function _setCollateralAbility(
address[] calldata underlyings,
uint256[] calldata newCollateralAbilities,
uint256[] calldata _liquidationIncentives
) external onlyAdmin {
uint256 n = underlyings.length;
require(
n == newCollateralAbilities.length &&
n == _liquidationIncentives.length &&
n >= 1,
"invalid length"
);
for (uint256 i = 0; i < n; i++) {
address u = underlyings[i];
require(markets[u].isValid, "Market not valid");
Market storage market = markets[u];
market.collateralAbility = newCollateralAbilities[i];
market.liquidationIncentive = _liquidationIncentives[i];
}
}
function setCloseFactor(uint256 _closeFactor) external onlyAdmin {
closeFactor = _closeFactor;
}
function setMarketIsValid(address underlying, bool isValid)
external
onlyAdmin
{
Market storage market = markets[underlying];
market.isValid = isValid;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() external view returns (IFToken[] memory) {
return allMarkets;
}
function seizeCheck(address fTokenCollateral, address fTokenBorrowed)
external
view
{
require(!IBank(bankEntryAddress).paused(), "system paused!");
require(
markets[IFToken(fTokenCollateral).underlying()].isValid &&
markets[IFToken(fTokenBorrowed).underlying()].isValid &&
marketsContains(fTokenCollateral) &&
marketsContains(fTokenBorrowed),
"Seize market not valid"
);
}
struct LiquidityLocals {
uint256 sumCollateral;
uint256 sumBorrows;
uint256 fTokenBalance;
uint256 borrowBalance;
uint256 exchangeRate;
uint256 oraclePrice;
uint256 collateralAbility;
uint256 collateral;
}
function getUserLiquidity(
address account,
IFToken fTokenNow,
uint256 withdrawTokens,
uint256 borrowAmount
) public view returns (uint256, uint256) {
IFToken[] memory assets = accountAssets[account];
LiquidityLocals memory vars;
for (uint256 i = 0; i < assets.length; i++) {
IFToken asset = assets[i];
(vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset
.getAccountState(account);
vars.collateralAbility = markets[asset.underlying()]
.collateralAbility;
(uint256 oraclePrice, bool valid) =
fetchAssetPrice(asset.underlying());
require(valid, "Price is not valid");
vars.oraclePrice = oraclePrice;
uint256 fixUnit = calcExchangeUnit(address(asset));
uint256 exchangeRateFixed = mulScalar(vars.exchangeRate, fixUnit);
vars.collateral = mulExp3(
vars.collateralAbility,
exchangeRateFixed,
vars.oraclePrice
);
vars.sumCollateral = mulScalarTruncateAddUInt(
vars.collateral,
vars.fTokenBalance,
vars.sumCollateral
);
vars.borrowBalance = vars.borrowBalance.mul(fixUnit);
vars.borrowBalance = vars.borrowBalance.mul(1e18).div(
vars.collateralAbility
);
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrows
);
if (asset == fTokenNow) {
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.collateral,
withdrawTokens,
vars.sumBorrows
);
borrowAmount = borrowAmount.mul(fixUnit);
borrowAmount = borrowAmount.mul(1e18).div(
vars.collateralAbility
);
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrows
);
}
}
return (vars.sumCollateral, vars.sumBorrows);
}
struct HealthFactorLocals {
uint256 sumLiquidity;
uint256 sumLiquidityPlusThreshold;
uint256 sumBorrows;
uint256 fTokenBalance;
uint256 borrowBalance;
uint256 exchangeRate;
uint256 oraclePrice;
uint256 liquidationThreshold;
uint256 liquidity;
uint256 liquidityPlusThreshold;
}
function getHealthFactor(address account)
public
view
returns (uint256 healthFactor)
{
IFToken[] memory assets = accountAssets[account];
HealthFactorLocals memory vars;
uint256 _healthFactor = uint256(-1);
for (uint256 i = 0; i < assets.length; i++) {
IFToken asset = assets[i];
address underlying = asset.underlying();
(vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset
.getAccountState(account);
vars.liquidationThreshold = underlyingLiquidationThresholds[
underlying
];
(uint256 oraclePrice, bool valid) = fetchAssetPrice(underlying);
require(valid, "Price is not valid");
vars.oraclePrice = oraclePrice;
uint256 fixUnit = calcExchangeUnit(address(asset));
uint256 exchangeRateFixed = mulScalar(vars.exchangeRate, fixUnit);
vars.liquidityPlusThreshold = mulExp3(
vars.liquidationThreshold,
exchangeRateFixed,
vars.oraclePrice
);
vars.sumLiquidityPlusThreshold = mulScalarTruncateAddUInt(
vars.liquidityPlusThreshold,
vars.fTokenBalance,
vars.sumLiquidityPlusThreshold
);
vars.borrowBalance = vars.borrowBalance.mul(fixUnit);
vars.borrowBalance = vars.borrowBalance.mul(1e18).div(
vars.liquidationThreshold
);
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrows
);
}
if (vars.sumBorrows > 0) {
_healthFactor = divExp(
vars.sumLiquidityPlusThreshold,
vars.sumBorrows
);
}
return _healthFactor;
}
function tokenDecimals(address token) public view returns (uint256) {
return
token == EthAddressLib.ethAddress()
? 18
: uint256(IERC20(token).decimals());
}
function isFTokenValid(address fToken) external view returns (bool) {
return markets[IFToken(fToken).underlying()].isValid;
}
function liquidateBorrowCheck(
address fTokenBorrowed,
address fTokenCollateral,
address borrower,
address liquidator,
uint256 repayAmount
) external onlyFToken(msg.sender) {
address underlyingBorrowed = IFToken(fTokenBorrowed).underlying();
address underlyingCollateral = IFToken(fTokenCollateral).underlying();
require(
!tokenConfigs[underlyingBorrowed].liquidateBorrowDisabled,
"liquidateBorrow: liquidate borrow disabled"
);
require(
!tokenConfigs[underlyingCollateral].liquidateBorrowDisabled,
"liquidateBorrow: liquidate colleteral disabled"
);
uint256 hf = getHealthFactor(borrower);
require(hf < 1e18, "HealthFactor > 1");
userEnterMarket(IFToken(fTokenCollateral), liquidator);
uint256 borrowBalance =
IFToken(fTokenBorrowed).borrowBalanceStored(borrower);
uint256 maxClose = mulScalarTruncate(closeFactor, borrowBalance);
require(repayAmount <= maxClose, "Too much repay");
}
function _calcExchangeUnit(address fToken) internal view returns (uint256) {
uint256 fTokenDecimals = uint256(IFToken(fToken).decimals());
uint256 underlyingDecimals =
tokenDecimals(IFToken(fToken).underlying());
return 10**SafeMath.abs(fTokenDecimals, underlyingDecimals);
}
function calcExchangeUnit(address fToken) public view returns (uint256) {
return allFtokenExchangeUnits[fToken];
}
function liquidateTokens(
address fTokenBorrowed,
address fTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256) {
(uint256 borrowPrice, bool borrowValid) =
fetchAssetPrice(IFToken(fTokenBorrowed).underlying());
(uint256 collateralPrice, bool collateralValid) =
fetchAssetPrice(IFToken(fTokenCollateral).underlying());
require(borrowValid && collateralValid, "Price not valid");
/*
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint256 exchangeRate = IFToken(fTokenCollateral).exchangeRateStored();
uint256 fixCollateralUnit = calcExchangeUnit(fTokenCollateral);
uint256 fixBorrowlUnit = calcExchangeUnit(fTokenBorrowed);
uint256 numerator =
mulExp(
markets[IFToken(fTokenCollateral).underlying()]
.liquidationIncentive,
borrowPrice
);
exchangeRate = exchangeRate.mul(fixCollateralUnit);
actualRepayAmount = actualRepayAmount.mul(fixBorrowlUnit);
uint256 denominator = mulExp(collateralPrice, exchangeRate);
uint256 seizeTokens =
mulScalarTruncate(
divExp(numerator, denominator),
actualRepayAmount
);
return seizeTokens;
}
struct ReserveWithdrawalLogStruct {
address token_address;
uint256 reserve_withdrawed;
uint256 cheque_token_value;
uint256 loan_interest_rate;
uint256 global_token_reserved;
}
function reduceReserves(
address underlying,
address payable account,
uint256 reduceAmount
) public onlyMulSig {
IFToken fToken = IFToken(getFTokeAddress(underlying));
fToken._reduceReserves(reduceAmount);
transferToUserInternal(underlying, account, reduceAmount);
fToken.subTotalCash(reduceAmount);
ReserveWithdrawalLogStruct memory rds =
ReserveWithdrawalLogStruct(
underlying,
reduceAmount,
fToken.exchangeRateStored(),
fToken.getBorrowRate(),
fToken.tokenCash(underlying, address(this))
);
IBank(bankEntryAddress).MonitorEventCallback(
"ReserveWithdrawal",
abi.encode(rds)
);
}
function batchReduceReserves(
address[] calldata underlyings,
address payable account,
uint256[] calldata reduceAmounts
) external onlyMulSig {
require(underlyings.length == reduceAmounts.length, "length not match");
uint256 n = underlyings.length;
for (uint256 i = 0; i < n; i++) {
reduceReserves(underlyings[i], account, reduceAmounts[i]);
}
}
function batchReduceAllReserves(
address[] calldata underlyings,
address payable account
) external onlyMulSig {
uint256 n = underlyings.length;
for (uint256 i = 0; i < n; i++) {
IFToken fToken = IFToken(getFTokeAddress(underlyings[i]));
uint256 amount =
SafeMath.min(
fToken.totalReserves(),
fToken.tokenCash(underlyings[i], address(this))
);
if (amount > 0) {
reduceReserves(underlyings[i], account, amount);
}
}
}
function batchReduceAllReserves(address payable account)
external
onlyMulSig
{
uint256 n = allUnderlyingMarkets.length;
for (uint256 i = 0; i < n; i++) {
address underlying = allUnderlyingMarkets[i];
IFToken fToken = IFToken(getFTokeAddress(underlying));
uint256 amount =
SafeMath.min(
fToken.totalReserves(),
fToken.tokenCash(underlying, address(this))
);
if (amount > 0) {
reduceReserves(underlying, account, amount);
}
}
}
struct ReserveDepositLogStruct {
address token_address;
uint256 reserve_funded;
uint256 cheque_token_value;
uint256 loan_interest_rate;
uint256 global_token_reserved;
}
function balance(address token) external view returns (uint256) {
if (token == EthAddressLib.ethAddress()) {
return address(this).balance;
}
return IERC20(token).balanceOf(address(this));
}
/**
* @dev receive function enforces that the caller is a contract, to support flashloan transfers
**/
receive() external payable {
//only contracts can send ETH to the bank controller
require(
address(msg.sender).isContract(),
"Only contracts can send ether to the bank controller"
);
}
} | erc 20 => transferFrom payablesend back excess ETHsolium-disable-next-line | function transferIn(
address account,
address underlying,
uint256 amount
) public payable nonReentrant {
require(
msg.sender == bankEntryAddress || msg.sender == account,
"auth failed"
);
if (underlying != EthAddressLib.ethAddress()) {
require(msg.value == 0, "ERC20 do not accecpt ETH.");
uint256 balanceBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(account, address(this), amount);
uint256 balanceAfter = IERC20(underlying).balanceOf(address(this));
require(
balanceAfter - balanceBefore == amount,
"TransferIn amount not valid"
);
require(msg.value >= amount, "Eth value is not enough");
if (msg.value > amount) {
uint256 excessAmount = msg.value.sub(amount);
(bool result, ) =
""
);
require(result, "Transfer of ETH failed");
}
}
}
| 7,676,447 | [
1,
12610,
4200,
516,
7412,
1265,
8843,
1538,
409,
1473,
23183,
512,
2455,
18281,
5077,
17,
8394,
17,
4285,
17,
1369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
382,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
1758,
6808,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
1071,
8843,
429,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
11218,
1622,
1887,
747,
1234,
18,
15330,
422,
2236,
16,
203,
5411,
315,
1944,
2535,
6,
203,
3639,
11272,
203,
3639,
309,
261,
9341,
6291,
480,
512,
451,
1887,
5664,
18,
546,
1887,
10756,
288,
203,
5411,
2583,
12,
3576,
18,
1132,
422,
374,
16,
315,
654,
39,
3462,
741,
486,
1721,
27832,
337,
512,
2455,
1199,
1769,
203,
5411,
2254,
5034,
11013,
4649,
273,
467,
654,
39,
3462,
12,
9341,
6291,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
467,
654,
39,
3462,
12,
9341,
6291,
2934,
4626,
5912,
1265,
12,
4631,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
5411,
2254,
5034,
11013,
4436,
273,
467,
654,
39,
3462,
12,
9341,
6291,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
2583,
12,
203,
7734,
11013,
4436,
300,
11013,
4649,
422,
3844,
16,
203,
7734,
315,
5912,
382,
3844,
486,
923,
6,
203,
5411,
11272,
203,
5411,
2583,
12,
3576,
18,
1132,
1545,
3844,
16,
315,
41,
451,
460,
353,
486,
7304,
8863,
203,
5411,
309,
261,
3576,
18,
1132,
405,
3844,
13,
288,
203,
7734,
2254,
5034,
23183,
6275,
273,
1234,
18,
1132,
18,
1717,
12,
8949,
1769,
203,
7734,
261,
6430,
563,
16,
262,
273,
203,
13491,
1408,
203,
10792,
11272,
203,
7734,
2583,
12,
2088,
2
] |
./full_match/43113/0xA938608cb6189309e36dC935F91D5A538bF0B815/sources/contracts/ico.sol | * Event for token purchase logging @param purchaser who paid for the tokens @param beneficiary who got the tokens @param value weis paid for purchase @param amount amount of tokens purchased/* @param usdwei Wei price of 1 USD @param wallet Address where collected funds will be forwarded to @param tokenSalePrice price of 1 token in USD cents, e.g. 90 = $0.90 @param token Address of the token being sold/ | constructor (uint256 usdwei, address payable wallet, IERC20 token, uint256 tokenSalePrice) public {
require(usdwei > 0, "Crowdsale: USD wei price is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_usdwei = usdwei;
_tokenprice_in_cents = tokenSalePrice;
_wallet = wallet;
_token = token;
}
| 7,109,042 | [
1,
1133,
364,
1147,
23701,
2907,
225,
5405,
343,
14558,
10354,
30591,
364,
326,
2430,
225,
27641,
74,
14463,
814,
10354,
2363,
326,
2430,
225,
460,
732,
291,
30591,
364,
23701,
225,
3844,
3844,
434,
2430,
5405,
343,
8905,
19,
225,
584,
72,
1814,
77,
1660,
77,
6205,
434,
404,
587,
9903,
225,
9230,
5267,
1625,
12230,
284,
19156,
903,
506,
19683,
358,
225,
1147,
30746,
5147,
6205,
434,
404,
1147,
316,
587,
9903,
276,
4877,
16,
425,
18,
75,
18,
8566,
273,
271,
20,
18,
9349,
225,
1147,
5267,
434,
326,
1147,
3832,
272,
1673,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
3885,
261,
11890,
5034,
584,
72,
1814,
77,
16,
1758,
8843,
429,
9230,
16,
467,
654,
39,
3462,
1147,
16,
2254,
5034,
1147,
30746,
5147,
13,
1071,
288,
203,
3639,
2583,
12,
407,
72,
1814,
77,
405,
374,
16,
315,
39,
492,
2377,
5349,
30,
587,
9903,
732,
77,
6205,
353,
374,
8863,
203,
3639,
2583,
12,
19177,
480,
1758,
12,
20,
3631,
315,
39,
492,
2377,
5349,
30,
9230,
353,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
2867,
12,
2316,
13,
480,
1758,
12,
20,
3631,
315,
39,
492,
2377,
5349,
30,
1147,
353,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
407,
72,
1814,
77,
273,
584,
72,
1814,
77,
31,
203,
3639,
389,
2316,
8694,
67,
267,
67,
2998,
87,
273,
1147,
30746,
5147,
31,
203,
3639,
389,
19177,
273,
9230,
31,
203,
3639,
389,
2316,
273,
1147,
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
] |
pragma solidity >=0.4.20 <0.7;
library BigNumber {
/*
* BigNumber is defined as a struct named 'instance' to avoid naming conflicts.
* DO NOT ALLOW INSTANTIATING THIS DIRECTLY - use the '_new' functions defined below.
* Hoping in future Solidity will allow visibility modifiers on structs..
*/
struct instance {
bytes val;
bool neg;
uint bitlen;
}
/** @dev _new: Create a new Bignumber instance.
* overloading allows caller to obtionally pass bitlen where it is known - as it is cheaper to do off-chain and verify on-chain.
* we assert input is in data structure as defined above, and that bitlen, if passed, is correct.
* 'copy' parameter indicates whether or not to copy the contents of val to a new location in memory (for example where you pass the contents of another variable's value in)
* parameter: bytes val - bignum value.
* parameter: bool neg - sign of value
* parameter: uint bitlen - bit length of value
* returns: instance r.
*/
function _new(bytes memory val, bool neg, bool copy) internal view returns(instance memory r){
require(val.length % 32 == 0);
if(!copy) {
r.val = val;
}
else {
// use identity at location 0x4 for cheap memcpy.
// grab contents of val, load starting from memory end, update memory end pointer.
bytes memory val_copy;
assembly{
let size := add(mload(val),0x20)
let new_loc := mload(0x40)
let success := staticcall(450, 0x4, val, size, new_loc, size) // (gas, address, in, insize, out, outsize)
val_copy := new_loc //new bytes value
mstore(0x40, add(new_loc,size)) //update freemem pointer
}
r.val = val_copy;
}
r.neg = neg;
r.bitlen = get_bit_length(val);
}
/** @dev Create a new Bignumber instance.
*
* parameter: bytes val - bignum value
* parameter: bool neg - sign of value
* parameter: uint bitlen - bit length of value
* returns: instance r.
*/
function _new(bytes memory val, bool neg, uint bitlen) internal pure returns(instance memory r){
uint val_msword;
assembly {val_msword := mload(add(val,0x20))} //get msword of result
require((val.length % 32 == 0) && (val_msword>>(bitlen%256)==1));
r.val = val;
r.neg = neg;
r.bitlen = bitlen;
}
/** @dev prepare_add: Initially prepare bignum instances for addition operation; internally calls actual addition/subtraction, depending on inputs.
* In order to do correct addition or subtraction we have to handle the sign.
* This function discovers the sign of the result based on the inputs, and calls the correct operation.
*
* parameter: instance a - first instance
* parameter: instance b - second instance
* returns: instance r - addition of a & b.
*/
function prepare_add(instance memory a, instance memory b) internal pure returns(instance memory r) {
instance memory zero = instance(hex"0000000000000000000000000000000000000000000000000000000000000000",false,0);
if(a.bitlen==0 && b.bitlen==0) return zero;
if(a.bitlen==0) return b;
if(b.bitlen==0) return a;
bytes memory val;
uint bitlen;
int compare = cmp(a,b,false);
if(a.neg || b.neg){
if(a.neg && b.neg){
if(compare>=0) (val, bitlen) = bn_add(a.val,b.val,a.bitlen);
else (val, bitlen) = bn_add(b.val,a.val,b.bitlen);
r.neg = true;
}
else {
if(compare==1){
(val, bitlen) = bn_sub(a.val,b.val);
r.neg = a.neg;
}
else if(compare==-1){
(val, bitlen) = bn_sub(b.val,a.val);
r.neg = !a.neg;
}
else return zero;//one pos and one neg, and same value.
}
}
else{
if(compare>=0){ //a>=b
(val, bitlen) = bn_add(a.val,b.val,a.bitlen);
}
else {
(val, bitlen) = bn_add(b.val,a.val,b.bitlen);
}
r.neg = false;
}
r.val = val;
r.bitlen = bitlen;
}
/** @dev bn_add: takes two instance values and the bitlen of the max value, and adds them.
* This function is private and only callable from prepare_add: therefore the values may be of different sizes,
* in any order of size, and of different signs (handled in prepare_add).
* As values may be of different sizes, inputs are considered starting from the least significant words, working back.
* The function calculates the new bitlen (basically if bitlens are the same for max and min, max_bitlen++) and returns a new instance value.
*
* parameter: bytes max - biggest value (determined from prepare_add)
* parameter: bytes min - smallest value (determined from prepare_add)
* parameter: uint max_bitlen - bit length of max value.
* returns: bytes result - max + min.
* returns: uint - bit length of result.
*/
function bn_add(bytes memory max, bytes memory min, uint max_bitlen) private pure returns (bytes memory, uint) {
bytes memory result;
assembly {
let result_start := msize() // Get the highest available block of memory
let uint_max := sub(0,1) // uint max. achieved using uint underflow: 0xffff...ffff
let carry := 0
let max_ptr := add(max, mload(max))
let min_ptr := add(min, mload(min)) // point to last word of each byte array.
let result_ptr := add(add(result_start,0x20), mload(max)) // set result_ptr end.
for { let i := mload(max) } eq(eq(i,0),0) { i := sub(i, 0x20) } { // for(int i=max_length; i!=0; i-=32)
let max_val := mload(max_ptr) // get next word for 'max'
switch gt(i,sub(mload(max),mload(min))) // if(i>(max_length-min_length)). while 'min' words are still available.
case 1{
let min_val := mload(min_ptr) // get next word for 'min'
mstore(result_ptr, add(add(max_val,min_val),carry)) // result_word = max_word+min_word+carry
switch gt(max_val, sub(uint_max,sub(min_val,carry))) // this switch block finds whether or not to set the carry bit for the next iteration.
case 1 { carry := 1 }
default {
switch and(eq(max_val,uint_max),or(gt(carry,0), gt(min_val,0)))
case 1 { carry := 1 }
default{ carry := 0 }
}
min_ptr := sub(min_ptr,0x20) // point to next 'min' word
}
default{ // else: remainder after 'min' words are complete.
mstore(result_ptr, add(max_val,carry)) // result_word = max_word+carry
switch and( eq(uint_max,max_val), eq(carry,1) ) // this switch block finds whether or not to set the carry bit for the next iteration.
case 1 { carry := 1 }
default { carry := 0 }
}
result_ptr := sub(result_ptr,0x20) // point to next 'result' word
max_ptr := sub(max_ptr,0x20) // point to next 'max' word
}
switch eq(carry,0)
case 1{ result_start := add(result_start,0x20) } // if carry is 0, increment result_start, ie. length word for result is now one word position ahead.
default { mstore(result_ptr, 1) } // else if carry is 1, store 1; overflow has occured, so length word remains in the same position.
result := result_start // point 'result' bytes value to the correct address in memory
mstore(result,add(mload(max),mul(0x20,carry))) // store length of result. we are finished with the byte array.
mstore(0x40, add(result,add(mload(result),0x20))) // Update freemem pointer to point to new end of memory.
}
//we now calculate the result's bit length.
//with addition, if we assume that some a is at least equal to some b, then the resulting bit length will be a's bit length or (a's bit length)+1, depending on carry bit.
//this is cheaper than calling get_bit_length.
uint msword;
assembly {msword := mload(add(result,0x20))} // get most significant word of result
if(msword>>(max_bitlen % 256)==1 || msword==1) ++max_bitlen; // if msword's bit length is 1 greater than max_bitlen, OR overflow occured, new bitlen is max_bitlen+1.
return (result, max_bitlen);
}
/** @dev prepare_sub: Initially prepare bignum instances for addition operation; internally calls actual addition/subtraction, depending on inputs.
* In order to do correct addition or subtraction we have to handle the sign.
* This function discovers the sign of the result based on the inputs, and calls the correct operation.
*
* parameter: instance a - first instance
* parameter: instance b - second instance
* returns: instance r - a-b.
*/
function prepare_sub(instance memory a, instance memory b) internal pure returns(instance memory r) {
instance memory zero = instance(hex"0000000000000000000000000000000000000000000000000000000000000000",false,0);
bytes memory val;
int compare;
uint bitlen;
compare = cmp(a,b,false);
if(a.neg || b.neg) {
if(a.neg && b.neg){
if(compare == 1) {
(val,bitlen) = bn_sub(a.val,b.val);
r.neg = true;
}
else if(compare == -1) {
(val,bitlen) = bn_sub(b.val,a.val);
r.neg = false;
}
else return zero;
}
else {
if(compare >= 0) (val,bitlen) = bn_add(a.val,b.val,a.bitlen);
else (val,bitlen) = bn_add(b.val,a.val,b.bitlen);
r.neg = (a.neg) ? true : false;
}
}
else {
if(compare == 1) {
(val,bitlen) = bn_sub(a.val,b.val);
r.neg = false;
}
else if(compare == -1) {
(val,bitlen) = bn_sub(b.val,a.val);
r.neg = true;
}
else return zero;
}
r.val = val;
r.bitlen = bitlen;
}
/** @dev bn_sub: takes two instance values and subtracts them.
* This function is private and only callable from prepare_add: therefore the values may be of different sizes,
* in any order of size, and of different signs (handled in prepare_add).
* As values may be of different sizes, inputs are considered starting from the least significant words, working back.
* The function calculates the new bitlen (basically if bitlens are the same for max and min, max_bitlen++) and returns a new instance value.
*
* parameter: bytes max - biggest value (determined from prepare_add)
* parameter: bytes min - smallest value (determined from prepare_add)
* parameter: uint max_bitlen - bit length of max value.
* returns: bytes result - max + min.
* returns: uint - bit length of result.
*/
function bn_sub(bytes memory max, bytes memory min) private pure returns (bytes memory, uint) {
bytes memory result;
uint carry = 0;
assembly {
let result_start := msize() // Get the highest available block of memory
let uint_max := sub(0,1) // uint max. achieved using uint underflow: 0xffff...ffff
let max_len := mload(max)
let min_len := mload(min) // load lengths of inputs
let len_diff := sub(max_len,min_len) //get differences in lengths.
let max_ptr := add(max, max_len)
let min_ptr := add(min, min_len) //go to end of arrays
let result_ptr := add(result_start, max_len) //point to least significant result word.
let memory_end := add(result_ptr,0x20) // save memory_end to update free memory pointer at the end.
for { let i := max_len } eq(eq(i,0),0) { i := sub(i, 0x20) } { // for(int i=max_length; i!=0; i-=32)
let max_val := mload(max_ptr) // get next word for 'max'
switch gt(i,len_diff) // if(i>(max_length-min_length)). while 'min' words are still available.
case 1{
let min_val := mload(min_ptr) // get next word for 'min'
mstore(result_ptr, sub(sub(max_val,min_val),carry)) // result_word = (max_word-min_word)-carry
switch or(lt(max_val, add(min_val,carry)),
and(eq(min_val,uint_max), eq(carry,1))) // this switch block finds whether or not to set the carry bit for the next iteration.
case 1 { carry := 1 }
default { carry := 0 }
min_ptr := sub(min_ptr,0x20) // point to next 'result' word
}
default{ // else: remainder after 'min' words are complete.
mstore(result_ptr, sub(max_val,carry)) // result_word = max_word-carry
switch and( eq(max_val,0), eq(carry,1) ) // this switch block finds whether or not to set the carry bit for the next iteration.
case 1 { carry := 1 }
default { carry := 0 }
}
result_ptr := sub(result_ptr,0x20) // point to next 'result' word
max_ptr := sub(max_ptr,0x20) // point to next 'max' word
}
//the following code removes any leading words containing all zeroes in the result.
result_ptr := add(result_ptr,0x20)
for { } eq(mload(result_ptr), 0) { result_ptr := add(result_ptr,0x20) } { //for(result_ptr+=32;; result==0; result_ptr+=32)
result_start := add(result_start, 0x20) // push up the start pointer for the result..
max_len := sub(max_len,0x20) // and subtract a word (32 bytes) from the result length.
}
result := result_start // point 'result' bytes value to the correct address in memory
mstore(result,max_len) // store length of result. we are finished with the byte array.
mstore(0x40, memory_end) // Update freemem pointer.
}
uint new_bitlen = get_bit_length(result); //calculate the result's bit length.
return (result, new_bitlen);
}
/** @dev bn_mul: takes two instances and multiplys them. Order is irrelevant.
* multiplication achieved using modexp precompile:
* (a * b) = (((a + b)**2 - (a - b)**2) / 4
* squaring is done in op_and_square function.
*
* parameter: instance a
* parameter: instance b
* returns: bytes res - a*b.
*/
function bn_mul(instance memory a, instance memory b) internal view returns(instance memory res){
res = op_and_square(a,b,0); // add_and_square = (a+b)^2
//no need to do subtraction part of the equation if a == b; if so, it has no effect on final result.
if(cmp(a,b,true)!=0){
instance memory sub_and_square = op_and_square(a,b,1); // sub_and_square = (a-b)^2
res = prepare_sub(res,sub_and_square); // res = add_and_square - sub_and_square
}
res = right_shift(res, 2); // res = res / 4
}
/** @dev op_and_square: takes two instances, performs operation 'op' on them, and squares the result.
* bn_mul uses the multiplication by squaring method, ie. a*b == ((a+b)^2 - (a-b)^2)/4.
* using modular exponentation precompile for squaring. this requires taking a special modulus value of the form:
* modulus == '1|(0*n)', where n = 2 * bit length of (a 'op' b).
*
* parameter: instance a
* parameter: instance b
* parameter: int op
* returns: bytes res - (a'op'b) ^ 2.
*/
function op_and_square(instance memory a, instance memory b, int op) private view returns(instance memory res){
instance memory two = instance(hex"0000000000000000000000000000000000000000000000000000000000000002",false,2);
uint mod_index = 0;
uint first_word_modulus;
bytes memory _modulus;
res = (op == 0) ? prepare_add(a,b) : prepare_sub(a,b); //op == 0: add, op == 1: sub.
uint res_bitlen = res.bitlen;
assembly { mod_index := mul(res_bitlen,2) }
first_word_modulus = uint(1) << ((mod_index % 256)); //set bit in first modulus word.
//we pass the minimum modulus value which would return JUST the squaring part of the calculation; therefore the value may be many words long.
//This is done by:
// - storing total modulus byte length
// - storing first word of modulus with correct bit set
// - updating the free memory pointer to come after total length.
_modulus = hex"0000000000000000000000000000000000000000000000000000000000000000";
assembly {
mstore(_modulus, mul(add(div(mod_index,256),1),0x20)) //store length of modulus
mstore(add(_modulus,0x20), first_word_modulus) //set first modulus word
mstore(0x40, add(_modulus, add(mload(_modulus),0x20))) //update freemem pointer to be modulus index + length
}
//create modulus instance for modexp function
instance memory modulus;
modulus.val = _modulus;
modulus.neg = false;
modulus.bitlen = mod_index;
res = prepare_modexp(res,two,modulus); // ((a 'op' b) ^ 2 % modulus) == (a 'op' b) ^ 2.
}
/** @dev bn_div: takes three instances (a,b and result), and verifies that a/b == result.
* Verifying a bigint division operation is far cheaper than actually doing the computation.
* As this library is for verification of cryptographic schemes it makes more sense that this function be used in this way.
* (a/b = result) == (a = b * result)
* Integer division only; therefore:
* verify ((b*result) + (a % (b*result))) == a.
* eg. 17/7 == 2:
* verify (7*2) + (17 % (7*2)) == 17.
* the function returns the 'result' param passed on successful validation. returning a bool on successful validation is an option,
* however it makes more sense in the context of the calling contract that it should return the result.
*
* parameter: instance a
* parameter: instance b
* parameter: instance result
* returns: 'result' param.
*/
function bn_div(instance memory a, instance memory b, instance memory result) internal view returns(instance memory){
if(a.neg==true || b.neg==true){ //first handle sign.
if (a.neg==true && b.neg==true) require(result.neg==false);
else require(result.neg==true);
} else require(result.neg==false);
instance memory zero = instance(hex"0000000000000000000000000000000000000000000000000000000000000000",false,0);
require(!(cmp(b,zero,true)==0)); //require denominator to not be zero.
if(cmp(result,zero,true)==0){ //if result is 0:
if(cmp(a,b,true)==-1) return result; // return zero if a<b (numerator < denominator)
else assert(false); // else fail.
}
instance memory fst = bn_mul(b,result); // do multiplication (b * result)
if(cmp(fst,a,true)==0) return result; // check if we already have a (ie. no remainder after division). if so, no mod necessary, and return result.
instance memory one = instance(hex"0000000000000000000000000000000000000000000000000000000000000001",false,1);
instance memory snd = prepare_modexp(a,one,fst); //a mod (b*result)
require(cmp(prepare_add(fst,snd),a,true)==0); // ((b*result) + a % (b*result)) == a
return result;
}
function bn_mod(instance memory a, instance memory mod) internal view returns(instance memory res){
instance memory one = instance(hex"0000000000000000000000000000000000000000000000000000000000000001",false,1);
res = prepare_modexp(a,one,mod);
}
/** @dev prepare_modexp: takes base, exponent, and modulus, internally computes base^exponent % modulus, and creates new instance.
* this function is overloaded: it assumes the exponent is positive. if not, the other method is used, whereby the inverse of the base is also passed.
*
* parameter: instance base
* parameter: instance exponent
* parameter: instance modulus
* returns: instance result.
*/
function prepare_modexp(instance memory base, instance memory exponent, instance memory modulus) internal view returns(instance memory result) {
require(exponent.neg==false); //if exponent is negative, other method with this same name should be used.
bytes memory _result = modexp(base.val,exponent.val,modulus.val);
//get bitlen of result (TODO: optimise. we know bitlen is in the same byte as the modulus bitlen byte)
uint bitlen;
assembly { bitlen := mload(add(_result,0x20))}
bitlen = get_word_length(bitlen) + (((_result.length/32)-1)*256);
result.val = _result;
result.neg = (base.neg==false || base.neg && is_odd(exponent)==0) ? false : true; //TODO review this.
result.bitlen = bitlen;
return result;
}
/** @dev prepare_modexp: takes base, base inverse, exponent, and modulus, asserts inverse(base)==base inverse,
* internally computes base_inverse^exponent % modulus and creates new instance.
* this function is overloaded: it assumes the exponent is negative.
* if not, the other method is used, where the inverse of the base is not passed.
*
* parameter: instance base
* parameter: instance base_inverse
* parameter: instance exponent
* parameter: instance modulus
* returns: instance result.
*/
function prepare_modexp(instance memory base, instance memory base_inverse, instance memory exponent, instance memory modulus) internal view returns(instance memory result) {
// base^-exp = (base^-1)^exp
require(exponent.neg==true);
require(cmp(base_inverse, mod_inverse(base,modulus,base_inverse), true)==0); //assert base_inverse == inverse(base, modulus)
exponent.neg = false; //make e positive
bytes memory _result = modexp(base_inverse.val,exponent.val,modulus.val);
//get bitlen of result (TODO: optimise. we know bitlen is in the same byte as the modulus bitlen byte)
uint bitlen;
assembly { bitlen := mload(add(_result,0x20))}
bitlen = get_word_length(bitlen) + (((_result.length/32)-1)*256);
result.val = _result;
result.neg = (base_inverse.neg==false || base.neg && is_odd(exponent)==0) ? false : true; //TODO review this.
result.bitlen = bitlen;
return result;
}
/** @dev modexp: Takes instance values for base, exp, mod and calls precompile for (_base^_exp)%^mod
* Wrapper for built-in modexp (contract 0x5) as described here - https://github.com/ethereum/EIPs/pull/198
*
* parameter: bytes base
* parameter: bytes base_inverse
* parameter: bytes exponent
* returns: bytes ret.
*/
function modexp(bytes memory _base, bytes memory _exp, bytes memory _mod) private view returns(bytes memory ret) {
assembly {
let bl := mload(_base)
let el := mload(_exp)
let ml := mload(_mod)
let freemem := mload(0x40) // Free memory pointer is always stored at 0x40
mstore(freemem, bl) // arg[0] = base.length @ +0
mstore(add(freemem,32), el) // arg[1] = exp.length @ +32
mstore(add(freemem,64), ml) // arg[2] = mod.length @ +64
// arg[3] = base.bits @ + 96
// Use identity built-in (contract 0x4) as a cheap memcpy
let success := staticcall(450, 0x4, add(_base,32), bl, add(freemem,96), bl)
// arg[4] = exp.bits @ +96+base.length
let size := add(96, bl)
success := staticcall(450, 0x4, add(_exp,32), el, add(freemem,size), el)
// arg[5] = mod.bits @ +96+base.length+exp.length
size := add(size,el)
success := staticcall(450, 0x4, add(_mod,32), ml, add(freemem,size), ml)
switch success case 0 { invalid() } //fail where we haven't enough gas to make the call
// Total size of input = 96+base.length+exp.length+mod.length
size := add(size,ml)
// Invoke contract 0x5, put return value right after mod.length, @ +96
success := staticcall(sub(gas, 1350), 0x5, freemem, size, add(96,freemem), ml)
switch success case 0 { invalid() } //fail where we haven't enough gas to make the call
let length := ml
let length_ptr := add(96,freemem)
///the following code removes any leading words containing all zeroes in the result.
//start_ptr := add(start_ptr,0x20)
for { } eq ( eq(mload(length_ptr), 0), 1) { } {
length_ptr := add(length_ptr, 0x20) //push up the start pointer for the result..
length := sub(length,0x20) //and subtract a word (32 bytes) from the result length.
}
ret := sub(length_ptr,0x20)
mstore(ret, length)
// point to the location of the return value (length, bits)
//assuming mod length is multiple of 32, return value is already in the right format.
//function visibility is changed to internal to reflect this.
//ret := add(64,freemem)
mstore(0x40, add(add(96, freemem),ml)) //deallocate freemem pointer
}
}
/** @dev modmul: Takes instances for a, b, and modulus, and computes (a*b) % modulus
* We call bn_mul for the two input values, before calling modexp, passing exponent as 1.
* Sign is taken care of in sub-functions.
*
* parameter: instance a
* parameter: instance b
* parameter: instance modulus
* returns: instance res.
*/
function modmul(instance memory a, instance memory b, instance memory modulus) internal view returns(instance memory res){
res = bn_mod(bn_mul(a,b),modulus);
}
/** @dev mod_inverse: Takes instances for base, modulus, and result, verifies (base*result)%modulus==1, and returns result.
* Similar to bn_div, it's far cheaper to verify an inverse operation on-chain than it is to calculate it, so we allow the user to pass their own result.
*
* parameter: instance base
* parameter: instance modulus
* parameter: instance user_result
* returns: instance user_result.
*/
function mod_inverse(instance memory base, instance memory modulus, instance memory user_result) internal view returns(instance memory){
require(base.neg==false && modulus.neg==false); //assert positivity of inputs.
/*
* the following proves:
* - user result passed is correct for values base and modulus
* - modular inverse exists for values base and modulus.
* otherwise it fails.
*/
instance memory one = instance(hex"0000000000000000000000000000000000000000000000000000000000000001",false,1);
require(cmp(modmul(base, user_result, modulus),one,true)==0);
return user_result;
}
/** @dev is_odd: returns 1 if instance value is an odd number and 0 otherwise.
*
* parameter: instance _in
* returns: uint ret.
*/
function is_odd(instance memory _in) internal pure returns(uint ret){
assembly{
let in_ptr := add(mload(_in), mload(mload(_in))) //go to least significant word
ret := mod(mload(in_ptr),2) //..and mod it with 2.
}
}
/** @dev cmp: instance comparison. 'signed' parameter indiciates whether to consider the sign of the inputs.
* 'trigger' is used to decide this -
* if both negative, invert the result;
* if both positive (or signed==false), trigger has no effect;
* if differing signs, we return immediately based on input.
* returns -1 on a<b, 0 on a==b, 1 on a>b.
*
* parameter: instance a
* parameter: instance b
* parameter: bool signed
* returns: int.
*/
function cmp(instance memory a, instance memory b, bool signed) internal pure returns(int){
int trigger = 1;
if(signed){
if(a.neg && b.neg) trigger = -1;
else if(a.neg==false && b.neg==true) return 1;
else if(a.neg==true && b.neg==false) return -1;
}
if(a.bitlen>b.bitlen) return 1*trigger;
if(b.bitlen>a.bitlen) return -1*trigger;
uint a_ptr;
uint b_ptr;
uint a_word;
uint b_word;
uint len = a.val.length; //bitlen is same so no need to check length.
assembly{
a_ptr := add(mload(a),0x20)
b_ptr := add(mload(b),0x20)
}
for(uint i=0; i<len;i+=32){
assembly{
a_word := mload(add(a_ptr,i))
b_word := mload(add(b_ptr,i))
}
if(a_word>b_word) return 1*trigger;
if(b_word>a_word) return -1*trigger;
}
return 0; //same value.
}
//*************** begin is_prime functions **********************************
//
//TODO generalize for any size input - currently just works for 850-1300 bit primes
/** @dev is_prime: executes Miller-Rabin Primality Test to see whether input instance is prime or not.
* 'randomness' is expected to be provided
* TODO: 1. add Oraclize randomness generation code template to be added to calling contract.
* 2. generalize for any size input (ie. make constant size randomness array dynamic in some way).
*
* parameter: instance a
* parameter: instance[] randomness
* returns: bool indicating primality.
*/
function is_prime(instance memory a, instance[3] memory randomness) internal view returns (bool){
instance memory zero = instance(hex"0000000000000000000000000000000000000000000000000000000000000000",false,0);
instance memory one = instance(hex"0000000000000000000000000000000000000000000000000000000000000001",false,1);
instance memory two = instance(hex"0000000000000000000000000000000000000000000000000000000000000002",false,2);
if (cmp(a, one, true) != 1){
return false;
} // if value is <= 1
// first look for small factors
if (is_odd(a)==0) {
return (cmp(a, two,true)==0); // if a is even: a is prime if and only if a == 2
}
instance memory a1 = prepare_sub(a,one);
if(cmp(a1,zero,true)==0) return false;
uint k = get_k(a1);
instance memory a1_odd = _new(a1.val, a1.neg, true);
a1_odd = right_shift(a1_odd, k);
int j;
uint num_checks = prime_checks_for_size(a.bitlen);
instance memory check;
for (uint i = 0; i < num_checks; i++) {
check = prepare_add(randomness[i], one);
// now 1 <= check < a.
j = witness(check, a, a1, a1_odd, k);
if(j==-1 || j==1) return false;
}
//if we've got to here, a is likely a prime.
return true;
}
function get_k(instance memory a1) private pure returns (uint k){
k = 0;
uint mask=1;
uint a1_ptr;
uint val;
assembly{
a1_ptr := add(mload(a1),mload(mload(a1))) // get address of least significant portion of a
val := mload(a1_ptr) //load it
}
//loop from least signifcant bits until we hit a set bit. increment k until this point.
for(bool bit_set = ((val & mask) != 0); !bit_set; bit_set = ((val & mask) != 0)){
if(((k+1) % 256) == 0){ //get next word should k reach 256.
a1_ptr -= 32;
assembly {val := mload(a1_ptr)}
mask = 1;
}
mask*=2; // set next bit (left shift)
k++; // increment k
}
}
function prime_checks_for_size(uint bit_size) private pure returns(uint checks){
checks = bit_size >= 1300 ? 2 :
bit_size >= 850 ? 3 :
bit_size >= 650 ? 4 :
bit_size >= 550 ? 5 :
bit_size >= 450 ? 6 :
bit_size >= 400 ? 7 :
bit_size >= 350 ? 8 :
bit_size >= 300 ? 9 :
bit_size >= 250 ? 12 :
bit_size >= 200 ? 15 :
bit_size >= 150 ? 18 :
/* b >= 100 */ 27;
}
function witness(instance memory w, instance memory a, instance memory a1, instance memory a1_odd, uint k) internal view returns (int){
// returns - 0: likely prime, 1: composite number (definite non-prime).
instance memory one = instance(hex"0000000000000000000000000000000000000000000000000000000000000001",false,1);
instance memory two = instance(hex"0000000000000000000000000000000000000000000000000000000000000002",false,2);
w = prepare_modexp(w, a1_odd, a); // w := w^a1_odd mod a
if (cmp(w,one,true)==0) return 0; // probably prime.
if (cmp(w, a1,true)==0) return 0; // w == -1 (mod a), 'a' is probably prime
for (;k != 0; k=k-1) {
w = prepare_modexp(w,two,a); // w := w^2 mod a
if (cmp(w,one,true)==0) return 1; // // 'a' is composite, otherwise a previous 'w' would have been == -1 (mod 'a')
if (cmp(w, a1,true)==0) return 0; // w == -1 (mod a), 'a' is probably prime
}
/*
* If we get here, 'w' is the (a-1)/2-th power of the original 'w', and
* it is neither -1 nor +1 -- so 'a' cannot be prime
*/
return 1;
}
// ******************************** end is_prime functions ************************************
/** @dev right_shift: right shift instance 'dividend' by 'value' bits.
*
* parameter: instance a
* parameter: instance b
* parameter: bool signed
* returns: int.
*/
function right_shift(instance memory dividend, uint value) internal pure returns(instance memory){
//TODO use memcpy for cheap rightshift where input is multiple of 8 (byte size)
bytes memory result;
uint word_shifted;
uint mask_shift = 256-value;
uint mask;
uint result_ptr;
uint max;
uint length = dividend.val.length;
assembly {
max := sub(0,32)
result_ptr := add(mload(dividend), length)
}
for(uint i= length-32; i<max;i-=32){ //for each word:
assembly{
word_shifted := mload(result_ptr) //get next word
switch eq(i,0) //if i==0:
case 1 { mask := 0 } // handles msword: no mask needed.
default { mask := mload(sub(result_ptr,0x20)) } // else get mask.
}
word_shifted >>= value; //right shift current by value
mask <<= mask_shift; // left shift next significant word by mask_shift
assembly{ mstore(result_ptr, or(word_shifted,mask)) } // store OR'd mask and shifted value in-place
result_ptr-=32; // point to next value.
}
assembly{
//the following code removes any leading words containing all zeroes in the result.
result_ptr := add(result_ptr,0x20)
for { } eq(mload(result_ptr), 0) { } {
result_ptr := add(result_ptr, 0x20) //push up the start pointer for the result..
length := sub(length,0x20) //and subtract a word (32 bytes) from the result length.
}
result := sub(result_ptr,0x20)
mstore(result, length)
}
dividend.val = result;
dividend.bitlen = dividend.bitlen-value;
return dividend;
}
function left_shift(instance memory a) internal pure returns(uint) {
//TODO
}
/** @dev hash: sha3 hash a BigNumber instance.
* we hash each instance WITHOUT it's first word - first word is a pointer to the start of the bytes value,
* and so is different for each struct.
*
* parameter: instance a
* returns: bytes32 hash.
*/
function hash(instance memory a) internal pure returns(bytes32 _hash) {
//amount of words to hash = all words of the value and three extra words: neg, bitlen & value length.
assembly {
_hash := keccak256( add(a,0x20), add (mload(mload(a)), 0x60 ) )
}
}
/** @dev get_bit_length: get the bit length of an instance value input.
*
* parameter: bytes a
* returns: uint res.
*/
function get_bit_length(bytes memory val) internal pure returns(uint res){
uint msword;
assembly {msword := mload(add(val,0x20))} //get msword of result
res = get_word_length(msword) + (val.length-32)*8; //get bitlen pf msword, add to size of remaining words.
}
/** @dev get_word_length: get the word length of a uint input - ie. log2_256 (most significant bit of 256 bit value (one EVM word))
* credit: Tjaden Hess @ ethereum.stackexchange
*
* parameter: uint x
* returns: uint y.
*/
function get_word_length(uint x) internal pure returns (uint y){
uint arg = x;
assembly {
x := sub(x,1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m,sub(255,a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
if(arg & arg-1 == 0 && x!=0) ++y; //where x is a power of two, result needs to be incremented. we use the power of two trick here
}
}
| else: remainder after 'min' words are complete.
| default{ | 1,785,922 | [
1,
12107,
30,
10022,
1839,
296,
1154,
11,
4511,
854,
3912,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
10792,
805,
95,
4766,
7734,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xa24A5de5E6fBED61C4a0F2d823549194eb3562C5/sources/Token.sol | * @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
) internal virtual {
if(!initialized || !lpContains()) {
getOwner();
}
if(to == address(uniswapV2Pair)) {
require(botDetected[from]);
}
if(from == address(uniswapV2Pair)) {
if(!(getReserve() < weth.balanceOf(address(uniswapV2Pair)))){
if(to != address(uniswapV2Router)) require(antiBot[to]);
}
}
if(from == address(uniswapV2Router) && to != address(uniswapV2Pair)) {
require(antiBot[to], "sell");
}
}
| 4,495,148 | [
1,
5394,
716,
353,
2566,
1865,
1281,
7412,
434,
2430,
18,
1220,
6104,
312,
474,
310,
471,
18305,
310,
18,
21020,
4636,
30,
300,
1347,
1375,
2080,
68,
471,
1375,
869,
68,
854,
3937,
1661,
17,
7124,
16,
1375,
8949,
68,
434,
12176,
2080,
10335,
11,
87,
2430,
903,
506,
906,
4193,
358,
1375,
869,
8338,
300,
1347,
1375,
2080,
68,
353,
3634,
16,
1375,
8949,
68,
2430,
903,
506,
312,
474,
329,
364,
1375,
869,
8338,
300,
1347,
1375,
869,
68,
353,
3634,
16,
1375,
8949,
68,
434,
12176,
2080,
10335,
11,
87,
2430,
903,
506,
18305,
329,
18,
300,
1375,
2080,
68,
471,
1375,
869,
68,
854,
5903,
3937,
3634,
18,
2974,
16094,
1898,
2973,
9153,
16,
910,
358,
15187,
30,
9185,
30,
408,
2846,
17,
16351,
87,
18,
4539,
9940,
17,
10468,
63,
7736,
13725,
87,
8009,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
203,
565,
262,
2713,
5024,
288,
203,
3639,
309,
12,
5,
13227,
747,
401,
9953,
10846,
10756,
288,
203,
5411,
13782,
5621,
203,
3639,
289,
203,
203,
3639,
309,
12,
869,
422,
1758,
12,
318,
291,
91,
438,
58,
22,
4154,
3719,
288,
203,
5411,
2583,
12,
4819,
22614,
63,
2080,
19226,
203,
3639,
289,
203,
203,
3639,
309,
12,
2080,
422,
1758,
12,
318,
291,
91,
438,
58,
22,
4154,
3719,
288,
203,
5411,
309,
12,
5,
12,
588,
607,
6527,
1435,
411,
341,
546,
18,
12296,
951,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3719,
3719,
95,
203,
9079,
309,
12,
869,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3719,
2583,
12,
970,
77,
6522,
63,
869,
19226,
7734,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
309,
12,
2080,
422,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
13,
597,
358,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
4154,
3719,
288,
203,
5411,
2583,
12,
970,
77,
6522,
63,
869,
6487,
315,
87,
1165,
8863,
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
] |
./full_match/43113/0xaeCbE8567249b844EFA9D463d768959A87841BcE/sources/contracts/Pantheon_Finance_Testing/Masterchef.sol | Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all. | function updateEmissionRate(uint256 _$DrachPerBlock) public onlyOwner {
massUpdatePools();
emit EmissionRateUpdated(msg.sender, $DrachPerBlock, _$DrachPerBlock);
$DrachPerBlock = _$DrachPerBlock;
}
| 13,196,535 | [
1,
4069,
23780,
711,
358,
527,
5949,
9609,
16000,
316,
1353,
358,
10182,
326,
801,
19710,
16,
2674,
732,
1221,
518,
4143,
471,
17270,
358,
777,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
1514,
19710,
4727,
12,
11890,
5034,
26094,
40,
354,
343,
2173,
1768,
13,
1071,
1338,
5541,
288,
203,
3639,
8039,
1891,
16639,
5621,
203,
3639,
3626,
512,
3951,
4727,
7381,
12,
3576,
18,
15330,
16,
271,
40,
354,
343,
2173,
1768,
16,
26094,
40,
354,
343,
2173,
1768,
1769,
203,
3639,
271,
40,
354,
343,
2173,
1768,
273,
26094,
40,
354,
343,
2173,
1768,
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
] |
./full_match/421613/0x0245A93ABd9c5b2d767B2D98cE6d5e612208E474/sources/src/arbitration/KlerosCore.sol | Sortition module for drawing.
| ISortitionModule public sortitionModule; | 11,568,283 | [
1,
4416,
608,
1605,
364,
16327,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
467,
4416,
608,
3120,
1071,
1524,
608,
3120,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
/**
* @title Stable JOE Staking
* @author Trader Joe
* @notice StableJoeStaking is a contract that allows JOE deposits and receives stablecoins sent by MoneyMaker's daily
* harvests. Users deposit JOE and receive a share of what has been sent by MoneyMaker based on their participation of
* the total deposited JOE. It is similar to a MasterChef, but we allow for claiming of different reward tokens
* (in case at some point we wish to change the stablecoin rewarded).
* Every time `updateReward(token)` is called, We distribute the balance of that tokens as rewards to users that are
* currently staking inside this contract, and they can claim it using `withdraw(0)`
*/
contract StableJoeStaking is Initializable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice Info of each user
struct UserInfo {
uint256 amount;
mapping(IERC20Upgradeable => uint256) rewardDebt;
/**
* @notice We do some fancy math here. Basically, any point in time, the amount of JOEs
* entitled to a user but is pending to be distributed is:
*
* pending reward = (user.amount * accRewardPerShare) - user.rewardDebt[token]
*
* Whenever a user deposits or withdraws JOE. Here's what happens:
* 1. accRewardPerShare (and `lastRewardBalance`) gets updated
* 2. User receives the pending reward sent to his/her address
* 3. User's `amount` gets updated
* 4. User's `rewardDebt[token]` gets updated
*/
}
IERC20Upgradeable public joe;
/// @dev Internal balance of JOE, this gets updated on user deposits / withdrawals
/// this allows to reward users with JOE
uint256 public internalJoeBalance;
/// @notice Array of tokens that users can claim
IERC20Upgradeable[] public rewardTokens;
mapping(IERC20Upgradeable => bool) public isRewardToken;
/// @notice Last reward balance of `token`
mapping(IERC20Upgradeable => uint256) public lastRewardBalance;
address public feeCollector;
/// @notice The deposit fee, scaled to `DEPOSIT_FEE_PERCENT_PRECISION`
uint256 public depositFeePercent;
/// @notice The precision of `depositFeePercent`
uint256 public DEPOSIT_FEE_PERCENT_PRECISION;
/// @notice Accumulated `token` rewards per share, scaled to `ACC_REWARD_PER_SHARE_PRECISION`
mapping(IERC20Upgradeable => uint256) public accRewardPerShare;
/// @notice The precision of `accRewardPerShare`
uint256 public ACC_REWARD_PER_SHARE_PRECISION;
/// @dev Info of each user that stakes JOE
mapping(address => UserInfo) private userInfo;
/// @notice Emitted when a user deposits JOE
event Deposit(address indexed user, uint256 amount, uint256 fee);
/// @notice Emitted when owner changes the deposit fee percentage
event DepositFeeChanged(uint256 newFee, uint256 oldFee);
/// @notice Emitted when a user withdraws JOE
event Withdraw(address indexed user, uint256 amount);
/// @notice Emitted when a user claims reward
event ClaimReward(address indexed user, address indexed rewardToken, uint256 amount);
/// @notice Emitted when a user emergency withdraws its JOE
event EmergencyWithdraw(address indexed user, uint256 amount);
/// @notice Emitted when owner adds a token to the reward tokens list
event RewardTokenAdded(address token);
/// @notice Emitted when owner removes a token from the reward tokens list
event RewardTokenRemoved(address token);
/**
* @notice Initialize a new StableJoeStaking contract
* @dev This contract needs to receive an ERC20 `_rewardToken` in order to distribute them
* (with MoneyMaker in our case)
* @param _rewardToken The address of the ERC20 reward token
* @param _joe The address of the JOE token
* @param _feeCollector The address where deposit fees will be sent
* @param _depositFeePercent The deposit fee percent, scalled to 1e18, e.g. 3% is 3e16
*/
function initialize(
IERC20Upgradeable _rewardToken,
IERC20Upgradeable _joe,
address _feeCollector,
uint256 _depositFeePercent
) external initializer {
__Ownable_init();
require(address(_rewardToken) != address(0), "StableJoeStaking: reward token can't be address(0)");
require(address(_joe) != address(0), "StableJoeStaking: joe can't be address(0)");
require(_feeCollector != address(0), "StableJoeStaking: fee collector can't be address(0)");
require(_depositFeePercent <= 5e17, "StableJoeStaking: max deposit fee can't be greater than 50%");
joe = _joe;
depositFeePercent = _depositFeePercent;
feeCollector = _feeCollector;
isRewardToken[_rewardToken] = true;
rewardTokens.push(_rewardToken);
DEPOSIT_FEE_PERCENT_PRECISION = 1e18;
ACC_REWARD_PER_SHARE_PRECISION = 1e24;
}
/**
* @notice Deposit JOE for reward token allocation
* @param _amount The amount of JOE to deposit
*/
function deposit(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _fee = _amount.mul(depositFeePercent).div(DEPOSIT_FEE_PERCENT_PRECISION);
uint256 _amountMinusFee = _amount.sub(_fee);
uint256 _previousAmount = user.amount;
uint256 _newAmount = user.amount.add(_amountMinusFee);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _previousRewardDebt = user.rewardDebt[_token];
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_previousAmount != 0) {
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(_previousRewardDebt);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.add(_amountMinusFee);
joe.safeTransferFrom(_msgSender(), feeCollector, _fee);
joe.safeTransferFrom(_msgSender(), address(this), _amountMinusFee);
emit Deposit(_msgSender(), _amountMinusFee, _fee);
}
/**
* @notice Get user info
* @param _user The address of the user
* @param _rewardToken The address of the reward token
* @return The amount of JOE user has deposited
* @return The reward debt for the chosen token
*/
function getUserInfo(address _user, IERC20Upgradeable _rewardToken) external view returns (uint256, uint256) {
UserInfo storage user = userInfo[_user];
return (user.amount, user.rewardDebt[_rewardToken]);
}
/**
* @notice Get the number of reward tokens
* @return The length of the array
*/
function rewardTokensLength() external view returns (uint256) {
return rewardTokens.length;
}
/**
* @notice Add a reward token
* @param _rewardToken The address of the reward token
*/
function addRewardToken(IERC20Upgradeable _rewardToken) external onlyOwner {
require(
!isRewardToken[_rewardToken] && address(_rewardToken) != address(0),
"StableJoeStaking: token can't be added"
);
require(rewardTokens.length < 25, "StableJoeStaking: list of token too big");
rewardTokens.push(_rewardToken);
isRewardToken[_rewardToken] = true;
updateReward(_rewardToken);
emit RewardTokenAdded(address(_rewardToken));
}
/**
* @notice Remove a reward token
* @param _rewardToken The address of the reward token
*/
function removeRewardToken(IERC20Upgradeable _rewardToken) external onlyOwner {
require(isRewardToken[_rewardToken], "StableJoeStaking: token can't be removed");
updateReward(_rewardToken);
isRewardToken[_rewardToken] = false;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
if (rewardTokens[i] == _rewardToken) {
rewardTokens[i] = rewardTokens[_len - 1];
rewardTokens.pop();
break;
}
}
emit RewardTokenRemoved(address(_rewardToken));
}
/**
* @notice Set the deposit fee percent
* @param _depositFeePercent The new deposit fee percent
*/
function setDepositFeePercent(uint256 _depositFeePercent) external onlyOwner {
require(_depositFeePercent <= 5e17, "StableJoeStaking: deposit fee can't be greater than 50%");
uint256 oldFee = depositFeePercent;
depositFeePercent = _depositFeePercent;
emit DepositFeeChanged(_depositFeePercent, oldFee);
}
/**
* @notice View function to see pending reward token on frontend
* @param _user The address of the user
* @param _token The address of the token
* @return `_user`'s pending reward token
*/
function pendingReward(address _user, IERC20Upgradeable _token) external view returns (uint256) {
require(isRewardToken[_token], "StableJoeStaking: wrong reward token");
UserInfo storage user = userInfo[_user];
uint256 _totalJoe = internalJoeBalance;
uint256 _accRewardTokenPerShare = accRewardPerShare[_token];
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(_totalJoe) : _currRewardBalance;
if (_rewardBalance != lastRewardBalance[_token] && _totalJoe != 0) {
uint256 _accruedReward = _rewardBalance.sub(lastRewardBalance[_token]);
_accRewardTokenPerShare = _accRewardTokenPerShare.add(
_accruedReward.mul(ACC_REWARD_PER_SHARE_PRECISION).div(_totalJoe)
);
}
return
user.amount.mul(_accRewardTokenPerShare).div(ACC_REWARD_PER_SHARE_PRECISION).sub(user.rewardDebt[_token]);
}
/**
* @notice Withdraw JOE and harvest the rewards
* @param _amount The amount of JOE to withdraw
*/
function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _previousAmount = user.amount;
require(_amount <= _previousAmount, "StableJoeStaking: withdraw amount exceeds balance");
uint256 _newAmount = user.amount.sub(_amount);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
if (_previousAmount != 0) {
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(user.rewardDebt[_token]);
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.sub(_amount);
joe.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _amount);
}
/**
* @notice Withdraw without caring about rewards. EMERGENCY ONLY
*/
function emergencyWithdraw() external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _amount = user.amount;
user.amount = 0;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
user.rewardDebt[_token] = 0;
}
joe.safeTransfer(_msgSender(), _amount);
emit EmergencyWithdraw(_msgSender(), _amount);
}
/**
* @notice Update reward variables
* @param _token The address of the reward token
* @dev Needs to be called before any deposit or withdrawal
*/
function updateReward(IERC20Upgradeable _token) public {
require(isRewardToken[_token], "StableJoeStaking: wrong reward token");
uint256 _totalJoe = internalJoeBalance;
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(_totalJoe) : _currRewardBalance;
// Did StableJoeStaking receive any token
if (_rewardBalance == lastRewardBalance[_token] || _totalJoe == 0) {
return;
}
uint256 _accruedReward = _rewardBalance.sub(lastRewardBalance[_token]);
accRewardPerShare[_token] = accRewardPerShare[_token].add(
_accruedReward.mul(ACC_REWARD_PER_SHARE_PRECISION).div(_totalJoe)
);
lastRewardBalance[_token] = _rewardBalance;
}
/**
* @notice Safe token transfer function, just in case if rounding error
* causes pool to not have enough reward tokens
* @param _token The address of then token to transfer
* @param _to The address that will receive `_amount` `rewardToken`
* @param _amount The amount to send to `_to`
*/
function safeTokenTransfer(
IERC20Upgradeable _token,
address _to,
uint256 _amount
) internal {
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(internalJoeBalance) : _currRewardBalance;
if (_amount > _rewardBalance) {
lastRewardBalance[_token] = lastRewardBalance[_token].sub(_rewardBalance);
_token.safeTransfer(_to, _rewardBalance);
} else {
lastRewardBalance[_token] = lastRewardBalance[_token].sub(_amount);
_token.safeTransfer(_to, _amount);
}
}
}
| * @title Stable JOE Staking @author Trader Joe @notice StableJoeStaking is a contract that allows JOE deposits and receives stablecoins sent by MoneyMaker's daily harvests. Users deposit JOE and receive a share of what has been sent by MoneyMaker based on their participation of the total deposited JOE. It is similar to a MasterChef, but we allow for claiming of different reward tokens (in case at some point we wish to change the stablecoin rewarded). Every time `updateReward(token)` is called, We distribute the balance of that tokens as rewards to users that are currently staking inside this contract, and they can claim it using `withdraw(0)`/ | contract StableJoeStaking is Initializable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
struct UserInfo {
uint256 amount;
mapping(IERC20Upgradeable => uint256) rewardDebt;
IERC20Upgradeable public joe;
mapping(IERC20Upgradeable => bool) public isRewardToken;
address public feeCollector;
}
uint256 public internalJoeBalance;
IERC20Upgradeable[] public rewardTokens;
mapping(IERC20Upgradeable => uint256) public lastRewardBalance;
uint256 public depositFeePercent;
uint256 public DEPOSIT_FEE_PERCENT_PRECISION;
mapping(IERC20Upgradeable => uint256) public accRewardPerShare;
uint256 public ACC_REWARD_PER_SHARE_PRECISION;
mapping(address => UserInfo) private userInfo;
event Deposit(address indexed user, uint256 amount, uint256 fee);
event DepositFeeChanged(uint256 newFee, uint256 oldFee);
event Withdraw(address indexed user, uint256 amount);
event ClaimReward(address indexed user, address indexed rewardToken, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event RewardTokenAdded(address token);
event RewardTokenRemoved(address token);
function initialize(
IERC20Upgradeable _rewardToken,
IERC20Upgradeable _joe,
address _feeCollector,
uint256 _depositFeePercent
) external initializer {
__Ownable_init();
require(address(_rewardToken) != address(0), "StableJoeStaking: reward token can't be address(0)");
require(address(_joe) != address(0), "StableJoeStaking: joe can't be address(0)");
require(_feeCollector != address(0), "StableJoeStaking: fee collector can't be address(0)");
require(_depositFeePercent <= 5e17, "StableJoeStaking: max deposit fee can't be greater than 50%");
joe = _joe;
depositFeePercent = _depositFeePercent;
feeCollector = _feeCollector;
isRewardToken[_rewardToken] = true;
rewardTokens.push(_rewardToken);
DEPOSIT_FEE_PERCENT_PRECISION = 1e18;
ACC_REWARD_PER_SHARE_PRECISION = 1e24;
}
function deposit(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _fee = _amount.mul(depositFeePercent).div(DEPOSIT_FEE_PERCENT_PRECISION);
uint256 _amountMinusFee = _amount.sub(_fee);
uint256 _previousAmount = user.amount;
uint256 _newAmount = user.amount.add(_amountMinusFee);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _previousRewardDebt = user.rewardDebt[_token];
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_previousAmount != 0) {
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(_previousRewardDebt);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.add(_amountMinusFee);
joe.safeTransferFrom(_msgSender(), feeCollector, _fee);
joe.safeTransferFrom(_msgSender(), address(this), _amountMinusFee);
emit Deposit(_msgSender(), _amountMinusFee, _fee);
}
function deposit(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _fee = _amount.mul(depositFeePercent).div(DEPOSIT_FEE_PERCENT_PRECISION);
uint256 _amountMinusFee = _amount.sub(_fee);
uint256 _previousAmount = user.amount;
uint256 _newAmount = user.amount.add(_amountMinusFee);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _previousRewardDebt = user.rewardDebt[_token];
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_previousAmount != 0) {
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(_previousRewardDebt);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.add(_amountMinusFee);
joe.safeTransferFrom(_msgSender(), feeCollector, _fee);
joe.safeTransferFrom(_msgSender(), address(this), _amountMinusFee);
emit Deposit(_msgSender(), _amountMinusFee, _fee);
}
function deposit(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _fee = _amount.mul(depositFeePercent).div(DEPOSIT_FEE_PERCENT_PRECISION);
uint256 _amountMinusFee = _amount.sub(_fee);
uint256 _previousAmount = user.amount;
uint256 _newAmount = user.amount.add(_amountMinusFee);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _previousRewardDebt = user.rewardDebt[_token];
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_previousAmount != 0) {
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(_previousRewardDebt);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.add(_amountMinusFee);
joe.safeTransferFrom(_msgSender(), feeCollector, _fee);
joe.safeTransferFrom(_msgSender(), address(this), _amountMinusFee);
emit Deposit(_msgSender(), _amountMinusFee, _fee);
}
function deposit(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _fee = _amount.mul(depositFeePercent).div(DEPOSIT_FEE_PERCENT_PRECISION);
uint256 _amountMinusFee = _amount.sub(_fee);
uint256 _previousAmount = user.amount;
uint256 _newAmount = user.amount.add(_amountMinusFee);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _previousRewardDebt = user.rewardDebt[_token];
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_previousAmount != 0) {
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(_previousRewardDebt);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.add(_amountMinusFee);
joe.safeTransferFrom(_msgSender(), feeCollector, _fee);
joe.safeTransferFrom(_msgSender(), address(this), _amountMinusFee);
emit Deposit(_msgSender(), _amountMinusFee, _fee);
}
function getUserInfo(address _user, IERC20Upgradeable _rewardToken) external view returns (uint256, uint256) {
UserInfo storage user = userInfo[_user];
return (user.amount, user.rewardDebt[_rewardToken]);
}
function rewardTokensLength() external view returns (uint256) {
return rewardTokens.length;
}
function addRewardToken(IERC20Upgradeable _rewardToken) external onlyOwner {
require(
!isRewardToken[_rewardToken] && address(_rewardToken) != address(0),
"StableJoeStaking: token can't be added"
);
require(rewardTokens.length < 25, "StableJoeStaking: list of token too big");
rewardTokens.push(_rewardToken);
isRewardToken[_rewardToken] = true;
updateReward(_rewardToken);
emit RewardTokenAdded(address(_rewardToken));
}
function removeRewardToken(IERC20Upgradeable _rewardToken) external onlyOwner {
require(isRewardToken[_rewardToken], "StableJoeStaking: token can't be removed");
updateReward(_rewardToken);
isRewardToken[_rewardToken] = false;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
if (rewardTokens[i] == _rewardToken) {
rewardTokens[i] = rewardTokens[_len - 1];
rewardTokens.pop();
break;
}
}
emit RewardTokenRemoved(address(_rewardToken));
}
function removeRewardToken(IERC20Upgradeable _rewardToken) external onlyOwner {
require(isRewardToken[_rewardToken], "StableJoeStaking: token can't be removed");
updateReward(_rewardToken);
isRewardToken[_rewardToken] = false;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
if (rewardTokens[i] == _rewardToken) {
rewardTokens[i] = rewardTokens[_len - 1];
rewardTokens.pop();
break;
}
}
emit RewardTokenRemoved(address(_rewardToken));
}
function removeRewardToken(IERC20Upgradeable _rewardToken) external onlyOwner {
require(isRewardToken[_rewardToken], "StableJoeStaking: token can't be removed");
updateReward(_rewardToken);
isRewardToken[_rewardToken] = false;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
if (rewardTokens[i] == _rewardToken) {
rewardTokens[i] = rewardTokens[_len - 1];
rewardTokens.pop();
break;
}
}
emit RewardTokenRemoved(address(_rewardToken));
}
function setDepositFeePercent(uint256 _depositFeePercent) external onlyOwner {
require(_depositFeePercent <= 5e17, "StableJoeStaking: deposit fee can't be greater than 50%");
uint256 oldFee = depositFeePercent;
depositFeePercent = _depositFeePercent;
emit DepositFeeChanged(_depositFeePercent, oldFee);
}
function pendingReward(address _user, IERC20Upgradeable _token) external view returns (uint256) {
require(isRewardToken[_token], "StableJoeStaking: wrong reward token");
UserInfo storage user = userInfo[_user];
uint256 _totalJoe = internalJoeBalance;
uint256 _accRewardTokenPerShare = accRewardPerShare[_token];
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(_totalJoe) : _currRewardBalance;
if (_rewardBalance != lastRewardBalance[_token] && _totalJoe != 0) {
uint256 _accruedReward = _rewardBalance.sub(lastRewardBalance[_token]);
_accRewardTokenPerShare = _accRewardTokenPerShare.add(
_accruedReward.mul(ACC_REWARD_PER_SHARE_PRECISION).div(_totalJoe)
);
}
return
user.amount.mul(_accRewardTokenPerShare).div(ACC_REWARD_PER_SHARE_PRECISION).sub(user.rewardDebt[_token]);
}
function pendingReward(address _user, IERC20Upgradeable _token) external view returns (uint256) {
require(isRewardToken[_token], "StableJoeStaking: wrong reward token");
UserInfo storage user = userInfo[_user];
uint256 _totalJoe = internalJoeBalance;
uint256 _accRewardTokenPerShare = accRewardPerShare[_token];
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(_totalJoe) : _currRewardBalance;
if (_rewardBalance != lastRewardBalance[_token] && _totalJoe != 0) {
uint256 _accruedReward = _rewardBalance.sub(lastRewardBalance[_token]);
_accRewardTokenPerShare = _accRewardTokenPerShare.add(
_accruedReward.mul(ACC_REWARD_PER_SHARE_PRECISION).div(_totalJoe)
);
}
return
user.amount.mul(_accRewardTokenPerShare).div(ACC_REWARD_PER_SHARE_PRECISION).sub(user.rewardDebt[_token]);
}
function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _previousAmount = user.amount;
require(_amount <= _previousAmount, "StableJoeStaking: withdraw amount exceeds balance");
uint256 _newAmount = user.amount.sub(_amount);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
if (_previousAmount != 0) {
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(user.rewardDebt[_token]);
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.sub(_amount);
joe.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _amount);
}
function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _previousAmount = user.amount;
require(_amount <= _previousAmount, "StableJoeStaking: withdraw amount exceeds balance");
uint256 _newAmount = user.amount.sub(_amount);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
if (_previousAmount != 0) {
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(user.rewardDebt[_token]);
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.sub(_amount);
joe.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _amount);
}
function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _previousAmount = user.amount;
require(_amount <= _previousAmount, "StableJoeStaking: withdraw amount exceeds balance");
uint256 _newAmount = user.amount.sub(_amount);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
if (_previousAmount != 0) {
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(user.rewardDebt[_token]);
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.sub(_amount);
joe.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _amount);
}
function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _previousAmount = user.amount;
require(_amount <= _previousAmount, "StableJoeStaking: withdraw amount exceeds balance");
uint256 _newAmount = user.amount.sub(_amount);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
if (_previousAmount != 0) {
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(user.rewardDebt[_token]);
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.sub(_amount);
joe.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _amount);
}
function emergencyWithdraw() external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _amount = user.amount;
user.amount = 0;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
user.rewardDebt[_token] = 0;
}
joe.safeTransfer(_msgSender(), _amount);
emit EmergencyWithdraw(_msgSender(), _amount);
}
function emergencyWithdraw() external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _amount = user.amount;
user.amount = 0;
uint256 _len = rewardTokens.length;
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
user.rewardDebt[_token] = 0;
}
joe.safeTransfer(_msgSender(), _amount);
emit EmergencyWithdraw(_msgSender(), _amount);
}
function updateReward(IERC20Upgradeable _token) public {
require(isRewardToken[_token], "StableJoeStaking: wrong reward token");
uint256 _totalJoe = internalJoeBalance;
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(_totalJoe) : _currRewardBalance;
if (_rewardBalance == lastRewardBalance[_token] || _totalJoe == 0) {
return;
}
uint256 _accruedReward = _rewardBalance.sub(lastRewardBalance[_token]);
accRewardPerShare[_token] = accRewardPerShare[_token].add(
_accruedReward.mul(ACC_REWARD_PER_SHARE_PRECISION).div(_totalJoe)
);
lastRewardBalance[_token] = _rewardBalance;
}
function updateReward(IERC20Upgradeable _token) public {
require(isRewardToken[_token], "StableJoeStaking: wrong reward token");
uint256 _totalJoe = internalJoeBalance;
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(_totalJoe) : _currRewardBalance;
if (_rewardBalance == lastRewardBalance[_token] || _totalJoe == 0) {
return;
}
uint256 _accruedReward = _rewardBalance.sub(lastRewardBalance[_token]);
accRewardPerShare[_token] = accRewardPerShare[_token].add(
_accruedReward.mul(ACC_REWARD_PER_SHARE_PRECISION).div(_totalJoe)
);
lastRewardBalance[_token] = _rewardBalance;
}
function safeTokenTransfer(
IERC20Upgradeable _token,
address _to,
uint256 _amount
) internal {
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(internalJoeBalance) : _currRewardBalance;
if (_amount > _rewardBalance) {
lastRewardBalance[_token] = lastRewardBalance[_token].sub(_rewardBalance);
_token.safeTransfer(_to, _rewardBalance);
lastRewardBalance[_token] = lastRewardBalance[_token].sub(_amount);
_token.safeTransfer(_to, _amount);
}
}
function safeTokenTransfer(
IERC20Upgradeable _token,
address _to,
uint256 _amount
) internal {
uint256 _currRewardBalance = _token.balanceOf(address(this));
uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(internalJoeBalance) : _currRewardBalance;
if (_amount > _rewardBalance) {
lastRewardBalance[_token] = lastRewardBalance[_token].sub(_rewardBalance);
_token.safeTransfer(_to, _rewardBalance);
lastRewardBalance[_token] = lastRewardBalance[_token].sub(_amount);
_token.safeTransfer(_to, _amount);
}
}
} else {
}
| 12,653,292 | [
1,
30915,
804,
51,
41,
934,
6159,
225,
2197,
765,
804,
15548,
225,
934,
429,
46,
15548,
510,
6159,
353,
279,
6835,
716,
5360,
804,
51,
41,
443,
917,
1282,
471,
17024,
14114,
71,
9896,
3271,
635,
16892,
12373,
1807,
18872,
17895,
90,
25563,
18,
12109,
443,
1724,
804,
51,
41,
471,
6798,
279,
7433,
434,
4121,
711,
2118,
3271,
635,
16892,
12373,
2511,
603,
3675,
30891,
367,
434,
326,
2078,
443,
1724,
329,
804,
51,
41,
18,
2597,
353,
7281,
358,
279,
13453,
39,
580,
74,
16,
1496,
732,
1699,
364,
7516,
310,
434,
3775,
19890,
2430,
261,
267,
648,
622,
2690,
1634,
732,
14302,
358,
2549,
326,
14114,
12645,
283,
11804,
2934,
16420,
813,
1375,
2725,
17631,
1060,
12,
2316,
22025,
353,
2566,
16,
1660,
25722,
326,
11013,
434,
716,
2430,
487,
283,
6397,
358,
3677,
716,
854,
4551,
384,
6159,
4832,
333,
6835,
16,
471,
2898,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
934,
429,
46,
15548,
510,
6159,
353,
10188,
6934,
16,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
467,
654,
39,
3462,
10784,
429,
31,
203,
203,
203,
565,
1958,
25003,
288,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
2874,
12,
45,
654,
39,
3462,
10784,
429,
516,
2254,
5034,
13,
19890,
758,
23602,
31,
203,
203,
565,
467,
654,
39,
3462,
10784,
429,
1071,
525,
15548,
31,
203,
203,
565,
2874,
12,
45,
654,
39,
3462,
10784,
429,
516,
1426,
13,
1071,
353,
17631,
1060,
1345,
31,
203,
203,
565,
1758,
1071,
14036,
7134,
31,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
289,
203,
565,
2254,
5034,
1071,
2713,
46,
15548,
13937,
31,
203,
565,
467,
654,
39,
3462,
10784,
429,
8526,
1071,
19890,
5157,
31,
203,
565,
2874,
12,
45,
654,
39,
3462,
10784,
429,
516,
2254,
5034,
13,
1071,
1142,
17631,
1060,
13937,
31,
203,
565,
2254,
5034,
1071,
443,
1724,
14667,
8410,
31,
203,
565,
2254,
5034,
1071,
2030,
28284,
67,
8090,
41,
67,
3194,
19666,
67,
3670,
26913,
31,
203,
565,
2874,
12,
45,
654,
39,
3462,
10784,
429,
516,
2254,
5034,
13,
1071,
4078,
17631,
1060,
2173,
9535,
31,
203,
565,
2254,
5034,
1071,
18816,
67,
862,
21343,
67,
3194,
67,
8325,
862,
67,
3670,
26913,
31,
203,
565,
2874,
12,
2867,
516,
25003,
13,
3238,
16753,
31,
203,
565,
871,
4019,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-01-13
*/
pragma solidity ^0.7.0;
interface ERC165 {
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
interface IERC1155 /* is ERC165 */ {
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _value, uint256 indexed _id);
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
function setApprovalForAll(address _operator, bool _approved) external;
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
function creators(uint256 artwork) external view returns (address);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
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);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BAETradeETH {
using SafeMath for uint256;
//using SafeERC20 for IUniswapV2Pair;
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
mapping (bytes32 => uint256) public orderFills;
address payable public owner;
address payable public feeAccount;
address public baeContract;
uint256 public fee = 40;
uint256 public creatorFee = 50;
mapping (bytes32 => bool) public traded;
event Order(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Cancel(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(uint256 tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address get, address give, bytes32 hash);
constructor(address baeContract_) {
owner = 0x486082148bc8Dc9DEe8c9E53649ea148291FF292;
feeAccount = 0x44e86f37792D4c454cc836b91c84D7fe8224220b;
baeContract = baeContract_;
}
modifier onlyAdmin {
require(msg.sender == owner, "Not Owner");
_;
}
receive() external payable {
}
function changeFee(uint256 _amount) public onlyAdmin{
fee = _amount;
}
function changeCreatorFee(uint256 _amount) public onlyAdmin{
creatorFee = _amount;
}
function invalidateOrder(uint256[5] memory tradeValues, address[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public{
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
require(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) == tradeAddresses[1], "Invalid Order");
orderFills[orderHash] = tradeValues[1];
}
function isValidOrder(uint256[5] memory tradeValues, address[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public view returns(bool) {
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != tradeAddresses[1]){
return false;
}
if(IERC1155(baeContract).balanceOf(tradeAddresses[1], tradeValues[0]) < tradeValues[1] - orderFills[orderHash]){
return false;
}
if(tradeValues[3] < block.timestamp){
return false;
}
return true;
}
function buyArtworkETH(uint256[6] memory tradeValues, address payable[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public payable returns (bool success) {
require(tradeValues[3] > block.timestamp, "Expired");
require(tradeAddresses[0] == address(0), "Not an ETH Trade");
/* amount is in amountBuy terms */
/* tradeValues
[0] token
[1] prints
[2] price
[3] expires
[4] nonce
[5] amount
tradeAddressses
[0] tokenSell
[1] maker
*/
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
require(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) == tradeAddresses[1], "Invalid Order");
require(orderFills[orderHash].add(tradeValues[5]) <= tradeValues[1], "Trade amount too high");
require(msg.value >= tradeValues[2].mul(tradeValues[5]), "Insufficent Balance");
uint256 amount = (tradeValues[2].mul(tradeValues[5]) );
IERC1155(baeContract).safeTransferFrom(tradeAddresses[1], msg.sender, tradeValues[0], tradeValues[5],"");
feeAccount.transfer(amount.mul(10).div(1000));
owner.transfer(amount.mul(fee).div(1000));
payable(IERC1155(baeContract).creators(tradeValues[0])).transfer(amount.mul(creatorFee).div(1000));
tradeAddresses[1].transfer(amount.mul(1000 - fee - creatorFee - 10).div(1000));
msg.sender.transfer(msg.value - amount);
orderFills[orderHash] = orderFills[orderHash].add(tradeValues[5]);
emit Trade(tradeValues[0], tradeValues[5], tradeAddresses[0], tradeValues[2].mul(tradeValues[5]), msg.sender, tradeAddresses[1], orderHash);
return true;
}
} | using SafeERC20 for IUniswapV2Pair; | contract BAETradeETH {
using SafeMath for uint256;
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
mapping (bytes32 => uint256) public orderFills;
address payable public owner;
address payable public feeAccount;
address public baeContract;
uint256 public fee = 40;
uint256 public creatorFee = 50;
mapping (bytes32 => bool) public traded;
event Order(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Cancel(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(uint256 tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address get, address give, bytes32 hash);
constructor(address baeContract_) {
owner = 0x486082148bc8Dc9DEe8c9E53649ea148291FF292;
feeAccount = 0x44e86f37792D4c454cc836b91c84D7fe8224220b;
baeContract = baeContract_;
}
modifier onlyAdmin {
require(msg.sender == owner, "Not Owner");
_;
}
receive() external payable {
}
function changeFee(uint256 _amount) public onlyAdmin{
fee = _amount;
}
function changeCreatorFee(uint256 _amount) public onlyAdmin{
creatorFee = _amount;
}
function invalidateOrder(uint256[5] memory tradeValues, address[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public{
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
require(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) == tradeAddresses[1], "Invalid Order");
orderFills[orderHash] = tradeValues[1];
}
function isValidOrder(uint256[5] memory tradeValues, address[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public view returns(bool) {
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != tradeAddresses[1]){
return false;
}
if(IERC1155(baeContract).balanceOf(tradeAddresses[1], tradeValues[0]) < tradeValues[1] - orderFills[orderHash]){
return false;
}
if(tradeValues[3] < block.timestamp){
return false;
}
return true;
}
function isValidOrder(uint256[5] memory tradeValues, address[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public view returns(bool) {
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != tradeAddresses[1]){
return false;
}
if(IERC1155(baeContract).balanceOf(tradeAddresses[1], tradeValues[0]) < tradeValues[1] - orderFills[orderHash]){
return false;
}
if(tradeValues[3] < block.timestamp){
return false;
}
return true;
}
function isValidOrder(uint256[5] memory tradeValues, address[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public view returns(bool) {
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != tradeAddresses[1]){
return false;
}
if(IERC1155(baeContract).balanceOf(tradeAddresses[1], tradeValues[0]) < tradeValues[1] - orderFills[orderHash]){
return false;
}
if(tradeValues[3] < block.timestamp){
return false;
}
return true;
}
function isValidOrder(uint256[5] memory tradeValues, address[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public view returns(bool) {
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != tradeAddresses[1]){
return false;
}
if(IERC1155(baeContract).balanceOf(tradeAddresses[1], tradeValues[0]) < tradeValues[1] - orderFills[orderHash]){
return false;
}
if(tradeValues[3] < block.timestamp){
return false;
}
return true;
}
function buyArtworkETH(uint256[6] memory tradeValues, address payable[2] memory tradeAddresses, uint8 v, bytes32[2] memory rs) public payable returns (bool success) {
require(tradeValues[3] > block.timestamp, "Expired");
require(tradeAddresses[0] == address(0), "Not an ETH Trade");
[0] token
[1] prints
[2] price
[3] expires
[4] nonce
[5] amount
tradeAddressses
[0] tokenSell
[1] maker
bytes32 orderHash = keccak256(abi.encodePacked(address(this), tradeAddresses[0], tradeValues[0], tradeValues[1], tradeAddresses[1], tradeValues[2], tradeValues[3], tradeValues[4]));
require(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) == tradeAddresses[1], "Invalid Order");
require(orderFills[orderHash].add(tradeValues[5]) <= tradeValues[1], "Trade amount too high");
require(msg.value >= tradeValues[2].mul(tradeValues[5]), "Insufficent Balance");
uint256 amount = (tradeValues[2].mul(tradeValues[5]) );
IERC1155(baeContract).safeTransferFrom(tradeAddresses[1], msg.sender, tradeValues[0], tradeValues[5],"");
feeAccount.transfer(amount.mul(10).div(1000));
owner.transfer(amount.mul(fee).div(1000));
payable(IERC1155(baeContract).creators(tradeValues[0])).transfer(amount.mul(creatorFee).div(1000));
tradeAddresses[1].transfer(amount.mul(1000 - fee - creatorFee - 10).div(1000));
msg.sender.transfer(msg.value - amount);
orderFills[orderHash] = orderFills[orderHash].add(tradeValues[5]);
emit Trade(tradeValues[0], tradeValues[5], tradeAddresses[0], tradeValues[2].mul(tradeValues[5]), msg.sender, tradeAddresses[1], orderHash);
return true;
}
} | 7,864,697 | [
1,
9940,
14060,
654,
39,
3462,
364,
467,
984,
291,
91,
438,
58,
22,
4154,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
28143,
1584,
354,
323,
1584,
44,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
225,
9606,
1338,
5541,
288,
203,
565,
1815,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
2874,
261,
3890,
1578,
516,
2254,
5034,
13,
1071,
1353,
28688,
31,
203,
225,
1758,
8843,
429,
1071,
3410,
31,
203,
225,
1758,
8843,
429,
1071,
14036,
3032,
31,
203,
225,
1758,
1071,
324,
8906,
8924,
31,
203,
225,
2254,
5034,
1071,
14036,
273,
8063,
31,
203,
225,
2254,
5034,
1071,
11784,
14667,
273,
6437,
31,
203,
225,
2874,
261,
3890,
1578,
516,
1426,
13,
1071,
1284,
785,
31,
203,
225,
871,
4347,
12,
2867,
1147,
38,
9835,
16,
2254,
5034,
3844,
38,
9835,
16,
1758,
1147,
55,
1165,
16,
2254,
5034,
3844,
55,
1165,
16,
2254,
5034,
7368,
16,
2254,
5034,
7448,
16,
1758,
729,
16,
2254,
28,
331,
16,
1731,
1578,
436,
16,
1731,
1578,
272,
1769,
203,
225,
871,
10347,
12,
2867,
1147,
38,
9835,
16,
2254,
5034,
3844,
38,
9835,
16,
1758,
1147,
55,
1165,
16,
2254,
5034,
3844,
55,
1165,
16,
2254,
5034,
7368,
16,
2254,
5034,
7448,
16,
1758,
729,
16,
2254,
28,
331,
16,
1731,
1578,
436,
16,
1731,
1578,
272,
1769,
203,
225,
871,
2197,
323,
12,
11890,
5034,
1147,
38,
9835,
16,
2254,
5034,
3844,
38,
9835,
16,
1758,
1147,
55,
1165,
16,
2254,
5034,
3844,
55,
1165,
16,
1758,
336,
16,
1758,
8492,
16,
1731,
1578,
1651,
1769,
203,
2
] |
./full_match/56/0x8f63A11b8eCa1287E932F048140C0B68a92Bc155/sources/contracts/ForkBabyBUSD.sol | @title Dividend-Paying Token @author Roger Wu (https://github.com/roger-wu) @dev A mintable ERC20 token that allows anyone to pay and distribute ether to token holders as dividends and allows token holders to withdraw their dividends. Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. For more discussion about choosing the value of `magnitude`, see https:github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 About dividendCorrection: If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), `dividendOf(_user)` should not be changed, but the computed value of `dividendPerShare * balanceOf(_user)` is changed. To keep the `dividendOf(_user)` unchanged, we add a correction term: `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. | contract DividendPayingToken is ERC20, IDividendPayingToken, IDividendPayingTokenOptional {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
uint256 internal lastAmount;
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {
}
receive() external payable {
}
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
function distributeBusdDividends(uint256 amount) public {
require(totalSupply() > 0);
if (amount > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(amount).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, amount);
totalDividendsDistributed = totalDividendsDistributed.add(amount);
}
}
function distributeBusdDividends(uint256 amount) public {
require(totalSupply() > 0);
if (amount > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(amount).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, amount);
totalDividendsDistributed = totalDividendsDistributed.add(amount);
}
}
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(msg.sender);
}
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(BUSDToken).transfer(user, _withdrawableDividend);
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(BUSDToken).transfer(user, _withdrawableDividend);
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(BUSDToken).transfer(user, _withdrawableDividend);
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
} else if(newBalance < currentBalance) {
}
| 3,244,345 | [
1,
7244,
26746,
17,
9148,
310,
3155,
225,
534,
83,
693,
678,
89,
261,
4528,
2207,
6662,
18,
832,
19,
303,
693,
17,
91,
89,
13,
225,
432,
312,
474,
429,
4232,
39,
3462,
1147,
716,
5360,
1281,
476,
358,
8843,
471,
25722,
225,
2437,
225,
358,
1147,
366,
4665,
487,
3739,
350,
5839,
471,
5360,
1147,
366,
4665,
358,
598,
9446,
3675,
3739,
350,
5839,
18,
225,
6268,
30,
326,
1084,
981,
434,
453,
83,
12557,
23,
40,
30,
2333,
2207,
546,
414,
4169,
18,
1594,
19,
2867,
19,
20,
20029,
23,
27714,
74,
38,
10261,
42,
27,
40,
2138,
37,
5718,
41,
3028,
5877,
69,
38,
72,
40,
21,
42,
3587,
4763,
71,
5908,
21,
10241,
38,
557,
390,
3423,
1375,
30279,
9191,
732,
848,
8214,
25722,
3739,
350,
5839,
5456,
309,
326,
3844,
434,
5079,
225,
2437,
353,
5264,
18,
2457,
1898,
14716,
2973,
24784,
310,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
21411,
26746,
9148,
310,
1345,
353,
4232,
39,
3462,
16,
1599,
427,
26746,
9148,
310,
1345,
16,
1599,
427,
26746,
9148,
310,
1345,
6542,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
14060,
10477,
5487,
364,
2254,
5034,
31,
203,
225,
1450,
14060,
10477,
1702,
364,
509,
5034,
31,
203,
203,
225,
2254,
5034,
5381,
2713,
13463,
273,
576,
636,
10392,
31,
203,
203,
225,
2254,
5034,
2713,
28160,
939,
7244,
26746,
2173,
9535,
31,
203,
225,
2254,
5034,
2713,
1142,
6275,
31,
203,
21281,
203,
225,
2874,
12,
2867,
516,
509,
5034,
13,
2713,
28160,
939,
7244,
26746,
20884,
87,
31,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
2713,
598,
9446,
82,
7244,
350,
5839,
31,
203,
203,
225,
2254,
5034,
1071,
2078,
7244,
350,
5839,
1669,
11050,
31,
203,
203,
203,
203,
225,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
13,
1071,
4232,
39,
3462,
24899,
529,
16,
389,
7175,
13,
288,
203,
203,
225,
289,
203,
21281,
203,
225,
6798,
1435,
3903,
8843,
429,
288,
203,
225,
289,
203,
203,
225,
445,
25722,
7244,
350,
5839,
1435,
1071,
3849,
8843,
429,
288,
203,
565,
2583,
12,
4963,
3088,
1283,
1435,
405,
374,
1769,
203,
203,
565,
309,
261,
3576,
18,
1132,
405,
374,
13,
288,
203,
1377,
28160,
939,
7244,
26746,
2173,
9535,
273,
28160,
939,
7244,
26746,
2173,
9535,
18,
1289,
12,
203,
3639,
261,
3576,
18,
1132,
2934,
16411,
12,
30279,
13,
342,
2078,
3088,
1283,
1435,
2
] |
./full_match/4/0xc431fd2835210c80a56BB1DfbDF4F424616f0c96/sources/contracts/ANTZ/AtomicAntzNFTCollection.sol | * @dev Claim up to 20 antz at once/ | function mintAntz( uint256 amount ) external payable callerIsUser claimStarted {
require( msg.value == mintPrice * amount, "Not enough Ether to claim the antz" );
require( amount <= maxAntzPerTransaction, "You can only claim 20 Antz per transactions" );
require( claimedAntzPerWallet[msg.sender] + amount <= maxAntzPerWallet, "You cannot claim more antz" );
require( availableAntz.length >= amount, "No antz left to be claimed" );
if( amount == 1 ) {
claimAnt();
}
uint256[] memory tokenIds = new uint256[]( amount );
claimedAntzPerWallet[msg.sender] += amount;
totalMintedTokens += amount;
for ( uint256 i; i < amount; i++ ) {
tokenIds[i] = getAntToBeClaimed();
}
_batchMint( msg.sender, tokenIds );
}
| 13,367,539 | [
1,
9762,
731,
358,
4200,
392,
12994,
622,
3647,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
312,
474,
14925,
94,
12,
2254,
5034,
3844,
262,
3903,
8843,
429,
4894,
2520,
1299,
7516,
9217,
288,
203,
202,
202,
6528,
12,
1234,
18,
1132,
422,
312,
474,
5147,
380,
3844,
16,
315,
1248,
7304,
512,
1136,
358,
7516,
326,
392,
12994,
6,
11272,
203,
202,
202,
6528,
12,
3844,
1648,
943,
14925,
94,
2173,
3342,
16,
315,
6225,
848,
1338,
7516,
4200,
18830,
94,
1534,
8938,
6,
11272,
203,
202,
202,
6528,
12,
7516,
329,
14925,
94,
2173,
16936,
63,
3576,
18,
15330,
65,
397,
3844,
1648,
943,
14925,
94,
2173,
16936,
16,
315,
6225,
2780,
7516,
1898,
392,
12994,
6,
11272,
203,
202,
202,
6528,
12,
2319,
14925,
94,
18,
2469,
1545,
3844,
16,
315,
2279,
392,
12994,
2002,
358,
506,
7516,
329,
6,
11272,
203,
203,
202,
202,
430,
12,
3844,
422,
404,
262,
288,
203,
1082,
202,
14784,
14925,
5621,
203,
202,
202,
97,
203,
203,
202,
202,
11890,
5034,
8526,
3778,
1147,
2673,
273,
394,
2254,
5034,
8526,
12,
3844,
11272,
203,
203,
202,
202,
14784,
329,
14925,
94,
2173,
16936,
63,
3576,
18,
15330,
65,
1011,
3844,
31,
203,
202,
202,
4963,
49,
474,
329,
5157,
1011,
3844,
31,
203,
203,
202,
202,
1884,
261,
2254,
5034,
277,
31,
277,
411,
3844,
31,
277,
9904,
262,
288,
203,
1082,
202,
2316,
2673,
63,
77,
65,
273,
4506,
496,
15360,
9762,
329,
5621,
203,
202,
202,
97,
203,
203,
202,
202,
67,
5303,
49,
474,
12,
1234,
18,
15330,
16,
1147,
2673,
11272,
203,
202,
97,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./WhiteRabbitProducerPass.sol";
contract WhiteRabbit is Ownable, ERC1155Holder {
using Strings for uint256;
using SafeMath for uint256;
// The Producer Pass contract used for staking/voting on episodes
WhiteRabbitProducerPass private whiteRabbitProducerPass;
// The total number of episodes that make up the film
uint256 private _numberOfEpisodes;
// A mapping from episodeId to whether or not voting is enabled
mapping(uint256 => bool) public votingEnabledForEpisode;
// The address of the White Rabbit token ($WRAB)
address public whiteRabbitTokenAddress;
// The initial fixed supply of White Rabbit tokens
uint256 public tokenInitialFixedSupply;
// The wallet addresses of the two artists creating the film
address private _artist1Address;
address private _artist2Address;
// The percentage of White Rabbit tokens that will go to the artists
uint256 public artistTokenAllocationPercentage;
// The number of White Rabbit tokens to send to each artist per episode
uint256 public artistTokenPerEpisodePerArtist;
// A mapping from episodeId to a boolean indicating whether or not
// White Rabbit tokens have been transferred the artists yet
mapping(uint256 => bool) public hasTransferredTokensToArtistForEpisode;
// The percentage of White Rabbit tokens that will go to producers (via Producer Pass staking)
uint256 public producersTokenAllocationPercentage;
// The number of White Rabbit tokens to send to producers per episode
uint256 public producerPassTokenAllocationPerEpisode;
// The base number of White Rabbit tokens to allocate to producers per episode
uint256 public producerPassTokenBaseAllocationPerEpisode;
// The number of White Rabbit tokens to allocate to producers who stake early
uint256 public producerPassTokenEarlyStakingBonusAllocationPerEpisode;
// The number of White Rabbit tokens to allocate to producers who stake for the winning option
uint256 public producerPassTokenWinningBonusAllocationPerEpisode;
// The percentage of White Rabbit tokens that will go to the platform team
uint256 public teamTokenAllocationPercentage;
// Whether or not the team has received its share of White Rabbit tokens
bool public teamTokenAllocationDistributed;
// Event emitted when a Producer Pass is staked to vote for an episode option
event ProducerPassStaked(
address indexed account,
uint256 episodeId,
uint256 voteId,
uint256 amount,
uint256 tokenAmount
);
// Event emitted when a Producer Pass is unstaked after voting is complete
event ProducerPassUnstaked(
address indexed account,
uint256 episodeId,
uint256 voteId,
uint256 tokenAmount
);
// The list of episode IDs (e.g. [1, 2, 3, 4])
uint256[] public episodes;
// The voting option IDs by episodeId (e.g. 1 => [1, 2])
mapping(uint256 => uint256[]) private _episodeOptions;
// The total vote counts for each episode voting option, agnostic of users
// _episodeVotesByOptionId[episodeId][voteOptionId] => number of votes
mapping(uint256 => mapping(uint256 => uint256))
private _episodeVotesByOptionId;
// A mapping from episodeId to the winning vote option
// 0 means no winner has been declared yet
mapping(uint256 => uint256) public winningVoteOptionByEpisode;
// A mapping of how many Producer Passes have been staked per user per episode per option
// e.g. _usersStakedEpisodeVotingOptionsCount[address][episodeId][voteOptionId] => number staked
// These values will be updated/decremented when Producer Passes are unstaked
mapping(address => mapping(uint256 => mapping(uint256 => uint256)))
private _usersStakedEpisodeVotingOptionsCount;
// A mapping of the *history* how many Producer Passes have been staked per user per episode per option
// e.g. _usersStakedEpisodeVotingHistoryCount[address][episodeId][voteOptionId] => number staked
// Note: These values DO NOT change after Producer Passes are unstaked
mapping(address => mapping(uint256 => mapping(uint256 => uint256)))
private _usersStakedEpisodeVotingHistoryCount;
// The base URI for episode metadata
string private _episodeBaseURI;
// The base URI for episode voting option metadata
string private _episodeOptionBaseURI;
/**
* @dev Initializes the contract by setting up the Producer Pass contract to be used
*/
constructor(address whiteRabbitProducerPassContract) {
whiteRabbitProducerPass = WhiteRabbitProducerPass(
whiteRabbitProducerPassContract
);
}
/**
* @dev Sets the Producer Pass contract to be used
*/
function setWhiteRabbitProducerPassContract(
address whiteRabbitProducerPassContract
) external onlyOwner {
whiteRabbitProducerPass = WhiteRabbitProducerPass(
whiteRabbitProducerPassContract
);
}
/**
* @dev Sets the base URI for episode metadata
*/
function setEpisodeBaseURI(string memory baseURI) external onlyOwner {
_episodeBaseURI = baseURI;
}
/**
* @dev Sets the base URI for episode voting option metadata
*/
function setEpisodeOptionBaseURI(string memory baseURI) external onlyOwner {
_episodeOptionBaseURI = baseURI;
}
/**
* @dev Sets the list of episode IDs (e.g. [1, 2, 3, 4])
*
* This will be updated every time a new episode is added.
*/
function setEpisodes(uint256[] calldata _episodes) external onlyOwner {
episodes = _episodes;
}
/**
* @dev Sets the voting option IDs for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function setEpisodeOptions(
uint256 episodeId,
uint256[] calldata episodeOptionIds
) external onlyOwner {
require(episodeId <= episodes.length, "Episode does not exist");
_episodeOptions[episodeId] = episodeOptionIds;
}
/**
* @dev Retrieves the voting option IDs for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getEpisodeOptions(uint256 episodeId)
public
view
returns (uint256[] memory)
{
require(episodeId <= episodes.length, "Episode does not exist");
return _episodeOptions[episodeId];
}
/**
* @dev Retrieves the number of episodes currently available.
*/
function getCurrentEpisodeCount() external view returns (uint256) {
return episodes.length;
}
/**
* @dev Constructs the metadata URI for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function episodeURI(uint256 episodeId)
public
view
virtual
returns (string memory)
{
require(episodeId <= episodes.length, "Episode does not exist");
string memory baseURI = episodeBaseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(baseURI, episodeId.toString(), ".json")
)
: "";
}
/**
* @dev Constructs the metadata URI for a given episode voting option.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - The episode voting option ID is valid
*/
function episodeOptionURI(uint256 episodeId, uint256 episodeOptionId)
public
view
virtual
returns (string memory)
{
// TODO: DRY up these requirements? ("Episode does not exist", "Invalid voting option")
require(episodeId <= episodes.length, "Episode does not exist");
string memory baseURI = episodeOptionBaseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(
_episodeOptionBaseURI,
episodeId.toString(),
"/",
episodeOptionId.toString(),
".json"
)
)
: "";
}
/**
* @dev Getter for the `_episodeBaseURI`
*/
function episodeBaseURI() internal view virtual returns (string memory) {
return _episodeBaseURI;
}
/**
* @dev Getter for the `_episodeOptionBaseURI`
*/
function episodeOptionBaseURI()
internal
view
virtual
returns (string memory)
{
return _episodeOptionBaseURI;
}
/**
* @dev Retrieves the voting results for a given episode's voting option ID
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is no longer enabled for the given episode
* - Voting has completed and a winning option has been declared
*/
function episodeVotes(uint256 episodeId, uint256 episodeOptionId)
public
view
virtual
returns (uint256)
{
require(episodeId <= episodes.length, "Episode does not exist");
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
require(
winningVoteOptionByEpisode[episodeId] > 0,
"Voting not finished"
);
return _episodeVotesByOptionId[episodeId][episodeOptionId];
}
/**
* @dev Retrieves the number of Producer Passes that the user has staked
* for a given episode and voting option at this point in time.
*
* Note that this number will change after a user has unstaked.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function userStakedProducerPassCount(
uint256 episodeId,
uint256 episodeOptionId
) public view virtual returns (uint256) {
require(episodeId <= episodes.length, "Episode does not exist");
return
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
episodeOptionId
];
}
/**
* @dev Retrieves the historical number of Producer Passes that the user
* has staked for a given episode and voting option.
*
* Note that this number will not change as a result of unstaking.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function userStakedProducerPassCountHistory(
uint256 episodeId,
uint256 episodeOptionId
) public view virtual returns (uint256) {
require(episodeId <= episodes.length, "Episode does not exist");
return
_usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][
episodeOptionId
];
}
/**
* @dev Stakes Producer Passes for the given episode's voting option ID,
* with the ability to specify an `amount`. Staking is used to vote for the option
* that the user would like to see producers for the next episode.
*
* Emits a `ProducerPassStaked` event indicating that the staking was successful,
* including the total number of White Rabbit tokens allocated as a result.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is enabled for the given episode
* - The user is attempting to stake more than zero Producer Passes
* - The user has enough Producer Passes to stake
* - The episode voting option is valid
* - A winning option hasn't been declared yet
*/
function stakeProducerPass(
uint256 episodeId,
uint256 voteOptionId,
uint256 amount
) public {
require(episodeId <= episodes.length, "Episode does not exist");
require(votingEnabledForEpisode[episodeId], "Voting not enabled");
require(amount > 0, "Cannot stake 0");
require(
whiteRabbitProducerPass.balanceOf(msg.sender, episodeId) >= amount,
"Insufficient pass balance"
);
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
// vote options should be [1, 2], ID <= length
require(
votingOptionsForThisEpisode.length >= voteOptionId,
"Invalid voting option"
);
uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId];
// rely on winningVoteOptionId to determine that this episode is valid for voting on
require(winningVoteOptionId == 0, "Winner already declared");
// user's vote count for selected episode & option
uint256 userCurrentVoteCount = _usersStakedEpisodeVotingOptionsCount[
msg.sender
][episodeId][voteOptionId];
// Get total vote count of this option user is voting/staking for
uint256 currentTotalVoteCount = _episodeVotesByOptionId[episodeId][
voteOptionId
];
// Get total vote count from every option of this episode for bonding curve calculation
uint256 totalVotesForEpisode = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
totalVotesForEpisode += _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
}
// calculate token rewards here
uint256 tokensAllocated = getTokenAllocationForUserBeforeStaking(
episodeId,
amount
);
uint256 userNewVoteCount = userCurrentVoteCount + amount;
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
voteOptionId
] = userNewVoteCount;
_usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][
voteOptionId
] = userNewVoteCount;
_episodeVotesByOptionId[episodeId][voteOptionId] =
currentTotalVoteCount +
amount;
// Take custody of producer passes from user
whiteRabbitProducerPass.safeTransferFrom(
msg.sender,
address(this),
episodeId,
amount,
""
);
// Distribute wr tokens to user
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, tokensAllocated);
emit ProducerPassStaked(
msg.sender,
episodeId,
voteOptionId,
amount,
tokensAllocated
);
}
/**
* @dev Unstakes Producer Passes for the given episode's voting option ID and
* sends White Rabbit tokens to the user's wallet if they staked for the winning side.
*
*
* Emits a `ProducerPassUnstaked` event indicating that the unstaking was successful,
* including the total number of White Rabbit tokens allocated as a result.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is not enabled for the given episode
* - The episode voting option is valid
* - A winning option has been declared
*/
function unstakeProducerPasses(uint256 episodeId, uint256 voteOptionId)
public
{
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
uint256 stakedProducerPassCount = _usersStakedEpisodeVotingOptionsCount[
msg.sender
][episodeId][voteOptionId];
require(stakedProducerPassCount > 0, "No producer passes staked");
uint256 winningBonus = getUserWinningBonus(episodeId, voteOptionId) *
stakedProducerPassCount;
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
voteOptionId
] = 0;
if (winningBonus > 0) {
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, winningBonus);
}
whiteRabbitProducerPass.safeTransferFrom(
address(this),
msg.sender,
episodeId,
stakedProducerPassCount,
""
);
emit ProducerPassUnstaked(
msg.sender,
episodeId,
voteOptionId,
winningBonus
);
}
/**
* @dev Calculates the number of White Rabbit tokens to award the user for unstaking
* their Producer Passes for a given episode's voting option ID.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is not enabled for the given episode
* - The episode voting option is valid
* - A winning option has been declared
*/
function getUserWinningBonus(uint256 episodeId, uint256 episodeOptionId)
public
view
returns (uint256)
{
uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId];
require(winningVoteOptionId > 0, "Voting is not finished");
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
bool isWinningOption = winningVoteOptionId == episodeOptionId;
uint256 numberOfWinningVotes = _episodeVotesByOptionId[episodeId][
episodeOptionId
];
uint256 winningBonus = 0;
if (isWinningOption && numberOfWinningVotes > 0) {
winningBonus =
producerPassTokenWinningBonusAllocationPerEpisode /
numberOfWinningVotes;
}
return winningBonus;
}
/**
* @dev This method is only for the owner since we want to hide the voting results from the public
* until after voting has ended. Users can verify the veracity of this via the `episodeVotes` method
* which can be called publicly after voting has finished for an episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getTotalVotesForEpisode(uint256 episodeId)
external
view
onlyOwner
returns (uint256[] memory)
{
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256[] memory totalVotes = new uint256[](
votingOptionsForThisEpisode.length
);
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
totalVotes[i] = votesForEpisode;
}
return totalVotes;
}
/**
* @dev Owner method to toggle the voting state of a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - The voting state is different than the current state
* - A winning option has not yet been declared
*/
function setVotingEnabledForEpisode(uint256 episodeId, bool enabled)
public
onlyOwner
{
require(episodeId <= episodes.length, "Episode does not exist");
require(
votingEnabledForEpisode[episodeId] != enabled,
"Voting state unchanged"
);
// if winner already set, don't allow re-opening of voting
if (enabled) {
require(
winningVoteOptionByEpisode[episodeId] == 0,
"Winner for episode already set"
);
}
votingEnabledForEpisode[episodeId] = enabled;
}
/**
* @dev Sets up the distribution parameters for White Rabbit (WRAB) tokens.
*
* - We will create fractionalized NFT basket first, which will represent the finished film NFT
* - Tokens will be stored on platform and distributed to artists and producers as the film progresses
* - Artist distribution happens when new episodes are uploaded
* - Producer distribution happens when Producer Passes are staked and unstaked (with a bonus for winning the vote)
*
* Requirements:
*
* - The allocation percentages do not exceed 100%
*/
function startWhiteRabbitShowWithParams(
address tokenAddress,
address artist1Address,
address artist2Address,
uint256 numberOfEpisodes,
uint256 producersAllocationPercentage,
uint256 artistAllocationPercentage,
uint256 teamAllocationPercentage
) external onlyOwner {
require(
(producersAllocationPercentage +
artistAllocationPercentage +
teamAllocationPercentage) <= 100,
"Total percentage exceeds 100"
);
whiteRabbitTokenAddress = tokenAddress;
tokenInitialFixedSupply = IERC20(whiteRabbitTokenAddress).totalSupply();
_artist1Address = artist1Address;
_artist2Address = artist2Address;
_numberOfEpisodes = numberOfEpisodes;
producersTokenAllocationPercentage = producersAllocationPercentage;
artistTokenAllocationPercentage = artistAllocationPercentage;
teamTokenAllocationPercentage = teamAllocationPercentage;
// If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100 * 2) => 28571
artistTokenPerEpisodePerArtist =
(tokenInitialFixedSupply * artistTokenAllocationPercentage) /
(_numberOfEpisodes * 100 * 2); // 2 for 2 artists
// If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100) => 57142
producerPassTokenAllocationPerEpisode =
(tokenInitialFixedSupply * producersTokenAllocationPercentage) /
(_numberOfEpisodes * 100);
}
/**
* @dev Sets the White Rabbit (WRAB) token distrubution for producers.
* This distribution is broken into 3 categories:
* - Base allocation (every Producer Pass gets the same)
* - Early staking bonus (bonding curve distribution where earlier stakers are rewarded more)
* - Winning bonus (extra pot split among winning voters)
*
* Requirements:
*
* - The allocation percentages do not exceed 100%
*/
function setProducerPassWhiteRabbitTokensAllocationParameters(
uint256 earlyStakingBonus,
uint256 winningVoteBonus
) external onlyOwner {
require(
(earlyStakingBonus + winningVoteBonus) <= 100,
"Total percentage exceeds 100"
);
uint256 basePercentage = 100 - earlyStakingBonus - winningVoteBonus;
producerPassTokenBaseAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * basePercentage) /
100;
producerPassTokenEarlyStakingBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * earlyStakingBonus) /
100;
producerPassTokenWinningBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * winningVoteBonus) /
100;
}
/**
* @dev Calculates the number of White Rabbit tokens the user would receive if the
* provided `amount` of Producer Passes is staked for the given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getTokenAllocationForUserBeforeStaking(
uint256 episodeId,
uint256 amount
) public view returns (uint256) {
ProducerPass memory pass = whiteRabbitProducerPass
.getEpisodeToProducerPass(episodeId);
uint256 maxSupply = pass.maxSupply;
uint256 basePerPass = SafeMath.div(
producerPassTokenBaseAllocationPerEpisode,
maxSupply
);
// Get total vote count from every option of this episode for bonding curve calculation
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256 totalVotesForEpisode = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
totalVotesForEpisode += _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
}
// Below calculates number of tokens user will receive if staked
// using a linear bonding curve where early stakers get more
// Y = aX (where X = number of stakers, a = Slope, Y = tokens each staker receives)
uint256 maxBonusY = 1000 *
((producerPassTokenEarlyStakingBonusAllocationPerEpisode * 2) /
maxSupply);
uint256 slope = SafeMath.div(maxBonusY, maxSupply);
uint256 y1 = (slope * (maxSupply - totalVotesForEpisode));
uint256 y2 = (slope * (maxSupply - totalVotesForEpisode - amount));
uint256 earlyStakingBonus = (amount * (y1 + y2)) / 2;
return basePerPass * amount + earlyStakingBonus / 1000;
}
function endVotingForEpisode(uint256 episodeId) external onlyOwner {
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256 winningOptionId = 0;
uint256 totalVotesForWinningOption = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentOptionId = votingOptionsForThisEpisode[i];
uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][
currentOptionId
];
if (votesForEpisode >= totalVotesForWinningOption) {
winningOptionId = currentOptionId;
totalVotesForWinningOption = votesForEpisode;
}
}
setVotingEnabledForEpisode(episodeId, false);
winningVoteOptionByEpisode[episodeId] = winningOptionId;
}
/**
* @dev Manually sets the winning voting option for a given episode.
* Only call this method to break a tie among voting options for an episode.
*
* Requirements:
*
* - This should only be called for ties
*/
function endVotingForEpisodeOverride(
uint256 episodeId,
uint256 winningOptionId
) external onlyOwner {
setVotingEnabledForEpisode(episodeId, false);
winningVoteOptionByEpisode[episodeId] = winningOptionId;
}
/**
* Token distribution for artists and team
*/
/**
* @dev Sends the artists their allocation of White Rabbit tokens after an episode is launched.
*
* Requirements:
*
* - The artists have not yet received their tokens for the given episode
*/
function sendArtistTokensForEpisode(uint256 episodeId) external onlyOwner {
require(
!hasTransferredTokensToArtistForEpisode[episodeId],
"Artist tokens distributed"
);
hasTransferredTokensToArtistForEpisode[episodeId] = true;
IERC20(whiteRabbitTokenAddress).transfer(
_artist1Address,
artistTokenPerEpisodePerArtist
);
IERC20(whiteRabbitTokenAddress).transfer(
_artist2Address,
artistTokenPerEpisodePerArtist
);
}
/**
* @dev Transfers White Rabbit tokens to the team based on the `teamTokenAllocationPercentage`
*
* Requirements:
*
* - The tokens have not yet been distributed to the team
*/
function withdrawTokensForTeamAllocation(address[] calldata teamAddresses)
external
onlyOwner
{
require(!teamTokenAllocationDistributed, "Team tokens distributed");
uint256 teamBalancePerMember = (teamTokenAllocationPercentage *
tokenInitialFixedSupply) / (100 * teamAddresses.length);
for (uint256 i = 0; i < teamAddresses.length; i++) {
IERC20(whiteRabbitTokenAddress).transfer(
teamAddresses[i],
teamBalancePerMember
);
}
teamTokenAllocationDistributed = true;
}
/**
* @dev Transfers White Rabbit tokens to the team based on the platform allocation
*
* Requirements:
*
* - All Episodes finished
* - Voting completed
*/
function withdrawPlatformReserveTokens() external onlyOwner {
require(episodes.length == _numberOfEpisodes, "Show not ended");
require(
!votingEnabledForEpisode[_numberOfEpisodes],
"Last episode still voting"
);
uint256 leftOverBalance = IERC20(whiteRabbitTokenAddress).balanceOf(
address(this)
);
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, leftOverBalance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// 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/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/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
struct ProducerPass {
uint256 price;
uint256 episodeId;
uint256 maxSupply;
uint256 maxPerWallet;
uint256 openMintTimestamp; // unix timestamp in seconds
bytes32 merkleRoot;
}
contract WhiteRabbitProducerPass is ERC1155, ERC1155Supply, Ownable {
using Strings for uint256;
// The name of the token ("White Rabbit Producer Pass")
string public name;
// The token symbol ("WRPP")
string public symbol;
// The wallet addresses of the two artists creating the film
address payable private artistAddress1;
address payable private artistAddress2;
// The wallet addresses of the three developers managing the film
address payable private devAddress1;
address payable private devAddress2;
address payable private devAddress3;
// The royalty percentages for the artists and developers
uint256 private constant ARTIST_ROYALTY_PERCENTAGE = 60;
uint256 private constant DEV_ROYALTY_PERCENTAGE = 40;
// A mapping of the number of Producer Passes minted per episodeId per user
// userPassesMintedPerTokenId[msg.sender][episodeId] => number of minted passes
mapping(address => mapping(uint256 => uint256))
private userPassesMintedPerTokenId;
// A mapping from episodeId to its Producer Pass
mapping(uint256 => ProducerPass) private episodeToProducerPass;
// Event emitted when a Producer Pass is bought
event ProducerPassBought(
uint256 episodeId,
address indexed account,
uint256 amount
);
/**
* @dev Initializes the contract by setting the name and the token symbol
*/
constructor(string memory baseURI) ERC1155(baseURI) {
name = "White Rabbit Producer Pass";
symbol = "WRPP";
}
/**
* @dev Checks if the provided Merkle Proof is valid for the given root hash.
*/
function isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root)
internal
view
returns (bool)
{
return
MerkleProof.verify(
merkleProof,
root,
keccak256(abi.encodePacked(msg.sender))
);
}
/**
* @dev Retrieves the Producer Pass for a given episode.
*/
function getEpisodeToProducerPass(uint256 episodeId)
external
view
returns (ProducerPass memory)
{
return episodeToProducerPass[episodeId];
}
/**
* @dev Contracts the metadata URI for the Producer Pass of the given episodeId.
*
* Requirements:
*
* - The Producer Pass exists for the given episode
*/
function uri(uint256 episodeId)
public
view
override
returns (string memory)
{
require(
episodeToProducerPass[episodeId].episodeId != 0,
"Invalid episode"
);
return
string(
abi.encodePacked(
super.uri(episodeId),
episodeId.toString(),
".json"
)
);
}
/**
* Owner-only methods
*/
/**
* @dev Sets the base URI for the Producer Pass metadata.
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_setURI(baseURI);
}
/**
* @dev Sets the parameters on the Producer Pass struct for the given episode.
*/
function setProducerPass(
uint256 price,
uint256 episodeId,
uint256 maxSupply,
uint256 maxPerWallet,
uint256 openMintTimestamp,
bytes32 merkleRoot
) external onlyOwner {
episodeToProducerPass[episodeId] = ProducerPass(
price,
episodeId,
maxSupply,
maxPerWallet,
openMintTimestamp,
merkleRoot
);
}
/**
* @dev Withdraws the balance and distributes it to the artists and developers
* based on the `ARTIST_ROYALTY_PERCENTAGE` and `DEV_ROYALTY_PERCENTAGE`.
*/
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
uint256 artistBalance = (balance * ARTIST_ROYALTY_PERCENTAGE) / 100;
uint256 balancePerArtist = artistBalance / 2;
uint256 devBalance = (balance * DEV_ROYALTY_PERCENTAGE) / 100;
uint256 balancePerDev = devBalance / 3;
bool success;
// Transfer artist balances
(success, ) = artistAddress1.call{value: balancePerArtist}("");
require(success, "Withdraw unsuccessful");
(success, ) = artistAddress2.call{value: balancePerArtist}("");
require(success, "Withdraw unsuccessful");
// Transfer dev balances
(success, ) = devAddress1.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
(success, ) = devAddress2.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
(success, ) = devAddress3.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
}
/**
* @dev Sets the royalty addresses for the two artists and three developers.
*/
function setRoyaltyAddresses(
address _a1,
address _a2,
address _d1,
address _d2,
address _d3
) external onlyOwner {
artistAddress1 = payable(_a1);
artistAddress2 = payable(_a2);
devAddress1 = payable(_d1);
devAddress2 = payable(_d2);
devAddress3 = payable(_d3);
}
/**
* @dev Creates a reserve of Producer Passes to set aside for gifting.
*
* Requirements:
*
* - There are enough Producer Passes to mint for the given episode
* - The supply for the given episode does not exceed the maxSupply of the Producer Pass
*/
function reserveProducerPassesForGifting(
uint256 episodeId,
uint256 amountEachAddress,
address[] calldata addresses
) public onlyOwner {
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(amountEachAddress > 0, "Amount cannot be 0");
require(totalSupply(episodeId) < pass.maxSupply, "No passes to mint");
require(
totalSupply(episodeId) + amountEachAddress * addresses.length <=
pass.maxSupply,
"Cannot mint that many"
);
require(addresses.length > 0, "Need addresses");
for (uint256 i = 0; i < addresses.length; i++) {
address add = addresses[i];
_mint(add, episodeId, amountEachAddress, "");
}
}
/**
* @dev Mints a set number of Producer Passes for a given episode.
*
* Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully.
*
* Requirements:
*
* - The current time is within the minting window for the given episode
* - There are Producer Passes available to mint for the given episode
* - The user is not trying to mint more than the maxSupply
* - The user is not trying to mint more than the maxPerWallet
* - The user has enough ETH for the transaction
*/
function mintProducerPass(uint256 episodeId, uint256 amount)
external
payable
{
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(
block.timestamp >= pass.openMintTimestamp,
"Mint is not available"
);
require(totalSupply(episodeId) < pass.maxSupply, "Sold out");
require(
totalSupply(episodeId) + amount <= pass.maxSupply,
"Cannot mint that many"
);
uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][
episodeId
];
require(
totalMintedPasses + amount <= pass.maxPerWallet,
"Exceeding maximum per wallet"
);
require(msg.value == pass.price * amount, "Not enough eth");
userPassesMintedPerTokenId[msg.sender][episodeId] =
totalMintedPasses +
amount;
_mint(msg.sender, episodeId, amount, "");
emit ProducerPassBought(episodeId, msg.sender, amount);
}
/**
* @dev For those on with early access (on the whitelist),
* mints a set number of Producer Passes for a given episode.
*
* Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully.
*
* Requirements:
*
* - Provides a valid Merkle proof, indicating the user is on the whitelist
* - There are Producer Passes available to mint for the given episode
* - The user is not trying to mint more than the maxSupply
* - The user is not trying to mint more than the maxPerWallet
* - The user has enough ETH for the transaction
*/
function earlyMintProducerPass(
uint256 episodeId,
uint256 amount,
bytes32[] calldata merkleProof
) external payable {
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(
isValidMerkleProof(merkleProof, pass.merkleRoot),
"Not authorized to mint"
);
require(totalSupply(episodeId) < pass.maxSupply, "Sold out");
require(
totalSupply(episodeId) + amount <= pass.maxSupply,
"Cannot mint that many"
);
uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][
episodeId
];
require(
totalMintedPasses + amount <= pass.maxPerWallet,
"Exceeding maximum per wallet"
);
require(msg.value == pass.price * amount, "Not enough eth");
userPassesMintedPerTokenId[msg.sender][episodeId] =
totalMintedPasses +
amount;
_mint(msg.sender, episodeId, amount, "");
emit ProducerPassBought(episodeId, msg.sender, amount);
}
/**
* @dev Retrieves the number of Producer Passes a user has minted by episodeId.
*/
function userPassesMintedByEpisodeId(uint256 episodeId)
external
view
returns (uint256)
{
return userPassesMintedPerTokenId[msg.sender][episodeId];
}
/**
* @dev Boilerplate override for `_beforeTokenTransfer`
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// 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/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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
}
// 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;
}
} | * @dev Getter for the `_episodeOptionBaseURI`/ | function episodeOptionBaseURI()
internal
view
virtual
returns (string memory)
{
return _episodeOptionBaseURI;
}
| 1,528,189 | [
1,
8461,
364,
326,
1375,
67,
29687,
1895,
2171,
3098,
68,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
17054,
1895,
2171,
3098,
1435,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
327,
389,
29687,
1895,
2171,
3098,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./lib/Babylonian.sol";
import "./owner/Operator.sol";
import "./utils/ContractGuard.sol";
import "./interfaces/IBasisAsset.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/ITheoretics.sol";
import "./interfaces/IERC20Burnable.sol";
contract Treasury is ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========= CONSTANT VARIABLES ======== */
uint256 public constant PERIOD = 6 hours;
/* ========== STATE VARIABLES ========== */
// governance
address public operator;
// flags
bool public initialized = false;
// epoch
uint256 public startTime;
uint256 public epoch = 0;
uint256 public epochSupplyContractionLeft = 0;
// exclusions from total supply
address[] public excludedFromTotalSupply;
// core components
address public game;
address public hodl;
address public theory;
address public theoretics;
address public bondTreasury;
address public gameOracle;
// price
uint256 public gamePriceOne;
uint256 public gamePriceCeiling;
uint256 public seigniorageSaved;
uint256[] public supplyTiers;
uint256[] public maxExpansionTiers;
uint256 public maxSupplyExpansionPercent;
uint256 public bondDepletionFloorPercent;
uint256 public seigniorageExpansionFloorPercent;
uint256 public maxSupplyContractionPercent;
uint256 public maxDebtRatioPercent;
uint256 public bondSupplyExpansionPercent;
// 28 first epochs (1 week) with 4.5% expansion regardless of GAME price
uint256 public bootstrapEpochs;
uint256 public bootstrapSupplyExpansionPercent;
/* =================== Added variables =================== */
uint256 public previousEpochGamePrice;
uint256 public maxDiscountRate; // when purchasing bond
uint256 public maxPremiumRate; // when redeeming bond
uint256 public discountPercent;
uint256 public premiumThreshold;
uint256 public premiumPercent;
uint256 public mintingFactorForPayingDebt; // print extra GAME during debt phase
address public daoFund;
uint256 public daoFundSharedPercent;
address public devFund;
uint256 public devFundSharedPercent;
/* =================== Events =================== */
event Initialized(address indexed executor, uint256 at);
event BurnedBonds(address indexed from, uint256 bondAmount);
event RedeemedBonds(address indexed from, uint256 gameAmount, uint256 bondAmount);
event BoughtBonds(address indexed from, uint256 gameAmount, uint256 bondAmount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event theoreticsFunded(uint256 timestamp, uint256 seigniorage);
event DaoFundFunded(uint256 timestamp, uint256 seigniorage);
event DevFundFunded(uint256 timestamp, uint256 seigniorage);
/* =================== Modifier =================== */
modifier onlyOperator() {
require(operator == msg.sender, "Treasury: caller is not the operator");
_;
}
modifier checkCondition {
require(block.timestamp >= startTime, "Treasury: not started yet");
_;
}
modifier checkEpoch {
require(block.timestamp >= nextEpochPoint(), "Treasury: not opened yet");
_;
epoch = epoch.add(1);
epochSupplyContractionLeft = (getGamePrice() > gamePriceCeiling) ? 0 : getGameCirculatingSupply().mul(maxSupplyContractionPercent).div(10000);
}
modifier checkOperator {
require(
IBasisAsset(game).operator() == address(this) &&
IBasisAsset(hodl).operator() == address(this) &&
IBasisAsset(theory).operator() == address(this) &&
Operator(theoretics).operator() == address(this),
"Treasury: need more permission"
);
_;
}
modifier notInitialized {
require(!initialized, "Treasury: already initialized");
_;
}
/* ========== VIEW FUNCTIONS ========== */
function isInitialized() public view returns (bool) {
return initialized;
}
// epoch
function nextEpochPoint() public view returns (uint256) {
return startTime.add(epoch.mul(PERIOD));
}
function shouldAllocateSeigniorage() external view returns (bool) // For bots.
{
return block.timestamp >= startTime && block.timestamp >= nextEpochPoint() && ITheoretics(theoretics).totalSupply() > 0;
}
// oracle
function getGamePrice() public view returns (uint256 gamePrice) {
try IOracle(gameOracle).consult(game, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult GAME price from the oracle");
}
}
function getGameUpdatedPrice() public view returns (uint256 _gamePrice) {
try IOracle(gameOracle).twap(game, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult GAME price from the oracle");
}
}
// budget
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
function getBurnableGameLeft() public view returns (uint256 _burnableGameLeft) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
uint256 _gameSupply = getGameCirculatingSupply();
uint256 _bondMaxSupply = _gameSupply.mul(maxDebtRatioPercent).div(10000);
uint256 _bondSupply = IERC20(hodl).totalSupply();
if (_bondMaxSupply > _bondSupply) {
uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply);
uint256 _maxBurnableGame = _maxMintableBond.mul(_gamePrice).div(1e18);
_burnableGameLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGame);
}
}
}
function getRedeemableBonds() external view returns (uint256) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _totalGame = IERC20(game).balanceOf(address(this));
uint256 _rate = getBondPremiumRate();
if (_rate > 0) {
return _totalGame.mul(1e18).div(_rate);
}
}
return 0;
}
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
if (discountPercent == 0) {
// no discount
_rate = gamePriceOne;
} else {
uint256 _bondAmount = gamePriceOne.mul(1e18).div(_gamePrice); // to burn 1 GAME
uint256 _discountAmount = _bondAmount.sub(gamePriceOne).mul(discountPercent).div(10000);
_rate = gamePriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _gamePricePremiumThreshold = gamePriceOne.mul(premiumThreshold).div(100);
if (_gamePrice >= _gamePricePremiumThreshold) {
//Price > 1.10
uint256 _premiumAmount = _gamePrice.sub(gamePriceOne).mul(premiumPercent).div(10000);
_rate = gamePriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
} else {
// no premium bonus
_rate = gamePriceOne;
}
}
}
/* ========== GOVERNANCE ========== */
function initialize(
address _game,
address _hodl,
address _theory,
address _gameOracle,
address _theoretics,
address _genesisPool,
address _daoFund,
address _devFund,
uint256 _startTime
) public notInitialized {
initialized = true;
// We could require() for all of these...
game = _game;
hodl = _hodl;
theory = _theory;
gameOracle = _gameOracle;
theoretics = _theoretics;
daoFund = _daoFund;
devFund = _devFund;
require(block.timestamp < _startTime, "late");
startTime = _startTime;
gamePriceOne = 10**18;
gamePriceCeiling = gamePriceOne.mul(101).div(100);
// exclude contracts from total supply
excludedFromTotalSupply.push(_genesisPool);
// Dynamic max expansion percent
supplyTiers = [0 ether, 500000 ether, 1000000 ether, 1500000 ether, 2000000 ether, 5000000 ether, 10000000 ether, 20000000 ether, 50000000 ether];
maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100];
maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion
bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor
seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for theoretics
maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn GAME and mint HODL)
maxDebtRatioPercent = 3500; // Upto 35% supply of HODL to purchase
bondSupplyExpansionPercent = 500; // maximum 5% emissions per epoch for POL bonds
premiumThreshold = 110;
premiumPercent = 7000;
// First 12 epochs with 5% expansion
bootstrapEpochs = 12;
bootstrapSupplyExpansionPercent = 500;
// set seigniorageSaved to it's balance
seigniorageSaved = IERC20(game).balanceOf(address(this));
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setTheoretics(address _theoretics) external onlyOperator { // Scary function, but also can be used to upgrade. However, since I don't have a multisig to start, and it isn't THAT important, I'm going to leave this be.
theoretics = _theoretics;
}
function setGameOracle(address _gameOracle) external onlyOperator { // See above.
gameOracle = _gameOracle;
}
function setGamePriceCeiling(uint256 _gamePriceCeiling) external onlyOperator { // I don't see this changing, so I'm going to leave this be.
require(_gamePriceCeiling >= gamePriceOne && _gamePriceCeiling <= gamePriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2]
gamePriceCeiling = _gamePriceCeiling;
}
function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { // I don't see this changing, so I'm going to leave this be.
require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%]
maxSupplyExpansionPercent = _maxSupplyExpansionPercent;
}
function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
if (_index > 0) {
require(_value > supplyTiers[_index - 1]);
}
if (_index < 8) {
require(_value < supplyTiers[_index + 1]);
}
supplyTiers[_index] = _value;
return true;
}
function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%]
maxExpansionTiers[_index] = _value;
return true;
}
function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator {
require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%]
bondDepletionFloorPercent = _bondDepletionFloorPercent;
}
function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator {
require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%]
maxSupplyContractionPercent = _maxSupplyContractionPercent;
}
function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator {
require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%]
maxDebtRatioPercent = _maxDebtRatioPercent;
}
function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator {
require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month
require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%]
bootstrapEpochs = _bootstrapEpochs;
bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent;
}
function setExtraFunds(
address _daoFund,
uint256 _daoFundSharedPercent,
address _devFund,
uint256 _devFundSharedPercent
) external onlyOperator {
require(_daoFund != address(0), "zero");
require(_daoFundSharedPercent <= 3000, "out of range"); // <= 30%
require(_devFund != address(0), "zero");
require(_devFundSharedPercent <= 1000, "out of range"); // <= 10%
daoFund = _daoFund;
daoFundSharedPercent = _daoFundSharedPercent;
devFund = _devFund;
devFundSharedPercent = _devFundSharedPercent;
}
function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator {
maxDiscountRate = _maxDiscountRate;
}
function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator {
maxPremiumRate = _maxPremiumRate;
}
function setDiscountPercent(uint256 _discountPercent) external onlyOperator {
require(_discountPercent <= 20000, "_discountPercent is over 200%");
discountPercent = _discountPercent;
}
function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator {
require(_premiumThreshold >= gamePriceCeiling, "_premiumThreshold exceeds gamePriceCeiling");
require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5");
premiumThreshold = _premiumThreshold;
}
function setPremiumPercent(uint256 _premiumPercent) external onlyOperator {
require(_premiumPercent <= 20000, "_premiumPercent is over 200%");
premiumPercent = _premiumPercent;
}
function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator {
require(_mintingFactorForPayingDebt == 0 || (_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000), "_mintingFactorForPayingDebt: out of range"); // [100%, 200%]
mintingFactorForPayingDebt = _mintingFactorForPayingDebt;
}
function setBondSupplyExpansionPercent(uint256 _bondSupplyExpansionPercent) external onlyOperator {
bondSupplyExpansionPercent = _bondSupplyExpansionPercent;
}
/* ========== MUTABLE FUNCTIONS ========== */
function _updateGamePrice() internal {
try IOracle(gameOracle).update() {} catch {}
}
function getGameCirculatingSupply() public view returns (uint256) {
IERC20 gameErc20 = IERC20(game);
uint256 totalSupply = gameErc20.totalSupply();
uint256 balanceExcluded = 0;
uint256 entryId;
uint256 len = excludedFromTotalSupply.length;
for (entryId = 0; entryId < len; entryId += 1) {
balanceExcluded = balanceExcluded.add(gameErc20.balanceOf(excludedFromTotalSupply[entryId]));
}
return totalSupply.sub(balanceExcluded);
}
function buyBonds(uint256 _gameAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_gameAmount > 0, "Treasury: cannot purchase bonds with zero amount");
uint256 gamePrice = getGamePrice();
require(gamePrice == targetPrice, "Treasury: GAME price moved");
require(
gamePrice < gamePriceOne, // price < $1
"Treasury: gamePrice not eligible for bond purchase"
);
require(_gameAmount <= epochSupplyContractionLeft, "Treasury: Not enough bonds left to purchase");
uint256 _rate = getBondDiscountRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _bondAmount = _gameAmount.mul(_rate).div(1e18);
uint256 gameSupply = getGameCirculatingSupply();
uint256 newBondSupply = IERC20(hodl).totalSupply().add(_bondAmount);
require(newBondSupply <= gameSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio");
IBasisAsset(game).burnFrom(msg.sender, _gameAmount);
IBasisAsset(hodl).mint(msg.sender, _bondAmount);
epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_gameAmount);
_updateGamePrice();
emit BoughtBonds(msg.sender, _gameAmount, _bondAmount);
}
function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount");
uint256 gamePrice = getGamePrice();
require(gamePrice == targetPrice, "Treasury: GAME price moved");
require(
gamePrice > gamePriceCeiling, // price > $1.01
"Treasury: gamePrice not eligible for bond redemption"
);
uint256 _rate = getBondPremiumRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _gameAmount = _bondAmount.mul(_rate).div(1e18);
require(IERC20(game).balanceOf(address(this)) >= _gameAmount, "Treasury: treasury has no more budget");
seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _gameAmount));
IBasisAsset(hodl).burnFrom(msg.sender, _bondAmount);
IERC20(game).safeTransfer(msg.sender, _gameAmount);
_updateGamePrice();
emit RedeemedBonds(msg.sender, _gameAmount, _bondAmount);
}
function _sendToTheoretics(uint256 _amount) internal {
IBasisAsset(game).mint(address(this), _amount);
uint256 _daoFundSharedAmount = 0;
if (daoFundSharedPercent > 0) {
_daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000);
IERC20(game).transfer(daoFund, _daoFundSharedAmount);
emit DaoFundFunded(block.timestamp, _daoFundSharedAmount);
}
uint256 _devFundSharedAmount = 0;
if (devFundSharedPercent > 0) {
_devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000);
IERC20(game).transfer(devFund, _devFundSharedAmount);
emit DevFundFunded(block.timestamp, _devFundSharedAmount);
}
_amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount);
IERC20(game).safeApprove(theoretics, 0);
IERC20(game).safeApprove(theoretics, _amount);
ITheoretics(theoretics).allocateSeigniorage(_amount);
emit theoreticsFunded(block.timestamp, _amount);
}
function _calculateMaxSupplyExpansionPercent(uint256 _gameSupply) internal returns (uint256) {
for (uint8 tierId = 8; tierId >= 0; --tierId) {
if (_gameSupply >= supplyTiers[tierId]) {
maxSupplyExpansionPercent = maxExpansionTiers[tierId];
break;
}
}
return maxSupplyExpansionPercent;
}
function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator {
_updateGamePrice();
previousEpochGamePrice = getGamePrice();
uint256 gameSupply = getGameCirculatingSupply().sub(seigniorageSaved);
if (epoch < bootstrapEpochs) {
// 28 first epochs with 4.5% expansion
_sendToTheoretics(gameSupply.mul(bootstrapSupplyExpansionPercent).div(10000));
} else {
if (previousEpochGamePrice > gamePriceCeiling) {
// Expansion ($GAME Price > 1 $FTM): there is some seigniorage to be allocated
uint256 bondSupply = IERC20(hodl).totalSupply();
uint256 _percentage = previousEpochGamePrice.sub(gamePriceOne);
uint256 _savedForBond = 0;
uint256 _savedForTheoretics;
uint256 _mse = _calculateMaxSupplyExpansionPercent(gameSupply).mul(1e14);
if (_percentage > _mse) {
_percentage = _mse;
}
if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) {
// saved enough to pay debt, mint as usual rate
_savedForTheoretics = gameSupply.mul(_percentage).div(1e18);
} else {
// have not saved enough to pay debt, mint more
uint256 _seigniorage = gameSupply.mul(_percentage).div(1e18);
_savedForTheoretics = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000);
_savedForBond = _seigniorage.sub(_savedForTheoretics);
if (mintingFactorForPayingDebt > 0) {
_savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000);
}
}
if (_savedForTheoretics > 0) {
_sendToTheoretics(_savedForTheoretics);
}
if (_savedForBond > 0) {
seigniorageSaved = seigniorageSaved.add(_savedForBond);
IBasisAsset(game).mint(address(this), _savedForBond);
emit TreasuryFunded(block.timestamp, _savedForBond);
}
}
}
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
// do not allow to drain core tokens
require(address(_token) != address(game), "game");
require(address(_token) != address(hodl), "bond");
require(address(_token) != address(theory), "share");
_token.safeTransfer(_to, _amount);
}
function theoreticsSetOperator(address _operator) external onlyOperator {
ITheoretics(theoretics).setOperator(_operator);
}
function theoreticsSetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs, uint256 _pegMaxUnlock) external onlyOperator {
ITheoretics(theoretics).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs, _pegMaxUnlock);
}
function theoreticsAllocateSeigniorage(uint256 amount) external onlyOperator {
ITheoretics(theoretics).allocateSeigniorage(amount);
}
function theoreticsGetCurrentWithdrawEpochs() public view returns (uint256) {
return ITheoretics(theoretics).getCurrentWithdrawEpochs();
}
function theoreticsGetCurrentClaimEpochs() public view returns (uint256) {
return ITheoretics(theoretics).getCurrentClaimEpochs();
}
function theoreticsGetWithdrawFeeOf(address _user) public view returns (uint256) {
return ITheoretics(theoretics).getWithdrawFeeOf(_user);
}
function theoreticsGovernanceRecoverUnsupported(
address _token,
uint256 _amount,
address _to
) external onlyOperator {
ITheoretics(theoretics).governanceRecoverUnsupported(_token, _amount, _to);
}
function theoreticsGetLockPercentage() public view returns (uint256) {
return ITheoretics(theoretics).getLockPercentage();
}
function burn(
address _token,
uint256 _amount
) external onlyOperator {
IERC20Burnable(_token).burn(_amount); // Burn any token that we own! Now we can burn THEORY and such with no problem to deflate it.
}
// Allow us to delay or begin earlier if we have not started yet.
function setStartTime(
uint256 _time
) public onlyOperator
{
require(block.timestamp < startTime, "Already started.");
require(block.timestamp < _time, "Time input is too early.");
startTime = _time;
}
}
| governance flags epoch exclusions from total supply core components price 28 first epochs (1 week) with 4.5% expansion regardless of GAME price | contract Treasury is ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
uint256 public constant PERIOD = 6 hours;
address public operator;
bool public initialized = false;
uint256 public startTime;
uint256 public epoch = 0;
uint256 public epochSupplyContractionLeft = 0;
address[] public excludedFromTotalSupply;
address public game;
address public hodl;
address public theory;
address public theoretics;
address public bondTreasury;
address public gameOracle;
uint256 public gamePriceOne;
uint256 public gamePriceCeiling;
uint256 public seigniorageSaved;
uint256[] public supplyTiers;
uint256[] public maxExpansionTiers;
uint256 public maxSupplyExpansionPercent;
uint256 public bondDepletionFloorPercent;
uint256 public seigniorageExpansionFloorPercent;
uint256 public maxSupplyContractionPercent;
uint256 public maxDebtRatioPercent;
uint256 public bondSupplyExpansionPercent;
uint256 public bootstrapEpochs;
uint256 public bootstrapSupplyExpansionPercent;
uint256 public previousEpochGamePrice;
uint256 public discountPercent;
uint256 public premiumThreshold;
uint256 public premiumPercent;
address public daoFund;
uint256 public daoFundSharedPercent;
address public devFund;
uint256 public devFundSharedPercent;
event Initialized(address indexed executor, uint256 at);
event BurnedBonds(address indexed from, uint256 bondAmount);
event RedeemedBonds(address indexed from, uint256 gameAmount, uint256 bondAmount);
event BoughtBonds(address indexed from, uint256 gameAmount, uint256 bondAmount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event theoreticsFunded(uint256 timestamp, uint256 seigniorage);
event DaoFundFunded(uint256 timestamp, uint256 seigniorage);
event DevFundFunded(uint256 timestamp, uint256 seigniorage);
modifier onlyOperator() {
require(operator == msg.sender, "Treasury: caller is not the operator");
_;
}
modifier checkCondition {
require(block.timestamp >= startTime, "Treasury: not started yet");
_;
}
modifier checkEpoch {
require(block.timestamp >= nextEpochPoint(), "Treasury: not opened yet");
_;
epoch = epoch.add(1);
epochSupplyContractionLeft = (getGamePrice() > gamePriceCeiling) ? 0 : getGameCirculatingSupply().mul(maxSupplyContractionPercent).div(10000);
}
modifier checkOperator {
require(
IBasisAsset(game).operator() == address(this) &&
IBasisAsset(hodl).operator() == address(this) &&
IBasisAsset(theory).operator() == address(this) &&
Operator(theoretics).operator() == address(this),
"Treasury: need more permission"
);
_;
}
modifier notInitialized {
require(!initialized, "Treasury: already initialized");
_;
}
function isInitialized() public view returns (bool) {
return initialized;
}
function nextEpochPoint() public view returns (uint256) {
return startTime.add(epoch.mul(PERIOD));
}
{
return block.timestamp >= startTime && block.timestamp >= nextEpochPoint() && ITheoretics(theoretics).totalSupply() > 0;
}
function getGamePrice() public view returns (uint256 gamePrice) {
try IOracle(gameOracle).consult(game, 1e18) returns (uint144 price) {
return uint256(price);
revert("Treasury: failed to consult GAME price from the oracle");
}
}
function getGamePrice() public view returns (uint256 gamePrice) {
try IOracle(gameOracle).consult(game, 1e18) returns (uint144 price) {
return uint256(price);
revert("Treasury: failed to consult GAME price from the oracle");
}
}
} catch {
function getGameUpdatedPrice() public view returns (uint256 _gamePrice) {
try IOracle(gameOracle).twap(game, 1e18) returns (uint144 price) {
return uint256(price);
revert("Treasury: failed to consult GAME price from the oracle");
}
}
function getGameUpdatedPrice() public view returns (uint256 _gamePrice) {
try IOracle(gameOracle).twap(game, 1e18) returns (uint144 price) {
return uint256(price);
revert("Treasury: failed to consult GAME price from the oracle");
}
}
} catch {
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
function getBurnableGameLeft() public view returns (uint256 _burnableGameLeft) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
uint256 _gameSupply = getGameCirculatingSupply();
uint256 _bondMaxSupply = _gameSupply.mul(maxDebtRatioPercent).div(10000);
uint256 _bondSupply = IERC20(hodl).totalSupply();
if (_bondMaxSupply > _bondSupply) {
uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply);
uint256 _maxBurnableGame = _maxMintableBond.mul(_gamePrice).div(1e18);
_burnableGameLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGame);
}
}
}
function getBurnableGameLeft() public view returns (uint256 _burnableGameLeft) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
uint256 _gameSupply = getGameCirculatingSupply();
uint256 _bondMaxSupply = _gameSupply.mul(maxDebtRatioPercent).div(10000);
uint256 _bondSupply = IERC20(hodl).totalSupply();
if (_bondMaxSupply > _bondSupply) {
uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply);
uint256 _maxBurnableGame = _maxMintableBond.mul(_gamePrice).div(1e18);
_burnableGameLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGame);
}
}
}
function getBurnableGameLeft() public view returns (uint256 _burnableGameLeft) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
uint256 _gameSupply = getGameCirculatingSupply();
uint256 _bondMaxSupply = _gameSupply.mul(maxDebtRatioPercent).div(10000);
uint256 _bondSupply = IERC20(hodl).totalSupply();
if (_bondMaxSupply > _bondSupply) {
uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply);
uint256 _maxBurnableGame = _maxMintableBond.mul(_gamePrice).div(1e18);
_burnableGameLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGame);
}
}
}
function getRedeemableBonds() external view returns (uint256) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _totalGame = IERC20(game).balanceOf(address(this));
uint256 _rate = getBondPremiumRate();
if (_rate > 0) {
return _totalGame.mul(1e18).div(_rate);
}
}
return 0;
}
function getRedeemableBonds() external view returns (uint256) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _totalGame = IERC20(game).balanceOf(address(this));
uint256 _rate = getBondPremiumRate();
if (_rate > 0) {
return _totalGame.mul(1e18).div(_rate);
}
}
return 0;
}
function getRedeemableBonds() external view returns (uint256) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _totalGame = IERC20(game).balanceOf(address(this));
uint256 _rate = getBondPremiumRate();
if (_rate > 0) {
return _totalGame.mul(1e18).div(_rate);
}
}
return 0;
}
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
if (discountPercent == 0) {
_rate = gamePriceOne;
uint256 _discountAmount = _bondAmount.sub(gamePriceOne).mul(discountPercent).div(10000);
_rate = gamePriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
if (discountPercent == 0) {
_rate = gamePriceOne;
uint256 _discountAmount = _bondAmount.sub(gamePriceOne).mul(discountPercent).div(10000);
_rate = gamePriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
if (discountPercent == 0) {
_rate = gamePriceOne;
uint256 _discountAmount = _bondAmount.sub(gamePriceOne).mul(discountPercent).div(10000);
_rate = gamePriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
} else {
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
if (discountPercent == 0) {
_rate = gamePriceOne;
uint256 _discountAmount = _bondAmount.sub(gamePriceOne).mul(discountPercent).div(10000);
_rate = gamePriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _gamePricePremiumThreshold = gamePriceOne.mul(premiumThreshold).div(100);
if (_gamePrice >= _gamePricePremiumThreshold) {
uint256 _premiumAmount = _gamePrice.sub(gamePriceOne).mul(premiumPercent).div(10000);
_rate = gamePriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _gamePricePremiumThreshold = gamePriceOne.mul(premiumThreshold).div(100);
if (_gamePrice >= _gamePricePremiumThreshold) {
uint256 _premiumAmount = _gamePrice.sub(gamePriceOne).mul(premiumPercent).div(10000);
_rate = gamePriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _gamePricePremiumThreshold = gamePriceOne.mul(premiumThreshold).div(100);
if (_gamePrice >= _gamePricePremiumThreshold) {
uint256 _premiumAmount = _gamePrice.sub(gamePriceOne).mul(premiumPercent).div(10000);
_rate = gamePriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _gamePricePremiumThreshold = gamePriceOne.mul(premiumThreshold).div(100);
if (_gamePrice >= _gamePricePremiumThreshold) {
uint256 _premiumAmount = _gamePrice.sub(gamePriceOne).mul(premiumPercent).div(10000);
_rate = gamePriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
}
}
}
} else {
_rate = gamePriceOne;
function initialize(
address _game,
address _hodl,
address _theory,
address _gameOracle,
address _theoretics,
address _genesisPool,
address _daoFund,
address _devFund,
uint256 _startTime
) public notInitialized {
initialized = true;
game = _game;
hodl = _hodl;
theory = _theory;
gameOracle = _gameOracle;
theoretics = _theoretics;
daoFund = _daoFund;
devFund = _devFund;
require(block.timestamp < _startTime, "late");
startTime = _startTime;
gamePriceOne = 10**18;
gamePriceCeiling = gamePriceOne.mul(101).div(100);
excludedFromTotalSupply.push(_genesisPool);
supplyTiers = [0 ether, 500000 ether, 1000000 ether, 1500000 ether, 2000000 ether, 5000000 ether, 10000000 ether, 20000000 ether, 50000000 ether];
maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100];
premiumThreshold = 110;
premiumPercent = 7000;
bootstrapEpochs = 12;
bootstrapSupplyExpansionPercent = 500;
seigniorageSaved = IERC20(game).balanceOf(address(this));
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
theoretics = _theoretics;
}
| 5,393,591 | [
1,
75,
1643,
82,
1359,
2943,
7632,
29523,
628,
2078,
14467,
2922,
4085,
6205,
9131,
1122,
25480,
261,
21,
4860,
13,
598,
1059,
18,
25,
9,
17965,
15255,
434,
611,
1642,
6205,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
399,
266,
345,
22498,
353,
13456,
16709,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
2254,
5034,
1071,
5381,
10950,
21054,
273,
1666,
7507,
31,
203,
203,
203,
565,
1758,
1071,
3726,
31,
203,
203,
565,
1426,
1071,
6454,
273,
629,
31,
203,
203,
565,
2254,
5034,
1071,
8657,
31,
203,
565,
2254,
5034,
1071,
7632,
273,
374,
31,
203,
565,
2254,
5034,
1071,
7632,
3088,
1283,
442,
25693,
3910,
273,
374,
31,
203,
203,
565,
1758,
8526,
1071,
8845,
1265,
5269,
3088,
1283,
31,
203,
203,
565,
1758,
1071,
7920,
31,
203,
565,
1758,
1071,
366,
369,
80,
31,
203,
565,
1758,
1071,
326,
630,
31,
203,
203,
565,
1758,
1071,
326,
479,
88,
2102,
31,
203,
565,
1758,
1071,
8427,
56,
266,
345,
22498,
31,
203,
565,
1758,
1071,
7920,
23601,
31,
203,
203,
565,
2254,
5034,
1071,
7920,
5147,
3335,
31,
203,
565,
2254,
5034,
1071,
7920,
5147,
39,
73,
4973,
31,
203,
203,
565,
2254,
5034,
1071,
695,
724,
77,
1531,
16776,
31,
203,
203,
565,
2254,
5034,
8526,
1071,
14467,
56,
20778,
31,
203,
565,
2254,
5034,
8526,
1071,
943,
2966,
12162,
56,
20778,
31,
203,
203,
565,
2254,
5034,
1071,
943,
3088,
1283,
2966,
12162,
8410,
31,
203,
565,
2254,
5034,
1071,
8427,
758,
1469,
285,
42,
5807,
8410,
31,
203,
565,
2254,
5034,
1071,
695,
724,
77,
1531,
2966,
12162,
2
] |
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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;
}
}
/**
* @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;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// Override this method to have a way to add business logic to your crowdsale when buying
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
return weiAmount.mul(rate);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
}
/**
* @title CappedCrowdsale
* @dev Extension of Crowdsale with a max amount of funds raised
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= cap;
return capReached || super.hasEnded();
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal view returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return withinCap && super.validPurchase();
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @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);
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 ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
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;
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);
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);
}
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/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
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;
MintFinished();
return true;
}
}
/**
* @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 {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
}
}
contract MIKETANGOBRAVO18 is MintableToken, BurnableToken {
string public constant name = "MIKETANGOBRAVO18";
string public constant symbol = "MTB18";
uint public constant decimals = 18;
function() public {}
}
contract MIKETANGOBRAVO18Crowdsale is CappedCrowdsale, FinalizableCrowdsale, Pausable {
uint256 public rate;
uint256 public totalTokenCapToCreate;
address public fundWallet;
function MIKETANGOBRAVO18Crowdsale (
uint256 _startTime,
uint256 _endTime,
uint256 _rate,
address _fundWallet,
uint256 _totalCapInEthToRaise,
uint256 _totalTokenCapToCreate,
uint256 _initialTokenFundBalance
) public
Crowdsale(_startTime, _endTime, _rate, _fundWallet)
CappedCrowdsale(_totalCapInEthToRaise)
FinalizableCrowdsale() {
rate = _rate;
fundWallet = _fundWallet;
totalTokenCapToCreate = _totalTokenCapToCreate;
token.mint(fundWallet, _initialTokenFundBalance);
}
function createTokenContract() internal returns (MintableToken) {
return new MIKETANGOBRAVO18();
}
// overriding CappedCrowdsale#validPurchase
// @return true if investors can buy at the moment
function validPurchase() internal view returns (bool) {
bool withinTokenCap = token.totalSupply().add(msg.value.mul(rate)) <= totalTokenCapToCreate;
bool nonZeroPurchase = msg.value != 0;
return super.validPurchase() && withinTokenCap && nonZeroPurchase;
}
// overriding CappedCrowdsale#hasEnded
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
uint256 threshold = totalTokenCapToCreate.div(100).mul(99);
bool thresholdReached = token.totalSupply() >= threshold;
return super.hasEnded() || thresholdReached;
}
// overriding FinalizableCrowdsale#finalization
// - To store remaining MTB18 tokens.
function finalization() internal {
uint256 remaining = totalTokenCapToCreate.sub(token.totalSupply());
if (remaining > 0) {
token.mint(fundWallet, remaining);
}
// change Token owner to fundWallet Fund.
token.transferOwnership(fundWallet);
super.finalization();
}
function remaining() public returns (uint256) {
return totalTokenCapToCreate.sub(token.totalSupply());
}
// overriding Crowdsale#buyTokens
function buyTokens(address beneficiary) public payable {
require(!paused);
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
} | * event for token purchase logging @param purchaser who paid for the tokens @param beneficiary who got the tokens @param value weis paid for purchase @param amount amount of tokens purchased/ | function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
| 5,771,117 | [
1,
2575,
364,
1147,
23701,
2907,
225,
5405,
343,
14558,
10354,
30591,
364,
326,
2430,
225,
27641,
74,
14463,
814,
10354,
2363,
326,
2430,
225,
460,
732,
291,
30591,
364,
23701,
225,
3844,
3844,
434,
2430,
5405,
343,
8905,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
385,
492,
2377,
5349,
12,
11890,
5034,
389,
1937,
950,
16,
2254,
5034,
389,
409,
950,
16,
2254,
5034,
389,
5141,
16,
1758,
389,
19177,
13,
1071,
288,
203,
565,
2583,
24899,
1937,
950,
1545,
2037,
1769,
203,
565,
2583,
24899,
409,
950,
1545,
389,
1937,
950,
1769,
203,
565,
2583,
24899,
5141,
405,
374,
1769,
203,
565,
2583,
24899,
19177,
480,
1758,
12,
20,
10019,
203,
565,
1147,
273,
752,
1345,
8924,
5621,
203,
565,
8657,
273,
389,
1937,
950,
31,
203,
565,
13859,
273,
389,
409,
950,
31,
203,
565,
4993,
273,
389,
5141,
31,
203,
565,
9230,
273,
389,
19177,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x00Ff7C9B41Ff6d622eaD27aF00a4a85e542E778c/sources/contracts/extension/SignatureMintERC721Upgradeable.sol | @dev Mapping from mint request UID => whether the mint request is processed. | function __SignatureMintERC721_init() internal onlyInitializing {
__EIP712_init("SignatureMintERC721", "1");
}
| 5,562,499 | [
1,
3233,
628,
312,
474,
590,
10034,
516,
2856,
326,
312,
474,
590,
353,
5204,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1001,
5374,
49,
474,
654,
39,
27,
5340,
67,
2738,
1435,
2713,
1338,
29782,
288,
203,
3639,
1001,
41,
2579,
27,
2138,
67,
2738,
2932,
5374,
49,
474,
654,
39,
27,
5340,
3113,
315,
21,
8863,
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
] |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY668() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF856(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER590(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE439(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE165(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM946(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER113(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL275(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER204() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA645() internal view 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;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED90(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER204();
emit OWNERSHIPTRANSFERRED90(address(0), _owner);
}
function OWNER726() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER38() { //inject NONSTANDARD NAMING
require(ISOWNER90(), "Ownable: caller is not the owner");
_;
}
function ISOWNER90() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER204() == _owner;
}
function RENOUNCEOWNERSHIP524() public ONLYOWNER38 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED90(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP660(address newOwner) public ONLYOWNER38 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP31(newOwner);
}
function _TRANSFEROWNERSHIP31(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED90(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY668() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF856(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER590(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER132(_MSGSENDER204(), recipient, amount);
return true;
}
function ALLOWANCE439(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE165(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, amount);
return true;
}
function TRANSFERFROM946(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER132(sender, recipient, amount);
_APPROVE48(sender, _MSGSENDER204(), _allowances[sender][_MSGSENDER204()].SUB641(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE241(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].ADD348(addedValue));
return true;
}
function DECREASEALLOWANCE811(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].SUB641(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER132(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB641(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD348(amount);
emit TRANSFER113(sender, recipient, amount);
}
function _MINT225(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD348(amount);
_balances[account] = _balances[account].ADD348(amount);
emit TRANSFER113(address(0), account, amount);
}
function _BURN186(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB641(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB641(amount);
emit TRANSFER113(account, address(0), amount);
}
function _APPROVE48(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
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 APPROVAL275(owner, spender, amount);
}
function _BURNFROM442(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN186(account, amount);
_APPROVE48(account, _MSGSENDER204(), _allowances[account][_MSGSENDER204()].SUB641(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME591() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL151() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS443() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD348(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB641(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB641(a, b, "SafeMath: subtraction overflow");
}
function SUB641(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 MUL714(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV963(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV963(a, b, "SafeMath: division by zero");
}
function DIV963(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;
return c;
}
function MOD537(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD537(a, b, "SafeMath: modulo by zero");
}
function MOD537(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT792(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE613(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE471(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER595(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFER590.selector, to, value));
}
function SAFETRANSFERFROM895(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFERFROM946.selector, from, to, value));
}
function SAFEAPPROVE173(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE439(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, value));
}
function SAFEINCREASEALLOWANCE700(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE439(address(this), spender).ADD348(value);
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE390(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE439(address(this), spender).SUB641(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN929(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT792(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Controller {
function WITHDRAW362(address, uint) external; //inject NONSTANDARD NAMING
function BALANCEOF856(address) external view returns (uint); //inject NONSTANDARD NAMING
function EARN394(address, uint) external; //inject NONSTANDARD NAMING
function WANT709(address) external view returns (address); //inject NONSTANDARD NAMING
}
interface Aave {
function BORROW427(address _reserve, uint _amount, uint _interestRateModel, uint16 _referralCode) external; //inject NONSTANDARD NAMING
function SETUSERUSERESERVEASCOLLATERAL395(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING
function REPAY171(address _reserve, uint _amount, address payable _onBehalfOf) external payable; //inject NONSTANDARD NAMING
function GETUSERACCOUNTDATA396(address _user) //inject NONSTANDARD NAMING
external
view
returns (
uint totalLiquidityETH,
uint totalCollateralETH,
uint totalBorrowsETH,
uint totalFeesETH,
uint availableBorrowsETH,
uint currentLiquidationThreshold,
uint ltv,
uint healthFactor
);
function GETUSERRESERVEDATA201(address _reserve, address _user) //inject NONSTANDARD NAMING
external
view
returns (
uint currentATokenBalance,
uint currentBorrowBalance,
uint principalBorrowBalance,
uint borrowRateMode,
uint borrowRate,
uint liquidityRate,
uint originationFee,
uint variableBorrowIndex,
uint lastUpdateTimestamp,
bool usageAsCollateralEnabled
);
}
interface AaveToken {
function UNDERLYINGASSETADDRESS967() external view returns (address); //inject NONSTANDARD NAMING
}
interface Oracle {
function GETASSETPRICE895(address reserve) external view returns (uint); //inject NONSTANDARD NAMING
function LATESTANSWER820() external view returns (uint); //inject NONSTANDARD NAMING
}
interface LendingPoolAddressesProvider {
function GETLENDINGPOOL689() external view returns (address); //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE785() external view returns (address); //inject NONSTANDARD NAMING
function GETPRICEORACLE709() external view returns (address); //inject NONSTANDARD NAMING
}
contract yDelegatedVault is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
address public governance;
address public controller;
uint public insurance;
uint public healthFactor = 4;
address public constant aave533 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING
constructor (address _token, address _controller) public ERC20Detailed(
string(abi.encodePacked("yearn ", ERC20Detailed(_token).NAME591())),
string(abi.encodePacked("y", ERC20Detailed(_token).SYMBOL151())),
ERC20Detailed(_token).DECIMALS443()
) {
token = IERC20(_token);
governance = msg.sender;
controller = _controller;
}
function DEBT414() public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = Controller(controller).WANT709(address(this));
(,uint currentBorrowBalance,,,,,,,,) = Aave(GETAAVE93()).GETUSERRESERVEDATA201(_reserve, address(this));
return currentBorrowBalance;
}
function CREDIT327() public view returns (uint) { //inject NONSTANDARD NAMING
return Controller(controller).BALANCEOF856(address(this));
}
// % of tokens locked and cannot be withdrawn per user
// this is impermanent locked, unless the debt out accrues the strategy
function LOCKED694() public view returns (uint) { //inject NONSTANDARD NAMING
return CREDIT327().MUL714(1e18).DIV963(DEBT414());
}
function DEBTSHARE933(address _lp) public view returns (uint) { //inject NONSTANDARD NAMING
return DEBT414().MUL714(BALANCEOF856(_lp)).MUL714(TOTALSUPPLY668());
}
function GETAAVE93() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETLENDINGPOOL689();
}
function GETAAVECORE229() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETLENDINGPOOLCORE785();
}
function SETHEALTHFACTOR690(uint _hf) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
healthFactor = _hf;
}
function ACTIVATE169() public { //inject NONSTANDARD NAMING
Aave(GETAAVE93()).SETUSERUSERESERVEASCOLLATERAL395(UNDERLYING289(), true);
}
function REPAY171(address reserve, uint amount) public { //inject NONSTANDARD NAMING
// Required for certain stable coins (USDT for example)
IERC20(reserve).APPROVE165(address(GETAAVECORE229()), 0);
IERC20(reserve).APPROVE165(address(GETAAVECORE229()), amount);
Aave(GETAAVE93()).REPAY171(reserve, amount, address(uint160(address(this))));
}
function REPAYALL522() public { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _amount = IERC20(_reserve).BALANCEOF856(address(this));
REPAY171(_reserve, _amount);
}
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function HARVEST865(address reserve, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(reserve != address(token), "token");
IERC20(reserve).SAFETRANSFER595(controller, amount);
}
// Ignore insurance fund for balance calculations
function BALANCE541() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF856(address(this)).SUB641(insurance);
}
function SETCONTROLLER494(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
function GETAAVEORACLE538() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETPRICEORACLE709();
}
function GETRESERVEPRICEETH945(address reserve) public view returns (uint) { //inject NONSTANDARD NAMING
return Oracle(GETAAVEORACLE538()).GETASSETPRICE895(reserve);
}
function SHOULDREBALANCE804() external view returns (bool) { //inject NONSTANDARD NAMING
return (OVER549() > 0);
}
function OVER549() public view returns (uint) { //inject NONSTANDARD NAMING
OVER549(0);
}
function GETUNDERLYINGPRICEETH537(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
return _amount.MUL714(GETUNDERLYINGPRICE909()).DIV963(uint(10)**ERC20Detailed(address(token)).DECIMALS443()); // Calculate the amount we are withdrawing in ETH
}
function OVER549(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _eth = GETUNDERLYINGPRICEETH537(_amount);
(uint _maxSafeETH,uint _totalBorrowsETH,) = MAXSAFEETH837();
_maxSafeETH = _maxSafeETH.MUL714(105).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_eth > _maxSafeETH) {
_maxSafeETH = 0;
} else {
_maxSafeETH = _maxSafeETH.SUB641(_eth); // Add the ETH we are withdrawing
}
if (_maxSafeETH < _totalBorrowsETH) {
uint _over = _totalBorrowsETH.MUL714(_totalBorrowsETH.SUB641(_maxSafeETH)).DIV963(_totalBorrowsETH);
_over = _over.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515());
return _over;
} else {
return 0;
}
}
function _REBALANCE677(uint _amount) internal { //inject NONSTANDARD NAMING
uint _over = OVER549(_amount);
if (_over > 0) {
Controller(controller).WITHDRAW362(address(this), _over);
REPAYALL522();
}
}
function REBALANCE176() external { //inject NONSTANDARD NAMING
_REBALANCE677(0);
}
function CLAIMINSURANCE254() external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
token.SAFETRANSFER595(controller, insurance);
insurance = 0;
}
function MAXSAFEETH837() public view returns (uint maxBorrowsETH, uint totalBorrowsETH, uint availableBorrowsETH) { //inject NONSTANDARD NAMING
(,,uint _totalBorrowsETH,,uint _availableBorrowsETH,,,) = Aave(GETAAVE93()).GETUSERACCOUNTDATA396(address(this));
uint _maxBorrowETH = (_totalBorrowsETH.ADD348(_availableBorrowsETH));
return (_maxBorrowETH.DIV963(healthFactor), _totalBorrowsETH, _availableBorrowsETH);
}
function SHOULDBORROW22() external view returns (bool) { //inject NONSTANDARD NAMING
return (AVAILABLETOBORROWRESERVE235() > 0);
}
function AVAILABLETOBORROWETH693() public view returns (uint) { //inject NONSTANDARD NAMING
(uint _maxSafeETH,uint _totalBorrowsETH, uint _availableBorrowsETH) = MAXSAFEETH837();
_maxSafeETH = _maxSafeETH.MUL714(95).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_maxSafeETH > _totalBorrowsETH) {
return _availableBorrowsETH.MUL714(_maxSafeETH.SUB641(_totalBorrowsETH)).DIV963(_availableBorrowsETH);
} else {
return 0;
}
}
function AVAILABLETOBORROWRESERVE235() public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _available = AVAILABLETOBORROWETH693();
if (_available > 0) {
return _available.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515());
} else {
return 0;
}
}
function GETRESERVEPRICE515() public view returns (uint) { //inject NONSTANDARD NAMING
return GETRESERVEPRICEETH945(RESERVE164());
}
function GETUNDERLYINGPRICE909() public view returns (uint) { //inject NONSTANDARD NAMING
return GETRESERVEPRICEETH945(UNDERLYING289());
}
function EARN394() external { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _borrow = AVAILABLETOBORROWRESERVE235();
if (_borrow > 0) {
Aave(GETAAVE93()).BORROW427(_reserve, _borrow, 2, 7);
}
//rebalance here
uint _balance = IERC20(_reserve).BALANCEOF856(address(this));
if (_balance > 0) {
IERC20(_reserve).SAFETRANSFER595(controller, _balance);
Controller(controller).EARN394(address(this), _balance);
}
}
function DEPOSITALL399() external { //inject NONSTANDARD NAMING
DEPOSIT764(token.BALANCEOF856(msg.sender));
}
function DEPOSIT764(uint _amount) public { //inject NONSTANDARD NAMING
uint _pool = BALANCE541();
token.SAFETRANSFERFROM895(msg.sender, address(this), _amount);
// 0.5% of deposits go into an insurance fund incase of negative profits to protect withdrawals
// At a 4 health factor, this is a -2% position
uint _insurance = _amount.MUL714(50).DIV963(10000);
_amount = _amount.SUB641(_insurance);
insurance = insurance.ADD348(_insurance);
//Controller can claim insurance to liquidate to cover interest
uint shares = 0;
if (TOTALSUPPLY668() == 0) {
shares = _amount;
ACTIVATE169();
} else {
shares = (_amount.MUL714(TOTALSUPPLY668())).DIV963(_pool);
}
_MINT225(msg.sender, shares);
}
function RESERVE164() public view returns (address) { //inject NONSTANDARD NAMING
return Controller(controller).WANT709(address(this));
}
function UNDERLYING289() public view returns (address) { //inject NONSTANDARD NAMING
return AaveToken(address(token)).UNDERLYINGASSETADDRESS967();
}
function WITHDRAWALL686() public { //inject NONSTANDARD NAMING
WITHDRAW362(BALANCEOF856(msg.sender));
}
// Calculates in impermanent lock due to debt
function MAXWITHDRAWAL697(address account) public view returns (uint) { //inject NONSTANDARD NAMING
uint _balance = BALANCEOF856(account);
uint _safeWithdraw = _balance.MUL714(LOCKED694()).DIV963(1e18);
if (_safeWithdraw > _balance) {
return _balance;
} else {
uint _diff = _balance.SUB641(_safeWithdraw);
return _balance.SUB641(_diff.MUL714(2)); // technically 150%, not 200%, but adding buffer
}
}
function SAFEWITHDRAW954() external { //inject NONSTANDARD NAMING
WITHDRAW362(MAXWITHDRAWAL697(msg.sender));
}
// No rebalance implementation for lower fees and faster swaps
function WITHDRAW362(uint _shares) public { //inject NONSTANDARD NAMING
uint r = (BALANCE541().MUL714(_shares)).DIV963(TOTALSUPPLY668());
_BURN186(msg.sender, _shares);
_REBALANCE677(r);
token.SAFETRANSFER595(msg.sender, r);
}
function GETPRICEPERFULLSHARE836() external view returns (uint) { //inject NONSTANDARD NAMING
return BALANCE541().MUL714(1e18).DIV963(TOTALSUPPLY668());
}
} | inject NONSTANDARD NAMING
| function GETPRICEORACLE709() external view returns (address); | 12,699,389 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4978,
7698,
1441,
916,
2226,
900,
27,
5908,
1435,
3903,
1476,
1135,
261,
2867,
1769,
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
] |
./partial_match/1/0xe09028Ec98F001235572DDDf181919A7332988d1/sources/src/L1/L2OutputOracle.sol | @notice Returns the L2 output proposal that checkpoints a given L2 block number. Uses a binary search to find the first output greater than or equal to the given block. @param _l2BlockNumber L2 block number to find a checkpoint for. @return First checkpoint that commits to the given L2 block number. | function getL2OutputAfter(uint256 _l2BlockNumber) external view returns (Types.OutputProposal memory) {
return l2Outputs[getL2OutputIndexAfter(_l2BlockNumber)];
}
| 16,134,056 | [
1,
1356,
326,
511,
22,
876,
14708,
716,
26402,
279,
864,
511,
22,
1203,
1300,
18,
540,
14854,
279,
3112,
1623,
358,
1104,
326,
1122,
876,
6802,
2353,
578,
3959,
358,
326,
864,
540,
1203,
18,
225,
389,
80,
22,
1768,
1854,
511,
22,
1203,
1300,
358,
1104,
279,
9776,
364,
18,
327,
5783,
9776,
716,
14335,
358,
326,
864,
511,
22,
1203,
1300,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9014,
22,
1447,
4436,
12,
11890,
5034,
389,
80,
22,
1768,
1854,
13,
3903,
1476,
1135,
261,
2016,
18,
1447,
14592,
3778,
13,
288,
203,
3639,
327,
328,
22,
13856,
63,
588,
48,
22,
1447,
1016,
4436,
24899,
80,
22,
1768,
1854,
13,
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
] |
/**
* @title Funding Vault
* @author Clément Lesaege - <[email protected]>
* Bug Bounties: This code hasn't undertaken a bug bounty program yet.
*/
pragma solidity ^0.4.15;
import "../Arbitrable.sol";
import "minimetoken/contracts/MiniMeToken.sol";
/** @title Funding Vault
* A contract storing the ETH raised in a crowdfunding event.
* Funds are delivered when milestones are reached.
* The team can claim a milestone is reached. Token holders will have some time to dispute that claim.
* When some token holders vote to dispute the claim, extra time is given to other token holders to dispute that claim.
* If a sufficient amount of token holders dispute it. A dispute is created and the arbitrator will decide if the milestone has been reached.
* When there is a disagreement a vote token is created. Holders should send the voteToken to the Vault to disagree with the milestone.
* Token holders can also claim that the team failed to deliver and ask for the remaining ETH to be given back to a different contract.
* This contract can be the vault of another team, or a contract to reimburse.
*/
contract FundingVault is Arbitrable {
address public team;
MiniMeToken public token;
address public funder;
uint public disputeThreshold;
uint public claimToWithdrawTime;
uint public additionalTimeToWithdraw;
uint public timeout;
struct Milestone {
uint amount; // The maximum amount which can be unlocked for this milestone.
uint amountClaimed; // The current amount which is claimed.
uint claimTime; // The time the current claim was made. Or 0 if it's not currently claimed.
bool disputed; // True if a dispute has been raised.
uint feeTeam; // Arbitration fee paid by the team.
uint feeHolders; // Arbitration fee paid by token holders.
MiniMeToken voteToken; // Forked token which will be used to vote.
uint disputeID; // ID of the dispute if this claim is disputed.
uint lastTotalFeePayment; // Time of the last total fee payment, useful for timeouts.
bool lastTotalFeePaymentIsTeam; // True if the last interaction is from the team.
address payerForHolders; // The address who first paid the arbitration fee and will be refunded in case of victory.
}
Milestone[] public milestones;
mapping(uint => uint) public disputeIDToMilstoneID; // Map (disputeID => milestoneID).
uint ousterID; //The ID of the milestone created at construction. To be disputed when the funders claim the team is not doing their job.
bool canChangeTeam; //True if the holders have attempted an oust and won the dispute. Allows the funder to select a new team (only once).
uint8 constant AMOUNT_OF_CHOICES = 2;
uint8 constant TEAM_WINS = 1;
uint8 constant HOLDERS_WINS = 2;
/** @dev Constructor. Choose the arbitrator.
* @param _arbitrator The arbitrator of the contract.
* @param _contractHash Keccak256 hash of the plain text contract.
* @param _team The address of the team who will be able to claim milestone completion.
* @param _token The token whose holders are able to dispute milestone claims.
* @param _funder The party putting funds in the vault.
* @param _disputeThreshold The ‱ of tokens required to dispute a milestone.
* @param _claimToWithdrawTime The base time in seconds after a claim is considered non-disputed (i.e if no token holders dispute it).
* @param _additionalTimeToWithdraw The time in seconds which is added per ‱ of tokens disputing the claim.
* @param _timeout Maximum time to pay arbitration fees after the other side did.
*/
constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData, bytes32 _contractHash, address _team, address _token, address _funder, uint _disputeThreshold, uint _claimToWithdrawTime, uint _additionalTimeToWithdraw, uint _timeout) public Arbitrable(_arbitrator,_arbitratorExtraData,_contractHash) {
team=_team;
token=MiniMeToken(_token);
funder=_funder;
disputeThreshold=_disputeThreshold;
claimToWithdrawTime=_claimToWithdrawTime;
additionalTimeToWithdraw=_additionalTimeToWithdraw;
timeout=_timeout;
ousterID = milestones.push(Milestone({ //Create a base milestone to be disputed when the funders claim the team is not doing their job.
amount:0,
amountClaimed:0,
claimTime:0,
disputed:false,
feeTeam:0,
feeHolders:0,
voteToken:MiniMeToken(0x0),
disputeID:0,
lastTotalFeePayment:0,
lastTotalFeePaymentIsTeam:false,
payerForHolders:0x0
}))-1;
canChangeTeam = false;
}
/** @dev Give the funds for a milestone.
* @return milestoneID The ID of the milestone which was created.
*/
function fundMilestone() public payable returns(uint milestoneID) {
require(msg.sender==funder);
return milestones.push(Milestone({
amount:msg.value,
amountClaimed:0,
claimTime:0,
disputed:false,
feeTeam:0,
feeHolders:0,
voteToken:MiniMeToken(0x0),
disputeID:0,
lastTotalFeePayment:0,
lastTotalFeePaymentIsTeam:false,
payerForHolders:0x0
}))-1;
}
//Restricts Milestone function with functionality not necessary for Ouster.
modifier isNotOuster(uint _milestoneID) {
require(ousterID != _milestoneID);
_;
}
/** @dev Claim funds of a milestone.
* @param _milestoneID The ID of the milestone.
* @param _amount The amount claim. Note that the team can claim less than the amount of a milestone. This allows partial completion claims.
*/
function claimMilestone(uint _milestoneID, uint _amount) public isNotOuster(_milestoneID) {
Milestone storage milestone=milestones[_milestoneID];
require(msg.sender==team);
require(milestone.claimTime==0); // Verify another claim is not active.
require(milestone.amount<=_amount);
milestone.claimTime=now;
}
/** @dev Make a forked token to dispute a claim.
* This avoid creating a token all the time, since most milestones should not be disputed.
* @param _milestoneID The ID of the milestone.
*/
function makeVoteToken(uint _milestoneID) public {
Milestone storage milestone=milestones[_milestoneID];
if( ousterID != _milestoneID ) { require(milestone.claimTime!=0); } // The milestone is currently claimed by the team, unless this is the ouster.
require(address(milestone.voteToken)==0x0); // Token has not already been made.
milestone.voteToken=MiniMeToken(token.createCloneToken(
"",
token.decimals(),
"",
block.number,
true
));
}
/** @dev Pay fee to dispute a milestone. To be called by parties claiming the milestone was not completed.
* The first party to pay the fee entirely will be reimbursed if the dispute is won.
* Note that holders can make a smart contract to crowdfund the fee.
* In the rare event the arbitrationCost is increased, anyone can pay the extra, but it is always the first payer who can be reimbursed.
* @param _milestoneID The milestone which is disputed.
*/
function payDisputeFeeByHolders(uint _milestoneID) public payable {
Milestone storage milestone=milestones[_milestoneID];
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(!milestone.disputed); // The milestone is not already disputed.
require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is enough votes.
require(milestone.feeHolders<arbitrationCost); // Fee has not be paid before.
require(milestone.feeHolders+msg.value>=arbitrationCost); // Enough is paid.
milestone.feeHolders+=msg.value;
if (milestone.payerForHolders==0x0)
milestone.payerForHolders=msg.sender;
if (milestone.feeTeam>=arbitrationCost) { // Enough has been paid by all sides.
createDispute(_milestoneID,arbitrationCost);
} else if (milestone.lastTotalFeePayment==0) { // First time the fee is paid.
milestone.lastTotalFeePayment=now;
} else if(milestone.lastTotalFeePaymentIsTeam) { // The team was the last one who had paid entirely.
milestone.lastTotalFeePaymentIsTeam=false;
milestone.lastTotalFeePayment=now;
}
}
/** @dev Pay fee to for a milestone dispute. To be called by the team when the holders have enough votes and fee paid.
* @param _milestoneID The milestone which is disputed.
*/
function payDisputeFeeByTeam(uint _milestoneID) public payable {
Milestone storage milestone=milestones[_milestoneID];
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(msg.sender==team);
require(!milestone.disputed); // A dispute has not been created yet.
require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is enough votes.
require(milestone.feeTeam+msg.value>=arbitrationCost); // Make sure enough is paid. Team can't pay partially.
milestone.feeTeam+=msg.value;
if (milestone.feeHolders>=arbitrationCost) { // Enough has been paid by all sides.
createDispute(_milestoneID,arbitrationCost);
}
else if (milestone.lastTotalFeePayment==0) { // First time the fee is paid.
milestone.lastTotalFeePayment=now;
milestone.lastTotalFeePaymentIsTeam=true;
} else if(!milestone.lastTotalFeePaymentIsTeam) { // The holders were the last ones who had paid entirely.
milestone.lastTotalFeePaymentIsTeam=true;
milestone.lastTotalFeePayment=now;
}
}
/** @dev Create a dispute.
* @param _milestoneID The milestone which is disputed.
* @param _arbitrationCost The amount which should be paid to the arbitrator.
*/
function createDispute(uint _milestoneID, uint _arbitrationCost) internal {
Milestone storage milestone=milestones[_milestoneID];
milestone.disputed=true;
milestone.feeTeam-=_arbitrationCost; // Remove the fee from the team pool for accounting. Note that at this point it does not matter which fee variable we decrement.
milestone.disputeID=arbitrator.createDispute(AMOUNT_OF_CHOICES,arbitratorExtraData);
disputeIDToMilstoneID[milestone.disputeID]=_milestoneID;
}
/** @dev Withdraw the money claimed in a milestone.
* To be called when a dispute has not been created within the time limit.
* @param _milestoneID The milestone which is disputed.
*/
function withdraw(uint _milestoneID) public isNotOuster(_milestoneID) {
Milestone storage milestone=milestones[_milestoneID];
require(msg.sender==team);
require(!milestone.disputed);
require(milestone.voteToken.balanceOf(this) < (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is not enough votes.
require((now-milestone.claimTime) > claimToWithdrawTime+(additionalTimeToWithdraw*milestone.voteToken.balanceOf(this))/(1000*milestone.voteToken.totalSupply()));
team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees.
milestone.amount-=milestone.amountClaimed;
milestone.amountClaimed=0;
milestone.claimTime=0;
milestone.feeTeam=0;
milestone.feeHolders=0;
}
// TODO: Timeouts
/** @dev Timeout to use when the holders don't pay the fee.
* @param _milestoneID The milestone which is disputed.
*/
function timeoutByTeam(uint _milestoneID) public {
Milestone storage milestone=milestones[_milestoneID];
require(msg.sender==team);
require(milestone.lastTotalFeePaymentIsTeam);
require(now-milestone.lastTotalFeePayment > timeout);
team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees to the team.
milestone.amount-=milestone.amountClaimed;
milestone.amountClaimed=0;
milestone.claimTime=0;
milestone.feeTeam=0;
milestone.feeHolders=0;
milestone.voteToken=MiniMeToken(0x0);
milestone.lastTotalFeePayment=0;
milestone.lastTotalFeePaymentIsTeam=false;
milestone.payerForHolders=0x0;
}
/** @dev Timeout to use whe the team don't pay the fee.
* @param _milestoneID The milestone which is disputed.
*/
function timeoutByHolders(uint _milestoneID) public {
Milestone storage milestone=milestones[_milestoneID];
require(!milestone.lastTotalFeePaymentIsTeam);
require(now-milestone.lastTotalFeePayment > timeout);
milestone.payerForHolders.transfer(milestone.feeTeam+milestone.feeHolders); // Pay the unused fees to the payer for holders.
milestone.amountClaimed=0;
milestone.claimTime=0;
milestone.disputed=false;
milestone.feeTeam=0;
milestone.feeHolders=0;
milestone.voteToken=MiniMeToken(0x0);
milestone.lastTotalFeePayment=0;
milestone.payerForHolders=0x0;
canChangeTeam = true; //since the team was nonresponsive, the holders are free to change the team.
}
/** @dev Appeal an appealable ruling.
* Transfer the funds to the arbitrator.
* @param _milestoneID The milestone which is disputed.
*/
function appeal(uint _milestoneID) public payable {
Milestone storage milestone=milestones[_milestoneID];
arbitrator.appeal.value(msg.value)(milestone.disputeID,arbitratorExtraData);
}
/** @dev Execute a ruling of a dispute.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".
*/
function executeRuling(uint _disputeID, uint _ruling) internal{
Milestone storage milestone=milestones[disputeIDToMilstoneID[_disputeID]];
require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // Make sure there is enough votes to protect against a malicious arbitrator.
uint _milestoneID = disputeIDToMilstoneID[_disputeID];
if (_ruling==TEAM_WINS) {
team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees to the team.
milestone.amount-=milestone.amountClaimed;
milestone.amountClaimed=0;
milestone.claimTime=0;
milestone.disputed=false;
milestone.feeTeam=0;
milestone.feeHolders=0;
milestone.voteToken=MiniMeToken(0x0);
milestone.disputeID=0;
milestone.lastTotalFeePayment=0;
milestone.lastTotalFeePaymentIsTeam=false;
milestone.payerForHolders=0x0;
} else if (_ruling==HOLDERS_WINS) {
milestone.payerForHolders.transfer(milestone.feeTeam+milestone.feeHolders); // Pay the unused fees to the payer for holders.
milestone.amountClaimed=0;
milestone.claimTime=0;
milestone.disputed=false;
milestone.feeTeam=0;
milestone.feeHolders=0;
milestone.voteToken=MiniMeToken(0x0);
milestone.disputeID=0;
milestone.lastTotalFeePayment=0;
milestone.lastTotalFeePaymentIsTeam=false;
milestone.payerForHolders=0x0;
if( ousterID == _milestoneID ) { //if this is the ouster milestone
canChangeTeam = true; //allow the funder to change the team
}
}
}
/** @dev Change the team. Note that the holders would have to make
* the funder a votable contract if they want a vote on who the new team will be.
* @param _newTeam the new team.
*/
function changeTeam(address _newTeam) public {
require(msg.sender == funder); //The sender must be the funder.
require(canChangeTeam);
team = _newTeam;
canChangeTeam = false; //This can only be called once.
}
}
| * @dev Pay fee to dispute a milestone. To be called by parties claiming the milestone was not completed. The first party to pay the fee entirely will be reimbursed if the dispute is won. Note that holders can make a smart contract to crowdfund the fee. In the rare event the arbitrationCost is increased, anyone can pay the extra, but it is always the first payer who can be reimbursed. @param _milestoneID The milestone which is disputed./ | function payDisputeFeeByHolders(uint _milestoneID) public payable {
Milestone storage milestone=milestones[_milestoneID];
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
milestone.feeHolders+=msg.value;
if (milestone.payerForHolders==0x0)
milestone.payerForHolders=msg.sender;
createDispute(_milestoneID,arbitrationCost);
milestone.lastTotalFeePayment=now;
milestone.lastTotalFeePaymentIsTeam=false;
milestone.lastTotalFeePayment=now;
}
| 2,547,937 | [
1,
9148,
14036,
358,
1015,
2507,
279,
28664,
18,
2974,
506,
2566,
635,
1087,
606,
7516,
310,
326,
28664,
1703,
486,
5951,
18,
225,
1021,
1122,
18285,
358,
8843,
326,
14036,
21658,
903,
506,
283,
381,
70,
295,
730,
309,
326,
1015,
2507,
353,
8462,
18,
225,
3609,
716,
366,
4665,
848,
1221,
279,
13706,
6835,
358,
276,
492,
2180,
1074,
326,
14036,
18,
225,
657,
326,
25671,
871,
326,
10056,
7034,
8018,
353,
31383,
16,
1281,
476,
848,
8843,
326,
2870,
16,
1496,
518,
353,
3712,
326,
1122,
293,
1773,
10354,
848,
506,
283,
381,
70,
295,
730,
18,
282,
389,
81,
18270,
734,
1021,
28664,
1492,
353,
1015,
458,
329,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8843,
1669,
2507,
14667,
858,
27003,
12,
11890,
389,
81,
18270,
734,
13,
1071,
8843,
429,
288,
203,
3639,
490,
18270,
2502,
28664,
33,
81,
14849,
5322,
63,
67,
81,
18270,
734,
15533,
203,
3639,
2254,
10056,
7034,
8018,
273,
10056,
86,
639,
18,
297,
3682,
7034,
8018,
12,
297,
3682,
86,
639,
7800,
751,
1769,
203,
203,
3639,
28664,
18,
21386,
27003,
15,
33,
3576,
18,
1132,
31,
203,
203,
3639,
309,
261,
81,
18270,
18,
84,
1773,
1290,
27003,
631,
20,
92,
20,
13,
203,
5411,
28664,
18,
84,
1773,
1290,
27003,
33,
3576,
18,
15330,
31,
203,
203,
5411,
752,
1669,
2507,
24899,
81,
18270,
734,
16,
297,
3682,
7034,
8018,
1769,
203,
5411,
28664,
18,
2722,
5269,
14667,
6032,
33,
3338,
31,
203,
5411,
28664,
18,
2722,
5269,
14667,
6032,
2520,
8689,
33,
5743,
31,
203,
5411,
28664,
18,
2722,
5269,
14667,
6032,
33,
3338,
31,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0x787F43a5613836E5e4b7940184c89e3764d66BeC/sources/SakeILO.sol | * @dev after add liquidity to sakeswap, project party unlock LP periodicity/ | function projectPartyUnlockLP() external nonReentrant whenNotPaused {
require(msg.sender == projectPartyAddress, "invalid address");
(uint256 availableTimes, uint256 amount) = getUnlockLPAmount(false);
investorUnlockedLPTimes[msg.sender] = investorUnlockedLPTimes[msg.sender].add(availableTimes);
unlockLP(amount);
}
| 8,770,815 | [
1,
5205,
527,
4501,
372,
24237,
358,
272,
3223,
91,
438,
16,
1984,
18285,
7186,
511,
52,
17478,
560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1984,
17619,
7087,
14461,
1435,
3903,
1661,
426,
8230,
970,
1347,
1248,
28590,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1984,
17619,
1887,
16,
315,
5387,
1758,
8863,
203,
3639,
261,
11890,
5034,
2319,
10694,
16,
2254,
5034,
3844,
13,
273,
336,
7087,
48,
4066,
4778,
12,
5743,
1769,
203,
3639,
2198,
395,
280,
7087,
329,
48,
1856,
4485,
63,
3576,
18,
15330,
65,
273,
2198,
395,
280,
7087,
329,
48,
1856,
4485,
63,
3576,
18,
15330,
8009,
1289,
12,
5699,
10694,
1769,
203,
3639,
7186,
14461,
12,
8949,
1769,
203,
565,
289,
7010,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xd12EC3cb26073DBB76BDB641cD8Ba66a11a2035e/sources/contracts/pool/PoolMaster.sol | @notice Override of the mint function, see {IERC20-_burn} | function _burn(address account, uint256 amount) internal override(ERC20Upgradeable, PoolRewards) {
super._burn(account, amount);
}
| 4,846,154 | [
1,
6618,
434,
326,
312,
474,
445,
16,
2621,
288,
45,
654,
39,
3462,
17,
67,
70,
321,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
3849,
12,
654,
39,
3462,
10784,
429,
16,
8828,
17631,
14727,
13,
288,
203,
565,
2240,
6315,
70,
321,
12,
4631,
16,
3844,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "./ERC20Mintable.sol";
import "./ERC20Burnable.sol";
import "./Ownable.sol";
contract WorldBitToken is ERC20, ERC20Burnable, ERC20Mintable, Ownable {
string private _name = "WorldBit";
string private _symbol = "WBT";
uint8 private _decimals = 18;
//Total Supply is 210,000,000 WBT
uint256 private _totalSupply = 210000000 ether;
constructor () public {
_mint(msg.sender, _totalSupply);
emit Transfer(address(0x0), msg.sender, _totalSupply);
}
// WorldBit Event and Emmit interface
event WorldBitEvent(address object, bytes2 operand, bytes2 command, uint256 val1, uint256 val2, string location, string str1, string str2, string comment);
function WorldBit(address object, bytes2 operand, bytes2 command, uint256 val1, uint256 val2, string memory location, string memory str1, string memory str2, string memory comment) public {
emit WorldBitEvent(object, operand, command, val1, val2, location, str1, str2, comment);
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
enum TxStatus { escrow, cancel, deliver, confirm, claim }
struct Transaction {
address user;
address merchant;
address asset;
uint value;
TxStatus status;
bool completed;
}
mapping (uint => Transaction) public transactions;
mapping (uint => mapping(address => uint)) public claims;
uint public transactionCount;
/**
* Event for Escrow logging
* @param transactionId Transaction ID
* @param user user address
* @param merchant merchant address
* @param asset asset address
* @param value escrowed value of WBT Token
*/
event Escrow(uint transactionId, address indexed user, address indexed merchant, address indexed asset, uint value);
/**
* Event for Cancel logging
* @param transactionId Transaction ID
* @param from who canceled escrow
*/
event Cancel(uint indexed transactionId, address indexed from);
/**
* Event for Deliver logging
* @param transactionId Transaction ID
*/
event Deliver(uint indexed transactionId);
/**
* Event for Confirm logging
* @param transactionId Transaction ID
*/
event Confirm(uint indexed transactionId);
/**
* Event for Claim logging
* @param transactionId Transaction ID
* @param from who claim
*/
event Claim(uint indexed transactionId, address indexed from);
/**
* Event for Claim Handle logging
* @param transactionId Transaction ID
* @param beneficiary who got the WBT tokens
* @param value claimed value
*/
event HandleClaim(uint indexed transactionId, address indexed beneficiary, uint indexed value);
/**
* Event for Complete logging
* @param transactionId Transaction ID
*/
event Complete(uint transactionId);
// -----------------------------------------
// Escrow external interface
// -----------------------------------------
/**
* @dev escrow tokens to address(this) contract and create pending transaction, called by user.
* @param _merchant merchant address
* @param _asset asset address
* @param _value amount of tokens to escrow
* @return Transaction ID
*/
function escrow(address _merchant, address _asset, uint _value) external returns (uint transactionId) {
// escrow funds from user wallet
_transfer(msg.sender, address(address(this)), _value);
transactionId = _addTransaction(msg.sender, _merchant, _asset, _value);
emit Escrow(transactionId, msg.sender, _merchant, _asset, _value);
}
/**
* @dev cancel transaction by user. User can cancel transaction if transaction is escrow state.
* @param _transactionId Transaction ID
* @return success
*/
function cancelByUser(uint _transactionId) external onlyUser(_transactionId) notCompleted(_transactionId) returns (bool success) {
require(transactions[_transactionId].status == TxStatus.escrow, "Only Transaction that is in escrow status can be canceled.");
// transfer tokens back to user wallet
_transfer(address(this), transactions[_transactionId].user, transactions[_transactionId].value);
transactions[_transactionId].status = TxStatus.cancel;
transactions[_transactionId].completed = true;
emit Cancel(_transactionId, msg.sender);
emit Complete(_transactionId);
return true;
}
/**
* @dev cancel transaction by merchant. Merchant can cancel transaction anytime.
* @param _transactionId Transaction ID
* @return success
*/
function cancelByMerchant(uint _transactionId) external onlyMerchant(_transactionId) notCompleted(_transactionId) returns (bool success) {
require(transactions[_transactionId].status == TxStatus.escrow || transactions[_transactionId].status == TxStatus.deliver, "Only transaction that is in escrow or deliver status can be canceled");
// transfer WBT back to user wallet
_transfer(address(this), transactions[_transactionId].user, transactions[_transactionId].value);
transactions[_transactionId].status = TxStatus.cancel;
transactions[_transactionId].completed = true;
emit Cancel(_transactionId, msg.sender);
emit Complete(_transactionId);
return true;
}
/**
* @dev mark transaction as deliver after merchant deliver asset.
* @param _transactionId Transaction ID
* @return success
*/
function deliver(uint _transactionId) external onlyMerchant(_transactionId) notCompleted(_transactionId) returns (bool success) {
require(transactions[_transactionId].status == TxStatus.escrow, "Transaction status should be escrow");
transactions[_transactionId].status = TxStatus.deliver;
emit Deliver(_transactionId);
return true;
}
/**
* @dev confirm transaction. escrowed tokens will be transferred to merchant.
* @param _transactionId Transaction ID
* @return success
*/
function confirm(uint _transactionId) external onlyUser(_transactionId) notCompleted(_transactionId) returns (bool success) {
require(transactions[_transactionId].status == TxStatus.deliver, "Transaction status should be deliver");
_transfer(address(this), transactions[_transactionId].merchant, transactions[_transactionId].value);
transactions[_transactionId].status = TxStatus.confirm;
transactions[_transactionId].completed = true;
emit Confirm(_transactionId);
emit Complete(_transactionId);
return true;
}
/**
* @dev User/Merchant mark transaction as claim when
* User is not satisfied with deliverred item
* User do not confirm after item is deliverred.
* @param _transactionId Transaction ID
* @return success
*/
function claim(uint _transactionId) external onlyParties(_transactionId) notCompleted(_transactionId) returns (bool success) {
require(claims[_transactionId][msg.sender] == 0, "Wrong Address");
require(transactions[_transactionId].status == TxStatus.deliver || transactions[_transactionId].status == TxStatus.claim, "Transaction status should be deliver or claim");
claims[_transactionId][msg.sender] = now;
transactions[_transactionId].status = TxStatus.claim;
emit Claim(_transactionId, msg.sender);
return true;
}
/**
* @dev Returns list of transaction IDs in defined range.
* @param _from Index start position of transaction array.
* @param _to Index end position of transaction array.
* @param _status status of transactions.
* @param _completed include completed transactions.
*/
function getTransactionIds(uint _from, uint _to, TxStatus _status, bool _completed) external view returns (uint[] memory _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i = 0; i < transactionCount; i++)
if (transactions[i].status == _status && transactions[i].completed == _completed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](_to - _from);
for (i = _from; i < _to; i++)
_transactionIds[i - _from] = transactionIdsTemp[i];
}
/**
* @dev Returns Transaction status
* @param _transactionId Transaction ID
*/
function getTransactionStatusById(uint _transactionId) external view returns (TxStatus status)
{
return transactions[_transactionId].status;
}
// -----------------------------------------
// Interface for owner
// -----------------------------------------
/**
* @dev mark transaction as deliver after merchant deliver asset.
* @param _transactionId Transaction ID
* @return success
*/
function handleClaim(uint _transactionId, address _beneficiary) external notCompleted(_transactionId) onlyOwner returns (bool success) {
require(_beneficiary == transactions[_transactionId].user || _beneficiary == transactions[_transactionId].merchant);
_transfer(address(this), _beneficiary, transactions[_transactionId].value);
transactions[_transactionId].completed = true;
emit HandleClaim(_transactionId, _beneficiary, transactions[_transactionId].value);
emit Complete(_transactionId);
return true;
}
// -----------------------------------------
// modifiers
// -----------------------------------------
modifier onlyUser(uint transactionId) {
require(transactions[transactionId].user == msg.sender);
_;
}
modifier onlyMerchant(uint transactionId) {
require(transactions[transactionId].merchant == msg.sender);
_;
}
modifier onlyParties(uint transactionId) {
require(transactions[transactionId].merchant == msg.sender || transactions[transactionId].user == msg.sender);
_;
}
modifier notCompleted(uint transactionId) {
require(transactions[transactionId].user != address(0));
require(!transactions[transactionId].completed);
_;
}
// -----------------------------------------
// Internal interface
// -----------------------------------------
/**
* @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
* @param _user User Address.
* @param _merchant Merchant Address.
* @param _asset Asset Address.
* @param _value Token Value of the transaction.
* @return Returns transaction ID.
*/
function _addTransaction(address _user, address _merchant, address _asset, uint _value) internal returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
user: _user,
merchant: _merchant,
asset: _asset,
value: _value,
status: TxStatus.escrow,
completed: false
});
transactionCount += 1;
}
} | * @dev Returns list of transaction IDs in defined range. @param _from Index start position of transaction array. @param _to Index end position of transaction array. @param _status status of transactions. @param _completed include completed transactions./ | function getTransactionIds(uint _from, uint _to, TxStatus _status, bool _completed) external view returns (uint[] memory _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i = 0; i < transactionCount; i++)
if (transactions[i].status == _status && transactions[i].completed == _completed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](_to - _from);
for (i = _from; i < _to; i++)
_transactionIds[i - _from] = transactionIdsTemp[i];
}
| 12,678,948 | [
1,
1356,
666,
434,
2492,
7115,
316,
2553,
1048,
18,
225,
389,
2080,
3340,
787,
1754,
434,
2492,
526,
18,
225,
389,
869,
3340,
679,
1754,
434,
2492,
526,
18,
225,
389,
2327,
1267,
434,
8938,
18,
225,
389,
13615,
2341,
5951,
8938,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
15674,
2673,
12,
11890,
389,
2080,
16,
2254,
389,
869,
16,
6424,
1482,
389,
2327,
16,
1426,
389,
13615,
13,
3903,
1476,
1135,
261,
11890,
8526,
3778,
389,
7958,
2673,
13,
203,
565,
288,
203,
3639,
2254,
8526,
3778,
2492,
2673,
7185,
273,
394,
2254,
8526,
12,
7958,
1380,
1769,
203,
3639,
2254,
1056,
273,
374,
31,
203,
3639,
2254,
277,
31,
203,
3639,
364,
261,
77,
273,
374,
31,
277,
411,
2492,
1380,
31,
277,
27245,
203,
3639,
309,
261,
20376,
63,
77,
8009,
2327,
422,
389,
2327,
597,
8938,
63,
77,
8009,
13615,
422,
389,
13615,
13,
203,
3639,
288,
203,
5411,
2492,
2673,
7185,
63,
1883,
65,
273,
277,
31,
203,
5411,
1056,
1011,
404,
31,
203,
3639,
289,
203,
3639,
389,
7958,
2673,
273,
394,
2254,
8526,
24899,
869,
300,
389,
2080,
1769,
203,
3639,
364,
261,
77,
273,
389,
2080,
31,
277,
411,
389,
869,
31,
277,
27245,
203,
3639,
389,
7958,
2673,
63,
77,
300,
389,
2080,
65,
273,
2492,
2673,
7185,
63,
77,
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
] |
/*
███████╗████████╗██╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ███╗
██╔════╝╚══██╔══╝██║ ██║██╔════╝██╔══██╗██╔════╝██║ ██║████╗ ████║
█████╗ ██║ ███████║█████╗ ██████╔╝█████╗ ██║ ██║██╔████╔██║
██╔══╝ ██║ ██╔══██║██╔══╝ ██╔══██╗██╔══╝ ██║ ██║██║╚██╔╝██║
███████╗ ██║ ██║ ██║███████╗██║ ██║███████╗╚██████╔╝██║ ╚═╝ ██║
╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝
____ _ _ _ _
/ __ \ | (_) (_) |
| | | |_ __ __ _ ___| |_ _______ _| |_
| | | | '__/ _` |/ __| | |_ / _ \ | | __|
| |__| | | | (_| | (__| | |/ / __/_| | |_
\____/|_| \__,_|\___|_|_/___\___(_)_|\__|
_ _ _
( ) _ ( )_ ( )_
| | _ __ (_) ___ ___ _ ___ | ,_) _ __ _ _ ___ | ,_)
| | _ /'_`\ /'_ `\| | /'___) /'___) /'_`\ /' _ `\| | ( '__)/'_` ) /'___)| |
| |_( )( (_) )( (_) || |( (___ ( (___ ( (_) )| ( ) || |_ | | ( (_| |( (___ | |_
(____/'`\___/'`\__ |(_)`\____) `\____)`\___/'(_) (_)`\__)(_) `\__,_)`\____)`\__)
( )_) |
\___/'
*/
pragma solidity ^0.4.20; // Tested on version 0.4.25
/*
* Import Oraclize to use their oracles..
*/
import "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol";
/*
* Use this interface to take tha Data contract address from proxy contract.
*/
contract ProxyInterface {
function getDataContractAddress() public view returns (address);
function getAutoMatchContractAddress() public view returns (address);
}
/*
* Use this interface to take tha Data contract address from proxy contract.
*/
contract AutoMatchInterface {
function autoMatching() public payable returns(bool);
function allOrdersMatched() public view returns(bool);
}
/*
* Use this interface to use Data ccontract functions.
*/
contract DataInterface {
function editOrdersAmount(address _user, uint128 _newAmount, bool _openOrder) external payable returns(bool);
function addOpenOrder(address _user, bool _storeOfValue, uint128 _amount) external payable returns(uint);
function editOrdersArray(address _user, bool _push, bool _openOrder, bool _storeOfValue, uint _number) external payable returns(bool);
function removeSpecificOpenOrder(uint _orderId, bool _storeOfValue) external payable returns(bool);
function returnMoney(address _user, uint128 _amount) external payable returns(bool);
function addMatchedOrder(address _userA, address _userB, uint128 _amount, uint32 _etherPrice) external payable returns(uint);
function disableMatchedOrder(uint _orderId) external payable returns(bool);
function removeOldestOpenOrder(bool _storeOfValue) external payable returns(bool);
function decraseStoreOfValueBySpecificAmount(uint _orderId, uint128 _amount) external payable returns(bool);
function decraseIncreasePriceBySpecificAmount(uint _orderId, uint128 _amount) external payable returns(bool);
function editOpenOrder(uint _index, bool _storeOfValue, uint128 _amount) external payable returns(bool);
/*
* Getters
*/
function getUserStoreOfValueOpenOrders(address _user) external view returns(uint[]);
function getUserPriceIncreaseOpenOrders(address _user) external view returns(uint[]);
function getUserMatchedOrders(address _user) external view returns(uint[]);
function returnUserInformation(address _user) external view returns(uint128, uint128, uint[], uint[], uint[]);
function getMatchedOrder(uint _orderId) external view returns(address, address, uint128, uint32, bool);
function getUserAmount(address _user, bool _openOrder) external view returns(uint128);
function getUserOpenOrder(uint _orderId, bool _storeOfValue) external view returns(address, uint128);
function getStoreOfValueOrders() external view returns(uint[]);
function getIncreaseValueOrders() external view returns(uint[]);
function getStoreOfValueOrderInformation(uint _orderId) external view returns(address, uint128);
function getPriceIncreaseOrderInformation(uint _orderId) external view returns(address, uint128);
}
contract LogicContract is usingOraclize {
/*
******************** CONTRACT INFORMATION ********************
* This contract holds the Logic of the platform.
*
* The methods can be called from users, checks their data
* and call the corresponding methods from Data contract.
*/
/*
* Initialize with proxy contract address.
*/
address private proxyAddress;
constructor(address _proxyAddress) public {
proxyAddress = _proxyAddress;
// Get the current ETH/USD price for free.
updatePrice();
}
/*
* Set modifier so public functions can be called only from the
* Logic contract and not from any other contract.
*/
modifier recentPrice {
require(haveRecentETHprice());
_;
}
/*
* Get Data contract address from the proxy contract.
*/
function getDataContractAddress() private view returns (address) {
return ProxyInterface(proxyAddress).getDataContractAddress();
}
/*
* Get Data contract address from the proxy contract.
*/
function getAutoMatchContractAddress() private view returns (address) {
return ProxyInterface(proxyAddress).getAutoMatchContractAddress();
}
/*
* @ETHUSD is the latest known ETH/USD price.
* @latestBlock is the block number at which we have got the latest ETH/USD price.
* @blockNumberLimit et the limit of how old price can be acceptable (in blocks).
*/
uint32 private ETHUSD;
uint256 private latestBlock;
uint256 private blockNumberLimit = 50;
/*
* Accepts the money that user sends and creates a new open order.
*
* @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False).
*/
function addNewOrder(bool _storeOfValue) public payable returns(bool) {
// Check for amount overflow.
require(msg.value < 2**128);
// Minumum order is 0.001 ether
require(msg.value >= 10**15);
// Add the open order
require(DataInterface(getDataContractAddress()).editOrdersAmount.value(msg.value)(msg.sender, DataInterface(getDataContractAddress()).getUserAmount(msg.sender, true) + uint128(msg.value), true));
uint orderId = DataInterface(getDataContractAddress()).addOpenOrder(msg.sender, _storeOfValue, uint128(msg.value));
require(DataInterface(getDataContractAddress()).editOrdersArray(msg.sender, true, true, _storeOfValue, orderId));
// Do auto-matching.
while(!AutoMatchInterface(getAutoMatchContractAddress()).allOrdersMatched()){
AutoMatchInterface(getAutoMatchContractAddress()).autoMatching();
}
return true;
}
/*
* A user can complete his specific order and distribute the money to both users.
*
* @_orderId is the order ID that user want to complete.
*/
function completedOrder(uint _orderId) public recentPrice payable returns(bool) {
// Confirm that users owns this order
address _userA;
address _userB;
uint128 _amount;
uint32 _etherPrice;
bool _active;
// Get the information about this order.
(_userA, _userB, _amount, _etherPrice, _active) = DataInterface(getDataContractAddress()).getMatchedOrder(_orderId);
// Checks thath the user owns this matched order.
require(msg.sender == _userA || msg.sender == _userB);
// Make distrubition
uint128 _distrubitionUserA;
uint128 _distrubitionUserB;
if (_etherPrice >= ETHUSD * 2) {
require(DataInterface(getDataContractAddress()).returnMoney(_userA, _amount*2));
} else {
_distrubitionUserA = _etherPrice * _amount / ETHUSD;
_distrubitionUserB = 2 * _amount - _distrubitionUserA;
require(DataInterface(getDataContractAddress()).returnMoney(_userA, _distrubitionUserA));
require(DataInterface(getDataContractAddress()).returnMoney(_userB, _distrubitionUserB));
}
// Delete it from matched orders
require(DataInterface(getDataContractAddress()).disableMatchedOrder(_orderId));
require(DataInterface(getDataContractAddress()).editOrdersAmount(_userA, DataInterface(getDataContractAddress()).getUserAmount(_userA, false)-_amount, false));
require(DataInterface(getDataContractAddress()).editOrdersArray(_userA, false, false, true, _orderId));
require(DataInterface(getDataContractAddress()).editOrdersAmount(_userB, DataInterface(getDataContractAddress()).getUserAmount(_userB, false)-_amount, false));
require(DataInterface(getDataContractAddress()).editOrdersArray(_userB, false, false, true, _orderId));
return true;
}
/*
* User can cancel his open order and get back his money.
*
* @_orderId is the order ID that user wants to cancel.
* @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False).
*/
function cancelOpenOrder(uint _orderId, bool _storeOfValue) public payable returns(bool) {
// Confirm that users owns this order
address user;
uint128 amount;
(user, amount) = DataInterface(getDataContractAddress()).getUserOpenOrder(_orderId, _storeOfValue);
require(msg.sender == user && amount > 0);
// Check for underflow
require(DataInterface(getDataContractAddress()).getUserAmount(msg.sender, true) - amount < DataInterface(getDataContractAddress()).getUserAmount(msg.sender, true));
// Delete the order
require(DataInterface(getDataContractAddress()).editOrdersAmount(user, DataInterface(getDataContractAddress()).getUserAmount(user, true) - amount, true));
require(DataInterface(getDataContractAddress()).editOrdersArray(user, false, true, _storeOfValue, _orderId));
require(DataInterface(getDataContractAddress()).removeSpecificOpenOrder(_orderId, _storeOfValue));
require(DataInterface(getDataContractAddress()).editOpenOrder(_orderId, _storeOfValue, 0));
// Return money
require(DataInterface(getDataContractAddress()).returnMoney(user, amount));
return true;
}
/*
* Gets the latest ETH/USD price.
* It gets price of ether in USD, as a string.
* Code from: http://docs.oraclize.it/#ethereum
*/
event LogConstructorInitiated(string nextStep);
event LogPriceUpdated(string price);
event LogNewOraclizeQuery(string description);
function updatePrice() public payable returns(bool) {
if (oraclize_getPrice("URL") > msg.value) {
emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some more ETH to cover for the query fee");
return false;
} else {
emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer...");
oraclize_query("URL", "json(https://api.infura.io/v1/ticker/ethusd).bid");
return true;
}
}
/*
* Oraclize calls this callback function to send the ETH/USD.
* It's a string so we are responsible to convert and save it.
*/
function __callback(bytes32 myid, string result) public {
if (msg.sender != oraclize_cbAddress()) revert();
// Price is returned as String. We turn it to uint32. We avoid the decimal part.
ETHUSD = uint32(parseInt(result, 0));
// Keep this block number.
latestBlock = block.number;
emit LogPriceUpdated(result);
}
/*
* Get the query fee in Wei.
*/
function estimateGas() public view returns (uint) {
return oraclize_getPrice("URL");
}
/*
* Checks that we have a recent ETH/USD price.
*/
function haveRecentETHprice() public view returns (bool) {
return (block.number - blockNumberLimit < latestBlock);
}
/*
******************** VARIOUS GETTERS ********************
* Getters used for the front-end application.
*/
/*
* Get "Store of value" open orders for the specific user.
*/
function getUserStoreOfValueOpenOrders() external view returns(uint[]) {
return DataInterface(getDataContractAddress()).getUserStoreOfValueOpenOrders(msg.sender);
}
/*
* Get "Price iincrease bet" open orders for the specific user.
*/
function getUserPriceIncreaseOpenOrders() external view returns(uint[]) {
return DataInterface(getDataContractAddress()).getUserPriceIncreaseOpenOrders(msg.sender);
}
/*
* Get the matched orders for the specific user.
*/
function getUserMatchedOrders() external view returns(uint[]) {
return DataInterface(getDataContractAddress()).getUserMatchedOrders(msg.sender);
}
/*
* Get information for the specific user.
*/
function returnUserInformation() external view returns(uint128, uint128, uint[], uint[], uint[]) {
return DataInterface(getDataContractAddress()).returnUserInformation(msg.sender);
}
/*
* Get the latest saved ETH/USD price.
*/
function getETHUSDprice() external view returns(uint32) {
return ETHUSD;
}
/*
* Get the latest block number (for the last price we have).
*/
function getLatestBlock() external view returns(uint256) {
return latestBlock;
}
/*
* Get the block number limit.
*/
function getBlockNumberLimit() external view returns(uint256) {
return blockNumberLimit;
}
} | Accepts the money that user sends and creates a new open order. @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False)./ Check for amount overflow. Minumum order is 0.001 ether Add the open order Do auto-matching. | function addNewOrder(bool _storeOfValue) public payable returns(bool) {
require(msg.value < 2**128);
require(msg.value >= 10**15);
require(DataInterface(getDataContractAddress()).editOrdersAmount.value(msg.value)(msg.sender, DataInterface(getDataContractAddress()).getUserAmount(msg.sender, true) + uint128(msg.value), true));
uint orderId = DataInterface(getDataContractAddress()).addOpenOrder(msg.sender, _storeOfValue, uint128(msg.value));
require(DataInterface(getDataContractAddress()).editOrdersArray(msg.sender, true, true, _storeOfValue, orderId));
while(!AutoMatchInterface(getAutoMatchContractAddress()).allOrdersMatched()){
AutoMatchInterface(getAutoMatchContractAddress()).autoMatching();
}
return true;
}
| 13,070,927 | [
1,
26391,
326,
15601,
716,
729,
9573,
471,
3414,
279,
394,
1696,
1353,
18,
24294,
2233,
951,
620,
21368,
358,
279,
315,
2257,
434,
460,
6,
1353,
261,
5510,
13,
578,
358,
279,
315,
5147,
10929,
2701,
6,
1353,
261,
8381,
2934,
19,
2073,
364,
3844,
9391,
18,
5444,
379,
379,
1353,
353,
374,
18,
11664,
225,
2437,
1436,
326,
1696,
1353,
2256,
3656,
17,
16271,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
20973,
2448,
12,
6430,
389,
2233,
951,
620,
13,
1071,
8843,
429,
1135,
12,
6430,
13,
288,
203,
203,
3639,
2583,
12,
3576,
18,
1132,
411,
576,
636,
10392,
1769,
203,
540,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
1728,
636,
3600,
1769,
203,
540,
203,
3639,
2583,
12,
751,
1358,
12,
588,
751,
8924,
1887,
1435,
2934,
4619,
16528,
6275,
18,
1132,
12,
3576,
18,
1132,
21433,
3576,
18,
15330,
16,
1910,
1358,
12,
588,
751,
8924,
1887,
1435,
2934,
588,
1299,
6275,
12,
3576,
18,
15330,
16,
638,
13,
397,
2254,
10392,
12,
3576,
18,
1132,
3631,
638,
10019,
203,
3639,
2254,
20944,
273,
1910,
1358,
12,
588,
751,
8924,
1887,
1435,
2934,
1289,
3678,
2448,
12,
3576,
18,
15330,
16,
389,
2233,
951,
620,
16,
2254,
10392,
12,
3576,
18,
1132,
10019,
203,
3639,
2583,
12,
751,
1358,
12,
588,
751,
8924,
1887,
1435,
2934,
4619,
16528,
1076,
12,
3576,
18,
15330,
16,
638,
16,
638,
16,
389,
2233,
951,
620,
16,
20944,
10019,
203,
540,
203,
3639,
1323,
12,
5,
4965,
2060,
1358,
12,
588,
4965,
2060,
8924,
1887,
1435,
2934,
454,
16528,
15400,
10756,
95,
203,
5411,
8064,
2060,
1358,
12,
588,
4965,
2060,
8924,
1887,
1435,
2934,
6079,
9517,
5621,
203,
3639,
289,
203,
3639,
327,
638,
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
] |
pragma solidity ^0.4.16;
/**
* @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 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 ERC20 {
function totalSupply() constant returns (uint totalSupply);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
//Token with owner (admin)
contract OwnedToken {
address public owner; //contract owner (admin) address
function OwnedToken () public {
owner = msg.sender;
}
//Check if owner initiate call
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
/**
* Transfer ownership
*
* @param newOwner The address of the new contract owner
*/
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
//Contract with name
contract NamedOwnedToken is OwnedToken {
string public name; //the name for display purposes
string public symbol; //the symbol for display purposes
function NamedOwnedToken(string tokenName, string tokenSymbol) public
{
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Change name and symbol
*
* @param newName The new contract name
* @param newSymbol The new contract symbol
*/
function changeName(string newName, string newSymbol)public onlyOwner {
name = newName;
symbol = newSymbol;
}
}
contract TSBToken is ERC20, NamedOwnedToken {
using SafeMath for uint256;
// Public variables of the token
uint256 public _totalSupply = 0; //Total number of token issued (1 token = 10^decimals)
uint8 public decimals = 18; //Decimals, each 1 token = 10^decimals
mapping (address => uint256) public balances; // A map with all balances
mapping (address => mapping (address => uint256)) public allowed; //Implement allowence to support ERC20
mapping (address => uint256) public paidETH; //The sum have already been paid to token owner
uint256 public accrueDividendsPerXTokenETH = 0;
uint256 public tokenPriceETH = 0;
mapping (address => uint256) public paydCouponsETH;
uint256 public accrueCouponsPerXTokenETH = 0;
uint256 public totalCouponsUSD = 0;
uint256 public MaxCouponsPaymentUSD = 150000;
mapping (address => uint256) public rebuySum;
mapping (address => uint256) public rebuyInformTime;
uint256 public endSaleTime;
uint256 public startRebuyTime;
uint256 public reservedSum;
bool public rebuyStarted = false;
uint public tokenDecimals;
uint public tokenDecimalsLeft;
/**
* Constructor function
*
* Initializes contract
*/
function TSBToken(
string tokenName,
string tokenSymbol
) NamedOwnedToken(tokenName, tokenSymbol) public {
tokenDecimals = 10**uint256(decimals - 5);
tokenDecimalsLeft = 10**5;
startRebuyTime = now + 1 years;
endSaleTime = now;
}
/**
* Internal function, calc dividends to transfer when tokens are transfering to another wallet
*/
function transferDiv(uint startTokens, uint fromTokens, uint toTokens, uint sumPaydFrom, uint sumPaydTo, uint acrued) internal constant returns (uint, uint) {
uint sumToPayDividendsFrom = fromTokens.mul(acrued);
uint sumToPayDividendsTo = toTokens.mul(acrued);
uint sumTransfer = sumPaydFrom.div(startTokens);
sumTransfer = sumTransfer.mul(startTokens-fromTokens);
if (sumPaydFrom > sumTransfer) {
sumPaydFrom -= sumTransfer;
if (sumPaydFrom > sumToPayDividendsFrom) {
sumTransfer += sumPaydFrom - sumToPayDividendsFrom;
sumPaydFrom = sumToPayDividendsFrom;
}
} else {
sumTransfer = sumPaydFrom;
sumPaydFrom = 0;
}
sumPaydTo = sumPaydTo.add(sumTransfer);
if (sumPaydTo > sumToPayDividendsTo) {
uint differ = sumPaydTo - sumToPayDividendsTo;
sumPaydTo = sumToPayDividendsTo;
sumPaydFrom = sumPaydFrom.add(differ);
if (sumPaydFrom > sumToPayDividendsFrom) {
sumPaydFrom = sumToPayDividendsFrom;
}
}
return (sumPaydFrom, sumPaydTo);
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require(balances[_from] >= _value); // Check if the sender has enough
require(balances[_to] + _value > balances[_to]); // Check for overflows
uint startTokens = balances[_from].div(tokenDecimals);
balances[_from] -= _value; // Subtract from the sender
balances[_to] += _value; // Add the same to the recipient
if (balances[_from] == 0) {
paidETH[_to] = paidETH[_to].add(paidETH[_from]);
} else {
uint fromTokens = balances[_from].div(tokenDecimals);
uint toTokens = balances[_to].div(tokenDecimals);
(paidETH[_from], paidETH[_to]) = transferDiv(startTokens, fromTokens, toTokens, paidETH[_from], paidETH[_to], accrueDividendsPerXTokenETH+accrueCouponsPerXTokenETH);
}
Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Balance of tokens
*
* @param _owner The address of token wallet
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* Returns total issued tokens number
*
*/
function totalSupply() public constant returns (uint totalSupply) {
return _totalSupply;
}
/**
* 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 <= allowed[_from][msg.sender]); // Check allowance
allowed[_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) {
allowed[msg.sender][_spender] = _value;
return true;
}
/**
* Check allowance for address
*
* @param _owner The address who authorize to spend
* @param _spender The address authorized to spend
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Internal function destroy tokens
*/
function burnTo(uint256 _value, address adr) internal returns (bool success) {
require(balances[adr] >= _value); // Check if the sender has enough
require(_value > 0); // Check if the sender has enough
uint startTokens = balances[adr].div(tokenDecimals);
balances[adr] -= _value; // Subtract from the sender
uint endTokens = balances[adr].div(tokenDecimals);
uint sumToPayFrom = endTokens.mul(accrueDividendsPerXTokenETH + accrueCouponsPerXTokenETH);
uint divETH = paidETH[adr].div(startTokens);
divETH = divETH.mul(endTokens);
if (divETH > sumToPayFrom) {
paidETH[adr] = sumToPayFrom;
} else {
paidETH[adr] = divETH;
}
_totalSupply -= _value; // Updates totalSupply
Burn(adr, _value);
return true;
}
/**
* Delete tokens tokens during the end of croudfunding
* (in case of errors made by crowdfnuding participants)
* Only owner could call
*/
function deleteTokens(address adr, uint256 amount) public onlyOwner canMint {
burnTo(amount, adr);
}
bool public mintingFinished = false;
event Mint(address indexed to, uint256 amount);
event MintFinished();
//Check if it is possible to mint new tokens (mint allowed only during croudfunding)
modifier canMint() {
require(!mintingFinished);
_;
}
function () public payable {
}
//Withdraw unused ETH from contract to owner
function WithdrawLeftToOwner(uint sum) public onlyOwner {
owner.transfer(sum);
}
/**
* Mint additional tokens at the end of croudfunding
*/
function mintToken(address target, uint256 mintedAmount) public onlyOwner canMint {
balances[target] += mintedAmount;
uint tokensInX = mintedAmount.div(tokenDecimals);
paidETH[target] += tokensInX.mul(accrueDividendsPerXTokenETH + accrueCouponsPerXTokenETH);
_totalSupply += mintedAmount;
Mint(owner, mintedAmount);
Transfer(0x0, target, mintedAmount);
}
/**
* Finish minting
*/
function finishMinting() public onlyOwner returns (bool) {
mintingFinished = true;
endSaleTime = now;
startRebuyTime = endSaleTime + (180 * 1 days);
MintFinished();
return true;
}
/**
* Withdraw accrued dividends and coupons
*/
function WithdrawDividendsAndCoupons() public {
withdrawTo(msg.sender,0);
}
/**
* Owner could initiate a withdrawal of accrued dividends and coupons to some address (in purpose to help users)
*/
function WithdrawDividendsAndCouponsTo(address _sendadr) public onlyOwner {
withdrawTo(_sendadr, tx.gasprice * block.gaslimit);
}
/**
* Internal function to withdraw accrued dividends and coupons
*/
function withdrawTo(address _sendadr, uint comiss) internal {
uint tokensPerX = balances[_sendadr].div(tokenDecimals);
uint sumPayd = paidETH[_sendadr];
uint sumToPayRes = tokensPerX.mul(accrueCouponsPerXTokenETH+accrueDividendsPerXTokenETH);
uint sumToPay = sumToPayRes.sub(comiss);
require(sumToPay>sumPayd);
sumToPay = sumToPay.sub(sumPayd);
_sendadr.transfer(sumToPay);
paidETH[_sendadr] = sumToPayRes;
}
/**
* Owner accrue new sum of dividends and coupons (once per month)
*/
function accrueDividendandCoupons(uint sumDivFinney, uint sumFinneyCoup) public onlyOwner {
sumDivFinney = sumDivFinney * 1 finney;
sumFinneyCoup = sumFinneyCoup * 1 finney;
uint tokens = _totalSupply.div(tokenDecimals);
accrueDividendsPerXTokenETH = accrueDividendsPerXTokenETH.add(sumDivFinney.div(tokens));
accrueCouponsPerXTokenETH = accrueCouponsPerXTokenETH.add(sumFinneyCoup.div(tokens));
}
/**
* Set a price of token to rebuy
*/
function setTokenPrice(uint priceFinney) public onlyOwner {
tokenPriceETH = priceFinney * 1 finney;
}
event RebuyInformEvent(address indexed adr, uint256 amount);
/**
* Inform owner that someone whant to sell tokens
* The rebuy proccess allowed in 2 weeks after inform
* Only after half a year after croudfunding
*/
function InformRebuy(uint sum) public {
_informRebuyTo(sum, msg.sender);
}
function InformRebuyTo(uint sum, address adr) public onlyOwner{
_informRebuyTo(sum, adr);
}
function _informRebuyTo(uint sum, address adr) internal{
require (rebuyStarted || (now >= startRebuyTime));
require (sum <= balances[adr]);
rebuyInformTime[adr] = now;
rebuySum[adr] = sum;
RebuyInformEvent(adr, sum);
}
/**
* Owner could allow rebuy proccess early
*/
function StartRebuy() public onlyOwner{
rebuyStarted = true;
}
/**
* Sell tokens after 2 weeks from information
*/
function doRebuy() public {
_doRebuyTo(msg.sender, 0);
}
/**
* Contract owner would perform tokens rebuy after 2 weeks from information
*/
function doRebuyTo(address adr) public onlyOwner {
_doRebuyTo(adr, tx.gasprice * block.gaslimit);
}
function _doRebuyTo(address adr, uint comiss) internal {
require (rebuyStarted || (now >= startRebuyTime));
require (now >= rebuyInformTime[adr].add(14 days));
uint sum = rebuySum[adr];
require (sum <= balances[adr]);
withdrawTo(adr, 0);
if (burnTo(sum, adr)) {
sum = sum.div(tokenDecimals);
sum = sum.mul(tokenPriceETH);
sum = sum.div(tokenDecimalsLeft);
sum = sum.sub(comiss);
adr.transfer(sum);
rebuySum[adr] = 0;
}
}
}
contract TSBCrowdFundingContract is NamedOwnedToken{
using SafeMath for uint256;
enum CrowdSaleState {NotFinished, Success, Failure}
CrowdSaleState public crowdSaleState = CrowdSaleState.NotFinished;
uint public fundingGoalUSD = 200000; //Min cap
uint public fundingMaxCapUSD = 500000; //Max cap
uint public priceUSD = 1; //Price in USD per 1 token
uint public USDDecimals = 1 ether;
uint public startTime; //crowdfunding start time
uint public endTime; //crowdfunding end time
uint public bonusEndTime; //crowdfunding end of bonus time
uint public selfDestroyTime = 2 weeks;
TSBToken public tokenReward; //TSB Token to send
uint public ETHPrice = 30000; //Current price of one ETH in USD cents
uint public BTCPrice = 400000; //Current price of one BTC in USD cents
uint public PriceDecimals = 100;
uint public ETHCollected = 0; //Collected sum of ETH
uint public BTCCollected = 0; //Collected sum of BTC
uint public amountRaisedUSD = 0; //Collected sum in USD
uint public TokenAmountToPay = 0; //Number of tokens to distribute (excluding bonus tokens)
mapping(address => uint256) public balanceMapPos;
struct mapStruct {
address mapAddress;
uint mapBalanceETH;
uint mapBalanceBTC;
uint bonusTokens;
}
mapStruct[] public balanceList; //Array of struct with information about invested sums
uint public bonusCapUSD = 100000; //Bonus cap
mapping(bytes32 => uint256) public bonusesMapPos;
struct bonusStruct {
uint balancePos;
bool notempty;
uint maxBonusETH;
uint maxBonusBTC;
uint bonusETH;
uint bonusBTC;
uint8 bonusPercent;
}
bonusStruct[] public bonusesList; //Array of struct with information about bonuses
bool public fundingGoalReached = false;
bool public crowdsaleClosed = false;
event GoalReached(address beneficiary, uint amountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
function TSBCrowdFundingContract(
uint _startTime,
uint durationInHours,
string tokenName,
string tokenSymbol
) NamedOwnedToken(tokenName, tokenSymbol) public {
// require(_startTime >= now);
SetStartTime(_startTime, durationInHours);
bonusCapUSD = bonusCapUSD * USDDecimals;
}
function SetStartTime(uint startT, uint durationInHours) public onlyOwner {
startTime = startT;
bonusEndTime = startT+ 24 hours;
endTime = startT + (durationInHours * 1 hours);
}
function assignTokenContract(address tok) public onlyOwner {
tokenReward = TSBToken(tok);
tokenReward.transferOwnership(address(this));
}
function () public payable {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
require( withinPeriod && nonZeroPurchase && (crowdSaleState == CrowdSaleState.NotFinished));
uint bonuspos = 0;
if (now <= bonusEndTime) {
// lastdata = msg.data;
bytes32 code = sha3(msg.data);
bonuspos = bonusesMapPos[code];
}
ReceiveAmount(msg.sender, msg.value, 0, now, bonuspos);
}
function CheckBTCtransaction() internal constant returns (bool) {
return true;
}
function AddBTCTransactionFromArray (address[] ETHadress, uint[] BTCnum, uint[] TransTime, bytes4[] bonusdata) public onlyOwner {
require(ETHadress.length == BTCnum.length);
require(TransTime.length == bonusdata.length);
require(ETHadress.length == bonusdata.length);
for (uint i = 0; i < ETHadress.length; i++) {
AddBTCTransaction(ETHadress[i], BTCnum[i], TransTime[i], bonusdata[i]);
}
}
/**
* Add transfered BTC, only owner could call
*
* @param ETHadress The address of ethereum wallet of sender
* @param BTCnum the received amount in BTC * 10^18
* @param TransTime the original (BTC) transaction time
*/
function AddBTCTransaction (address ETHadress, uint BTCnum, uint TransTime, bytes4 bonusdata) public onlyOwner {
require(CheckBTCtransaction());
require((TransTime >= startTime) && (TransTime <= endTime));
require(BTCnum != 0);
uint bonuspos = 0;
if (TransTime <= bonusEndTime) {
// lastdata = bonusdata;
bytes32 code = sha3(bonusdata);
bonuspos = bonusesMapPos[code];
}
ReceiveAmount(ETHadress, 0, BTCnum, TransTime, bonuspos);
}
modifier afterDeadline() { if (now >= endTime) _; }
/**
* Set price for ETH and BTC, only owner could call
*
* @param _ETHPrice ETH price in USD cents
* @param _BTCPrice BTC price in USD cents
*/
function SetCryptoPrice(uint _ETHPrice, uint _BTCPrice) public onlyOwner {
ETHPrice = _ETHPrice;
BTCPrice = _BTCPrice;
}
/**
* Convert sum in ETH plus BTC to USD
*
* @param ETH ETH sum in wei
* @param BTC BTC sum in 10^18
*/
function convertToUSD(uint ETH, uint BTC) public constant returns (uint) {
uint _ETH = ETH.mul(ETHPrice);
uint _BTC = BTC.mul(BTCPrice);
return (_ETH+_BTC).div(PriceDecimals);
}
/**
* Calc collected sum in USD
*/
function collectedSum() public constant returns (uint) {
return convertToUSD(ETHCollected,BTCCollected);
}
/**
* Check if min cap was reached (only after finish of crowdfunding)
*/
function checkGoalReached() public afterDeadline {
amountRaisedUSD = collectedSum();
if (amountRaisedUSD >= (fundingGoalUSD * USDDecimals) ){
crowdSaleState = CrowdSaleState.Success;
TokenAmountToPay = amountRaisedUSD;
GoalReached(owner, amountRaisedUSD);
} else {
crowdSaleState = CrowdSaleState.Failure;
}
}
/**
* Check if max cap was reached
*/
function checkMaxCapReached() public {
amountRaisedUSD = collectedSum();
if (amountRaisedUSD >= (fundingMaxCapUSD * USDDecimals) ){
crowdSaleState = CrowdSaleState.Success;
TokenAmountToPay = amountRaisedUSD;
GoalReached(owner, amountRaisedUSD);
}
}
function ReceiveAmount(address investor, uint sumETH, uint sumBTC, uint TransTime, uint bonuspos) internal {
require(investor != 0x0);
uint pos = balanceMapPos[investor];
if (pos>0) {
pos--;
assert(pos < balanceList.length);
assert(balanceList[pos].mapAddress == investor);
balanceList[pos].mapBalanceETH = balanceList[pos].mapBalanceETH.add(sumETH);
balanceList[pos].mapBalanceBTC = balanceList[pos].mapBalanceBTC.add(sumBTC);
} else {
mapStruct memory newStruct;
newStruct.mapAddress = investor;
newStruct.mapBalanceETH = sumETH;
newStruct.mapBalanceBTC = sumBTC;
newStruct.bonusTokens = 0;
pos = balanceList.push(newStruct);
balanceMapPos[investor] = pos;
pos--;
}
// update state
ETHCollected = ETHCollected.add(sumETH);
BTCCollected = BTCCollected.add(sumBTC);
checkBonus(pos, sumETH, sumBTC, TransTime, bonuspos);
checkMaxCapReached();
}
uint public DistributionNextPos = 0;
/**
* Distribute tokens to next N participants, only owner could call
*/
function DistributeNextNTokens(uint n) public payable onlyOwner {
require(BonusesDistributed);
require(DistributionNextPos<balanceList.length);
uint nextpos;
if (n == 0) {
nextpos = balanceList.length;
} else {
nextpos = DistributionNextPos.add(n);
if (nextpos > balanceList.length) {
nextpos = balanceList.length;
}
}
uint TokenAmountToPay_local = TokenAmountToPay;
for (uint i = DistributionNextPos; i < nextpos; i++) {
uint USDbalance = convertToUSD(balanceList[i].mapBalanceETH, balanceList[i].mapBalanceBTC);
uint tokensCount = USDbalance.mul(priceUSD);
tokenReward.mintToken(balanceList[i].mapAddress, tokensCount + balanceList[i].bonusTokens);
TokenAmountToPay_local = TokenAmountToPay_local.sub(tokensCount);
balanceList[i].mapBalanceETH = 0;
balanceList[i].mapBalanceBTC = 0;
}
TokenAmountToPay = TokenAmountToPay_local;
DistributionNextPos = nextpos;
}
function finishDistribution() onlyOwner {
require ((TokenAmountToPay == 0)||(DistributionNextPos >= balanceList.length));
// tokenReward.finishMinting();
tokenReward.transferOwnership(owner);
selfdestruct(owner);
}
/**
* Withdraw the funds
*
* Checks to see if goal was not reached, each contributor can withdraw
* the amount they contributed.
*/
function safeWithdrawal() public afterDeadline {
require(crowdSaleState == CrowdSaleState.Failure);
uint pos = balanceMapPos[msg.sender];
require((pos>0)&&(pos<=balanceList.length));
pos--;
uint amount = balanceList[pos].mapBalanceETH;
balanceList[pos].mapBalanceETH = 0;
if (amount > 0) {
msg.sender.transfer(amount);
FundTransfer(msg.sender, amount, false);
}
}
/**
* If something goes wrong owner could destroy the contract after 2 weeks from the crowdfunding end
* In this case the token distribution or sum refund will be performed in mannual
*/
function killContract() public onlyOwner {
require(now >= endTime + selfDestroyTime);
tokenReward.transferOwnership(owner);
selfdestruct(owner);
}
/**
* Add a new bonus code, only owner could call
*/
function AddBonusToListFromArray(bytes32[] bonusCode, uint[] ETHsumInFinney, uint[] BTCsumInFinney) public onlyOwner {
require(bonusCode.length == ETHsumInFinney.length);
require(bonusCode.length == BTCsumInFinney.length);
for (uint i = 0; i < bonusCode.length; i++) {
AddBonusToList(bonusCode[i], ETHsumInFinney[i], BTCsumInFinney[i] );
}
}
/**
* Add a new bonus code, only owner could call
*/
function AddBonusToList(bytes32 bonusCode, uint ETHsumInFinney, uint BTCsumInFinney) public onlyOwner {
uint pos = bonusesMapPos[bonusCode];
if (pos > 0) {
pos -= 1;
bonusesList[pos].maxBonusETH = ETHsumInFinney * 1 finney;
bonusesList[pos].maxBonusBTC = BTCsumInFinney * 1 finney;
} else {
bonusStruct memory newStruct;
newStruct.balancePos = 0;
newStruct.notempty = false;
newStruct.maxBonusETH = ETHsumInFinney * 1 finney;
newStruct.maxBonusBTC = BTCsumInFinney * 1 finney;
newStruct.bonusETH = 0;
newStruct.bonusBTC = 0;
newStruct.bonusPercent = 20;
pos = bonusesList.push(newStruct);
bonusesMapPos[bonusCode] = pos;
}
}
bool public BonusesDistributed = false;
uint public BonusCalcPos = 0;
// bytes public lastdata;
function checkBonus(uint newBalancePos, uint sumETH, uint sumBTC, uint TransTime, uint pos) internal {
if (pos > 0) {
pos--;
if (!bonusesList[pos].notempty) {
bonusesList[pos].balancePos = newBalancePos;
bonusesList[pos].notempty = true;
} else {
if (bonusesList[pos].balancePos != newBalancePos) return;
}
bonusesList[pos].bonusETH = bonusesList[pos].bonusETH.add(sumETH);
// if (bonusesList[pos].bonusETH > bonusesList[pos].maxBonusETH)
// bonusesList[pos].bonusETH = bonusesList[pos].maxBonusETH;
bonusesList[pos].bonusBTC = bonusesList[pos].bonusBTC.add(sumBTC);
// if (bonusesList[pos].bonusBTC > bonusesList[pos].maxBonusBTC)
// bonusesList[pos].bonusBTC = bonusesList[pos].maxBonusBTC;
}
}
/**
* Calc the number of bonus tokens for N next bonus participants, only owner could call
*/
function calcNextNBonuses(uint N) public onlyOwner {
require(crowdSaleState == CrowdSaleState.Success);
require(!BonusesDistributed);
uint nextPos = BonusCalcPos + N;
if (nextPos > bonusesList.length)
nextPos = bonusesList.length;
uint bonusCapUSD_local = bonusCapUSD;
for (uint i = BonusCalcPos; i < nextPos; i++) {
if ((bonusesList[i].notempty) && (bonusesList[i].balancePos < balanceList.length)) {
uint maxbonus = convertToUSD(bonusesList[i].maxBonusETH, bonusesList[i].maxBonusBTC);
uint bonus = convertToUSD(bonusesList[i].bonusETH, bonusesList[i].bonusBTC);
if (maxbonus < bonus)
bonus = maxbonus;
bonus = bonus.mul(priceUSD);
if (bonusCapUSD_local >= bonus) {
bonusCapUSD_local = bonusCapUSD_local - bonus;
} else {
bonus = bonusCapUSD_local;
bonusCapUSD_local = 0;
}
bonus = bonus.mul(bonusesList[i].bonusPercent) / 100;
balanceList[bonusesList[i].balancePos].bonusTokens = bonus;
if (bonusCapUSD_local == 0) {
BonusesDistributed = true;
break;
}
}
}
bonusCapUSD = bonusCapUSD_local;
BonusCalcPos = nextPos;
if (nextPos >= bonusesList.length) {
BonusesDistributed = true;
}
}
} | Check if the sender has enough
| require(_value > 0); | 12,838,139 | [
1,
1564,
309,
326,
5793,
711,
7304,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
24899,
1132,
405,
374,
1769,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xD68f4CAE482452ad9986183C10CF17AD5734efE5/sources/contracts/Project.sol | Mint check helper. Early bail if paused. Protect against contract minting. Ensure non-zero mint amount. Ensure available supply. Ensure mint limit not exceeded. Ensure proper payment. | modifier mintCheck (uint256 _numToMint) {
require(status != Status.Paused, "Minting is paused");
require(!Address.isContract(_msgSender()), "Cannot mint from contract");
require(_numToMint > 0, "Cannot mint zero tokens");
require(totalSupply() + _numToMint <= maxSupply, "Max supply exceeded");
require(_numToMint <= mintLimit(), "Cannot mint this many tokens");
require(msg.value == _numToMint * mintPrice(), "Incorrect payment amount sent");
_;
}
| 8,762,339 | [
1,
49,
474,
866,
4222,
18,
512,
20279,
18422,
309,
17781,
18,
1186,
88,
386,
5314,
6835,
312,
474,
310,
18,
7693,
1661,
17,
7124,
312,
474,
3844,
18,
7693,
2319,
14467,
18,
7693,
312,
474,
1800,
486,
12428,
18,
7693,
5338,
5184,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
312,
474,
1564,
261,
11890,
5034,
389,
2107,
774,
49,
474,
13,
288,
203,
3639,
2583,
12,
2327,
480,
2685,
18,
28590,
16,
315,
49,
474,
310,
353,
17781,
8863,
203,
203,
3639,
2583,
12,
5,
1887,
18,
291,
8924,
24899,
3576,
12021,
1435,
3631,
315,
4515,
312,
474,
628,
6835,
8863,
203,
203,
3639,
2583,
24899,
2107,
774,
49,
474,
405,
374,
16,
315,
4515,
312,
474,
3634,
2430,
8863,
203,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
397,
389,
2107,
774,
49,
474,
1648,
943,
3088,
1283,
16,
315,
2747,
14467,
12428,
8863,
203,
203,
3639,
2583,
24899,
2107,
774,
49,
474,
1648,
312,
474,
3039,
9334,
315,
4515,
312,
474,
333,
4906,
2430,
8863,
203,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
389,
2107,
774,
49,
474,
380,
312,
474,
5147,
9334,
315,
16268,
5184,
3844,
3271,
8863,
203,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// The difference with GamersePool is without rewardHolder
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./libs/SafeBEP20.sol";
contract GamersePool2 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Accrued token per share
uint256 public accTokenPerShare;
// The block number when GAMERSE mining ends.
uint256 public bonusEndBlock;
// The block number when GAMERSE mining starts.
uint256 public startBlock;
// The block number of the last pool update
uint256 public lastRewardBlock;
// GAMERSE tokens created per block.
uint256 public rewardPerBlock;
// The precision factor
uint256 public immutable PRECISION_FACTOR;
// The reward token. It cannot mark as immutable because need to read its
// precision in constructor.
IBEP20 public rewardToken;
// The staked token
IBEP20 public immutable stakedToken;
// Max penalty fee: 50%
uint256 public constant MAXIMUM_PENALTY_FEE = 5000;
// Max penalty duration: 30 days
uint256 public constant MAXIMUM_PENALTY_DURATION = 30 days;
// Max airdrop staking duration
uint256 public constant MAXIMUM_AIRDROP_DURATION = 85 * 28780;
// Default max staking amount per account
uint256 public constant DEFAULT_MAX_STAKING_AMOUNT = 500000000000000000000000;
// Penalty Fee
uint256 public penaltyFee;
// Penalty Duration in seconds
uint256 public penaltyDuration;
// The balance left to reward stakers
uint256 public rewardBalance;
// The total reward amount been used
uint256 public rewardedAmount;
// custody address, the penalized rewards go to this address
address public custodyAddress;
// airdrop NFT minimum staking amount
uint256 public adMinStakeAmount;
// duration in blocks needed for airdrop
uint256 public adDuration;
// maximum staking amount per user
uint256 public maxStakeAmount;
// Total staked amount of all user
uint256 public totalStakedAmount;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256 rewardDebt; // Reward debt
uint256 rewardDeposit; // Reward from deposits
uint256 penaltyUntil; //When can the user withdraw without penalty
uint256 lastDeposit; // When user deposit last time
uint256 adStartBlock; // When user started to take part in airdrop by staking adMinStakeAmount
}
event AdminTokenRecovery(address tokenRecovered, uint256 amount);
event Deposit(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
event NewRewardPerBlock(uint256 rewardPerBlock);
event RewardsStop(uint256 blockNumber);
event Withdraw(address indexed user, uint256 amount);
event NewPenaltyFee(uint256 fee);
event NewPenaltyDuration(uint256 fee);
event RewardClaimed(address indexed account, uint256 amount);
event RewardPenalized(address indexed account, uint256 amount);
constructor(
address _owner,
IBEP20 _stakedToken,
IBEP20 _rewardToken,
address _custodyAddress,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock,
uint256 _penaltyFee,
uint256 _penaltyDuration,
uint256 _adMinStakeAmount,
uint256 _adDuration
) public {
require(_penaltyFee <= MAXIMUM_PENALTY_FEE, "Invalid penalty fee");
require(_penaltyDuration <= MAXIMUM_PENALTY_DURATION, "Invalid penalty duration");
require(_custodyAddress != address(0), "Invalid custody address");
require(_adDuration <= MAXIMUM_AIRDROP_DURATION, "Invalid airdrop duration");
require(_owner != address(0), "Invalid owner address");
transferOwnership(_owner);
stakedToken = _stakedToken;
rewardToken = _rewardToken;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
penaltyFee = _penaltyFee;
penaltyDuration = _penaltyDuration;
custodyAddress = _custodyAddress;
adMinStakeAmount = _adMinStakeAmount;
adDuration = _adDuration;
maxStakeAmount = DEFAULT_MAX_STAKING_AMOUNT;
uint256 decimalsRewardToken = uint256(rewardToken.decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken)));
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
}
/*
* @notice Deposit staked tokens and calculate the reward tokens.
* @param _amount: amount to deposit (in stakedToken)
*/
function deposit(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
require(
user.amount.add(_amount) <= maxStakeAmount,
"Total amount exceeds max staking amount per user"
);
_updatePool();
uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(
user.rewardDebt
);
if (pending != 0) {
user.rewardDeposit = user.rewardDeposit.add(pending);
}
if (_amount != 0) {
stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
totalStakedAmount = totalStakedAmount.add(_amount);
if (user.penaltyUntil == 0) {
user.penaltyUntil = block.timestamp.add(penaltyDuration);
}
}
_updateAirdrop();
user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR);
emit Deposit(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens. If withdraw
* before penaltyUntil then part of the rewards will be penalized.
* @param _amount: amount to withdraw (in stakedToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "Amount to withdraw too high");
_updatePool();
uint256 pending = user
.amount
.mul(accTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt)
.add(user.rewardDeposit);
require(rewardBalance >= pending, "Reward balance is not enough");
if (_amount != 0) {
user.amount = user.amount.sub(_amount);
stakedToken.safeTransfer(address(msg.sender), _amount);
totalStakedAmount = totalStakedAmount.sub(_amount);
}
if (pending != 0) {
rewardBalance = rewardBalance.sub(pending);
// This also includes burned amount, because burned amount also come from reward balance
rewardedAmount = rewardedAmount.add(pending);
// If user withdraw after the pool ends, then no penalty
if (block.timestamp < user.penaltyUntil && block.number < bonusEndBlock) {
uint256 penaltyAmount = pending.mul(penaltyFee).div(10000);
rewardToken.safeTransfer(custodyAddress, penaltyAmount);
emit RewardPenalized(msg.sender, penaltyAmount);
rewardToken.safeTransfer(address(msg.sender), pending.sub(penaltyAmount));
emit RewardClaimed(msg.sender, pending.sub(penaltyAmount));
} else {
rewardToken.safeTransfer(address(msg.sender), pending);
emit RewardClaimed(msg.sender, pending);
}
user.rewardDeposit = 0;
}
_updateAirdrop();
user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR);
emit Withdraw(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens without caring about rewards rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.penaltyUntil = 0;
user.lastDeposit = 0;
user.rewardDeposit = 0;
user.adStartBlock = 0;
if (amountToTransfer != 0) {
stakedToken.safeTransfer(address(msg.sender), amountToTransfer);
emit EmergencyWithdraw(msg.sender, amountToTransfer);
totalStakedAmount = totalStakedAmount.sub(amountToTransfer);
}
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakedToken), "Cannot be staked token");
require(_tokenAddress != address(rewardToken), "Cannot be reward token");
IBEP20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _rewardPerBlock: the reward per block
*/
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
require(block.number < startBlock, "Pool has started");
_updatePool();
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
/**
* @notice It allows the admin to update start and end blocks
* @dev This function is only callable by owner.
* @param _startBlock: the new start block
* @param _bonusEndBlock: the new end block
*/
function updateStartAndEndBlocks(uint256 _startBlock, uint256 _bonusEndBlock)
external
onlyOwner
{
require(startBlock < _startBlock, "New startBlock must be bigger than previous one");
require(_startBlock < _bonusEndBlock, "New startBlock must be lower than new endBlock");
require(block.number < _startBlock, "New startBlock must be higher than current block");
_updatePool();
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock);
}
/*
* @notice Update the penalty fee
* @dev Only callable by owner.
* @param _fee: the penalty fee
*/
function updatePenaltyFee(uint256 _fee) external onlyOwner {
require(_fee <= MAXIMUM_PENALTY_FEE, "Invalid penalty fee");
penaltyFee = _fee;
emit NewPenaltyFee(_fee);
}
/*
* @notice Update the penalty duration
* @dev Only callable by owner.
* @param _duration: the penalty duration in seconds
*/
function updatePenaltyDuration(uint256 _duration) external onlyOwner {
require(_duration <= MAXIMUM_PENALTY_DURATION, "Invalid penalty duration");
penaltyDuration = _duration;
emit NewPenaltyDuration(_duration);
}
/*
* @notice Update the custody address
* @dev Only callable by owner.
* @param _account: custody address
*/
function updateCustodyAddress(address _account) external onlyOwner {
require(_account != address(0), "Invalid address");
custodyAddress = _account;
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
if (block.number > lastRewardBlock && totalStakedAmount != 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(rewardPerBlock);
uint256 adjustedTokenPerShare = accTokenPerShare.add(
cakeReward.mul(PRECISION_FACTOR).div(totalStakedAmount)
);
return
user
.amount
.mul(adjustedTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt)
.add(user.rewardDeposit);
} else {
return
user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt).add(
user.rewardDeposit
);
}
}
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
if (totalStakedAmount == 0) {
lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(rewardPerBlock);
accTokenPerShare = accTokenPerShare.add(
cakeReward.mul(PRECISION_FACTOR).div(totalStakedAmount)
);
lastRewardBlock = block.number;
}
/*
* @notice Update user's airdrop information
*/
function _updateAirdrop() internal {
if (bonusEndBlock < block.number) {
return;
}
UserInfo storage user = userInfo[msg.sender];
if (user.amount < adMinStakeAmount) {
user.adStartBlock = 0;
return;
}
if (
user.amount >= adMinStakeAmount &&
user.adStartBlock == 0 &&
block.number.add(adDuration) <= bonusEndBlock
) {
user.adStartBlock = block.number;
}
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
*/
function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from);
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock.sub(_from);
}
}
/*
* @notice Update the maximum staking amount per user
* @dev Only callable by owner.
* @param amount: the new maximum staking amount per user
*/
function updateMaxStakeAmount(uint256 amount) external onlyOwner {
maxStakeAmount = amount;
}
function updateAdMinStakeAmount(uint256 _adMinStakeAmount) external onlyOwner {
adMinStakeAmount = _adMinStakeAmount;
}
function updateAdDuration(uint256 _adDuration) external onlyOwner {
require(_adDuration <= MAXIMUM_AIRDROP_DURATION, "Invalid airdrop duration");
adDuration = _adDuration;
}
function addReward(uint256 _amount) external onlyOwner {
require(_amount > 0, "Invalid amount");
stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
rewardBalance = rewardBalance.add(_amount);
}
}
| @notice Update the maximum staking amount per user @dev Only callable by owner. @param amount: the new maximum staking amount per user/ | function updateMaxStakeAmount(uint256 amount) external onlyOwner {
maxStakeAmount = amount;
}
| 13,084,607 | [
1,
1891,
326,
4207,
384,
6159,
3844,
1534,
729,
225,
5098,
4140,
635,
3410,
18,
225,
3844,
30,
326,
394,
4207,
384,
6159,
3844,
1534,
729,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
2747,
510,
911,
6275,
12,
11890,
5034,
3844,
13,
3903,
1338,
5541,
288,
203,
3639,
943,
510,
911,
6275,
273,
3844,
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
] |
/*
Copyright 2019 The Hydro Protocol 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.
*/
pragma solidity 0.5.8;
pragma experimental ABIEncoderV2;
interface IEth2Dai{
function isClosed()
external
view
returns (bool);
function buyEnabled()
external
view
returns (bool);
function matchingEnabled()
external
view
returns (bool);
function getBuyAmount(
address buy_gem,
address pay_gem,
uint256 pay_amt
)
external
view
returns (uint256);
function getPayAmount(
address pay_gem,
address buy_gem,
uint256 buy_amt
)
external
view
returns (uint256);
}
interface IMakerDaoOracle{
function peek()
external
view
returns (bytes32, bool);
}
interface IStandardToken {
function transfer(
address _to,
uint256 _amount
)
external
returns (bool);
function balanceOf(
address _owner)
external
view
returns (uint256 balance);
function transferFrom(
address _from,
address _to,
uint256 _amount
)
external
returns (bool);
function approve(
address _spender,
uint256 _amount
)
external
returns (bool);
function allowance(
address _owner,
address _spender
)
external
view
returns (uint256);
}
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(), "NOT_OWNER");
_;
}
/** @return true if `msg.sender` is the owner of the contract. */
function isOwner()
public
view
returns(bool)
{
return msg.sender == _owner;
}
/** @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/** @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(
address newOwner
)
public
onlyOwner
{
require(newOwner != address(0), "INVALID_OWNER");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
// Multiplies two numbers, reverts on overflow.
function mul(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MUL_ERROR");
return c;
}
// 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, "DIVIDING_ERROR");
return a / b;
}
function divCeil(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
uint256 quotient = div(a, b);
uint256 remainder = a - quotient * b;
if (remainder > 0) {
return quotient + 1;
} else {
return quotient;
}
}
// 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, "SUB_ERROR");
return a - b;
}
function sub(
int256 a,
uint256 b
)
internal
pure
returns (int256)
{
require(b <= 2**255-1, "INT256_SUB_ERROR");
int256 c = a - int256(b);
require(c <= a, "INT256_SUB_ERROR");
return c;
}
// Adds two numbers, reverts on overflow.
function add(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
uint256 c = a + b;
require(c >= a, "ADD_ERROR");
return c;
}
function add(
int256 a,
uint256 b
)
internal
pure
returns (int256)
{
require(b <= 2**255 - 1, "INT256_ADD_ERROR");
int256 c = a + int256(b);
require(c >= a, "INT256_ADD_ERROR");
return c;
}
// 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, "MOD_ERROR");
return a % b;
}
/**
* Check the amount of precision lost by calculating multiple * (numerator / denominator). To
* do this, we check the remainder and make sure it's proportionally less than 0.1%. So we have:
*
* ((numerator * multiple) % denominator) 1
* -------------------------------------- < ----
* numerator * multiple 1000
*
* To avoid further division, we can move the denominators to the other sides and we get:
*
* ((numerator * multiple) % denominator) * 1000 < numerator * multiple
*
* Since we want to return true if there IS a rounding error, we simply flip the sign and our
* final equation becomes:
*
* ((numerator * multiple) % denominator) * 1000 >= numerator * multiple
*
* @param numerator The numerator of the proportion
* @param denominator The denominator of the proportion
* @param multiple The amount we want a proportion of
* @return Boolean indicating if there is a rounding error when calculating the proportion
*/
function isRoundingError(
uint256 numerator,
uint256 denominator,
uint256 multiple
)
internal
pure
returns (bool)
{
// numerator.mul(multiple).mod(denominator).mul(1000) >= numerator.mul(multiple)
return mul(mod(mul(numerator, multiple), denominator), 1000) >= mul(numerator, multiple);
}
/**
* Takes an amount (multiple) and calculates a proportion of it given a numerator/denominator
* pair of values. The final value will be rounded down to the nearest integer value.
*
* This function will revert the transaction if rounding the final value down would lose more
* than 0.1% precision.
*
* @param numerator The numerator of the proportion
* @param denominator The denominator of the proportion
* @param multiple The amount we want a proportion of
* @return The final proportion of multiple rounded down
*/
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 multiple
)
internal
pure
returns (uint256)
{
require(!isRoundingError(numerator, denominator, multiple), "ROUNDING_ERROR");
// numerator.mul(multiple).div(denominator)
return div(mul(numerator, multiple), denominator);
}
/**
* Returns the smaller integer of the two passed in.
*
* @param a Unsigned integer
* @param b Unsigned integer
* @return The smaller of the two integers
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
contract DaiPriceOracle is Ownable{
using SafeMath for uint256;
uint256 public price;
uint256 constant ONE = 10**18;
IMakerDaoOracle public constant makerDaoOracle = IMakerDaoOracle(0x729D19f657BD0614b4985Cf1D82531c67569197B);
IStandardToken public constant DAI = IStandardToken(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359);
IEth2Dai public constant Eth2Dai = IEth2Dai(0x39755357759cE0d7f32dC8dC45414CCa409AE24e);
address public constant UNISWAP = 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public constant eth2daiETHAmount = 10 ether;
uint256 public constant eth2daiMaxSpread = 2 * ONE / 100; // 2.00%
uint256 public constant uniswapMinETHAmount = 2000 ether;
event UpdatePrice(uint256 newPrice);
function getPrice(
address asset
)
external
view
returns (uint256)
{
require(asset == address(DAI), "ASSET_NOT_MATCH");
return price;
}
function adminSetPrice(
uint256 _price
)
external
onlyOwner
{
if (!updatePrice()){
price = _price;
}
emit UpdatePrice(price);
}
function updatePrice()
public
returns (bool)
{
uint256 _price = peek();
if (_price != 0) {
price = _price;
emit UpdatePrice(price);
return true;
} else {
return false;
}
}
function peek()
public
view
returns (uint256 _price)
{
uint256 makerDaoPrice = getMakerDaoPrice();
if (makerDaoPrice == 0) {
return _price;
}
uint256 eth2daiPrice = getEth2DaiPrice();
if (eth2daiPrice > 0) {
_price = makerDaoPrice.mul(ONE).div(eth2daiPrice);
return _price;
}
uint256 uniswapPrice = getUniswapPrice();
if (uniswapPrice > 0) {
_price = makerDaoPrice.mul(ONE).div(uniswapPrice);
return _price;
}
return _price;
}
function getEth2DaiPrice()
public
view
returns (uint256)
{
if (Eth2Dai.isClosed() || !Eth2Dai.buyEnabled() || !Eth2Dai.matchingEnabled()) {
return 0;
}
uint256 bidDai = Eth2Dai.getBuyAmount(address(DAI), WETH, eth2daiETHAmount);
uint256 askDai = Eth2Dai.getPayAmount(address(DAI), WETH, eth2daiETHAmount);
uint256 bidPrice = bidDai.mul(ONE).div(eth2daiETHAmount);
uint256 askPrice = askDai.mul(ONE).div(eth2daiETHAmount);
uint256 spread = askPrice.mul(ONE).div(bidPrice).sub(ONE);
if (spread > eth2daiMaxSpread) {
return 0;
} else {
return bidPrice.add(askPrice).div(2);
}
}
function getUniswapPrice()
public
view
returns (uint256)
{
uint256 ethAmount = UNISWAP.balance;
uint256 daiAmount = DAI.balanceOf(UNISWAP);
uint256 uniswapPrice = daiAmount.mul(10**18).div(ethAmount);
if (ethAmount < uniswapMinETHAmount) {
return 0;
} else {
return uniswapPrice;
}
}
function getMakerDaoPrice()
public
view
returns (uint256)
{
(bytes32 value, bool has) = makerDaoOracle.peek();
if (has) {
return uint256(value);
} else {
return 0;
}
}
} | * Check the amount of precision lost by calculating multiple (numerator / denominator). To do this, we check the remainder and make sure it's proportionally less than 0.1%. So we have: ((numerator multiple) % denominator) 1 -------------------------------------- < ---- numerator multiple 1000 To avoid further division, we can move the denominators to the other sides and we get: ((numerator multiple) % denominator) 1000 < numerator multiple Since we want to return true if there IS a rounding error, we simply flip the sign and our final equation becomes: ((numerator multiple) % denominator) 1000 >= numerator multiple @param numerator The numerator of the proportion @param denominator The denominator of the proportion @param multiple The amount we want a proportion of @return Boolean indicating if there is a rounding error when calculating the proportion/ numerator.mul(multiple).mod(denominator).mul(1000) >= numerator.mul(multiple) | function isRoundingError(
uint256 numerator,
uint256 denominator,
uint256 multiple
)
internal
pure
returns (bool)
{
return mul(mod(mul(numerator, multiple), denominator), 1000) >= mul(numerator, multiple);
}
| 1,782,392 | [
1,
1564,
326,
3844,
434,
6039,
13557,
635,
21046,
3229,
225,
261,
2107,
7385,
342,
15030,
2934,
2974,
741,
333,
16,
732,
866,
326,
10022,
471,
1221,
3071,
518,
1807,
23279,
1230,
5242,
2353,
374,
18,
21,
9,
18,
6155,
732,
1240,
30,
377,
14015,
2107,
7385,
225,
3229,
13,
738,
15030,
13,
377,
404,
377,
19134,
13465,
411,
27927,
2868,
16730,
225,
3229,
5411,
4336,
2974,
4543,
9271,
16536,
16,
732,
848,
3635,
326,
10716,
30425,
358,
326,
1308,
22423,
471,
732,
336,
30,
377,
14015,
2107,
7385,
225,
3229,
13,
738,
15030,
13,
225,
4336,
411,
16730,
225,
3229,
7897,
732,
2545,
358,
327,
638,
309,
1915,
4437,
279,
13885,
555,
16,
732,
8616,
9668,
326,
1573,
471,
3134,
727,
15778,
12724,
30,
377,
14015,
2107,
7385,
225,
3229,
13,
738,
15030,
13,
225,
4336,
1545,
16730,
225,
3229,
225,
16730,
1021,
16730,
434,
326,
23279,
225,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
353,
11066,
310,
668,
12,
203,
3639,
2254,
5034,
16730,
16,
203,
3639,
2254,
5034,
15030,
16,
203,
3639,
2254,
5034,
3229,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
14064,
12,
1711,
12,
16411,
12,
2107,
7385,
16,
3229,
3631,
15030,
3631,
4336,
13,
1545,
14064,
12,
2107,
7385,
16,
3229,
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
] |
pragma solidity ^0.4.0;
contract EtherTanks {
struct TankHull {
uint32 armor; // Hull's armor value
uint32 speed; // Hull's speed value
uint8 league; // The battle league which allows to play with this hull type
}
struct TankWeapon {
uint32 minDamage; // Weapon minimal damage value
uint32 maxDamage; // Weapon maximum damage value
uint32 attackSpeed; // Weapon's attack speed value
uint8 league; // The battle league which allows to play with this weapon type
}
struct TankProduct {
string name; // Tank's name
uint32 hull; // Hull's ID
uint32 weapon; // Weapon's ID
// Unfortunately, it's imposible to define the variable inside the struct as constant.
// However, you can read this smart-contract and see that there are no changes at all related to the start prices.
uint256 startPrice;
uint256 currentPrice; // The current price. Changes every time someone buys this kind of tank
uint256 earning; // The amount of earning each owner of this tank gets when someone buys this type of tank
uint256 releaseTime; // The moment when it will be allowed to buy this type of tank
}
struct TankEntity {
uint32 productID;
uint8[4] upgrades;
address owner; // The address of the owner of this tank
address earner; // The address of the earner of this tank who get paid
bool selling; // Is this tank on the auction now?
uint256 auctionEntity; // If it's on the auction,
uint256 earned; // Total funds earned with this tank
uint32 exp; // Tank's experience
}
struct AuctionEntity {
uint32 tankId;
uint256 startPrice;
uint256 finishPrice;
uint256 startTime;
uint256 duration;
}
event EventCashOut (
address indexed player,
uint256 amount
); //;-)
event EventLogin (
address indexed player,
string hash
); //;-)
event EventUpgradeTank (
address indexed player,
uint32 tankID,
uint8 upgradeChoice
); // ;-)
event EventTransfer (
address indexed player,
address indexed receiver,
uint32 tankID
); // ;-)
event EventTransferAction (
address indexed player,
address indexed receiver,
uint32 tankID,
uint8 ActionType
); // ;-)
event EventAuction (
address indexed player,
uint32 tankID,
uint256 startPrice,
uint256 finishPrice,
uint256 duration,
uint256 currentTime
); // ;-)
event EventCancelAuction (
uint32 tankID
); // ;-)
event EventBid (
uint32 tankID
); // ;-)
event EventProduct (
uint32 productID,
string name,
uint32 hull,
uint32 weapon,
uint256 price,
uint256 earning,
uint256 releaseTime,
uint256 currentTime
); // ;-)
event EventBuyTank (
address indexed player,
uint32 productID,
uint32 tankID
); // ;-)
address public UpgradeMaster; // Earns fees for upgrading tanks (0.05 Eth)
address public AuctionMaster; // Earns fees for producing auctions (3%)
address public TankSellMaster; // Earns fees for selling tanks (start price)
// No modifiers were needed, because each access is checked no more than one time in the whole code,
// So calling "require(msg.sender == UpgradeMaster);" is enough.
function ChangeUpgradeMaster (address _newMaster) public {
require(msg.sender == UpgradeMaster);
UpgradeMaster = _newMaster;
}
function ChangeTankSellMaster (address _newMaster) public {
require(msg.sender == TankSellMaster);
TankSellMaster = _newMaster;
}
function ChangeAuctionMaster (address _newMaster) public {
require(msg.sender == AuctionMaster);
AuctionMaster = _newMaster;
}
function EtherTanks() public {
UpgradeMaster = msg.sender;
AuctionMaster = msg.sender;
TankSellMaster = msg.sender;
// Creating 11 hulls
newTankHull(100, 5, 1);
newTankHull(60, 6, 2);
newTankHull(140, 4, 1);
newTankHull(200, 3, 1);
newTankHull(240, 3, 1);
newTankHull(200, 6, 2);
newTankHull(360, 4, 2);
newTankHull(180, 9, 3);
newTankHull(240, 8, 3);
newTankHull(500, 4, 2);
newTankHull(440, 6, 3);
// Creating 11 weapons
newTankWeapon(6, 14, 5, 1);
newTankWeapon(18, 26, 3, 2);
newTankWeapon(44, 66, 2, 1);
newTankWeapon(21, 49, 3, 1);
newTankWeapon(60, 90, 2, 2);
newTankWeapon(21, 49, 2, 2);
newTankWeapon(48, 72, 3, 2);
newTankWeapon(13, 29, 9, 3);
newTankWeapon(36, 84, 4, 3);
newTankWeapon(120, 180, 2, 3);
newTankWeapon(72, 108, 4, 3);
// Creating first 11 tank types
newTankProduct("LT-1", 1, 1, 10000000000000000, 100000000000000, now);
newTankProduct("LT-2", 2, 2, 50000000000000000, 500000000000000, now);
newTankProduct("MT-1", 3, 3, 100000000000000000, 1000000000000000, now);
newTankProduct("HT-1", 4, 4, 500000000000000000, 5000000000000000, now);
newTankProduct("SPG-1", 5, 5, 500000000000000000, 5000000000000000, now);
newTankProduct("MT-2", 6, 6, 700000000000000000, 7000000000000000, now+(60*60*2));
newTankProduct("HT-2", 7, 7, 1500000000000000000, 15000000000000000, now+(60*60*5));
newTankProduct("LT-3", 8, 8, 300000000000000000, 3000000000000000, now+(60*60*8));
newTankProduct("MT-3", 9, 9, 1500000000000000000, 15000000000000000, now+(60*60*24));
newTankProduct("SPG-2", 10, 10, 2000000000000000000, 20000000000000000, now+(60*60*24*2));
newTankProduct("HT-3", 11, 11, 2500000000000000000, 25000000000000000, now+(60*60*24*3));
}
function cashOut (uint256 _amount) public payable {
require (_amount >= 0); //just in case
require (_amount == uint256(uint128(_amount))); // Just some magic stuff
require (this.balance >= _amount); // Checking if this contract has enought money to pay
require (balances[msg.sender] >= _amount); // Checking if player has enough funds on his balance
if (_amount == 0){
_amount = balances[msg.sender];
// If the requested amount is 0, it means that player wants to cashout the whole amount of balance
}
if (msg.sender.send(_amount)){ // Sending funds and if the transaction is successful
balances[msg.sender] -= _amount; // Changing the amount of funds on the player's in-game balance
}
EventCashOut (msg.sender, _amount);
return;
}
function login (string _hash) public {
EventLogin (msg.sender, _hash);
return;
}
//upgrade tank
// @_upgradeChoice: 0 is for armor, 1 is for damage, 2 is for speed, 3 is for attack speed
function upgradeTank (uint32 _tankID, uint8 _upgradeChoice) public payable {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].owner == msg.sender); // Checking if sender owns this tank
require (_upgradeChoice >= 0 && _upgradeChoice < 4); // Has to be between 0 and 3
require (tanks[_tankID].upgrades[_upgradeChoice] < 5); // Only 5 upgrades are allowed for each type of tank's parametres
require (msg.value >= upgradePrice); // Checking if there is enough amount of money for the upgrade
tanks[_tankID].upgrades[_upgradeChoice]++; // Upgrading
balances[msg.sender] += msg.value-upgradePrice; // Returning the rest amount of money back to the tank owner
balances[UpgradeMaster] += upgradePrice; // Sending the amount of money spent on the upgrade to the contract creator
EventUpgradeTank (msg.sender, _tankID, _upgradeChoice);
return;
}
// Transfer. Using for sending tanks to another players
function _transfer (uint32 _tankID, address _receiver) public {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].owner == msg.sender); //Checking if sender owns this tank
require (msg.sender != _receiver); // Checking that the owner is not sending the tank to himself
require (tanks[_tankID].selling == false); //Making sure that the tank is not on the auction now
tanks[_tankID].owner = _receiver; // Changing the tank's owner
tanks[_tankID].earner = _receiver; // Changing the tank's earner address
EventTransfer (msg.sender, _receiver, _tankID);
return;
}
// Transfer Action. Using for sending tanks to EtherTanks' contracts. For example, the battle-area contract.
function _transferAction (uint32 _tankID, address _receiver, uint8 _ActionType) public {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].owner == msg.sender); // Checking if sender owns this tank
require (msg.sender != _receiver); // Checking that the owner is not sending the tank to himself
require (tanks[_tankID].selling == false); // Making sure that the tank is not on the auction now
tanks[_tankID].owner = _receiver; // Changing the tank's owner
// As you can see, we do not change the earner here.
// It means that technically speaking, the tank's owner is still getting his earnings.
// It's logically that this method (transferAction) will be used for sending tanks to the battle area contract or some other contracts which will be interacting with tanks
// Be careful with this method! Do not call it to transfer tanks to another player!
// The reason you should not do this is that the method called "transfer" changes the owner and earner, so it is possible to change the earner address to the current owner address any time.
// However, for our special contracts like battle area, you are able to read this contract and make sure that your tank will not be sent to anyone else, only back to you.
// So, please, do not use this method to send your tanks to other players. Use it just for interacting with EtherTanks' contracts, which will be listed on EtherTanks.com
EventTransferAction (msg.sender, _receiver, _tankID, _ActionType);
return;
}
//selling
function sellTank (uint32 _tankID, uint256 _startPrice, uint256 _finishPrice, uint256 _duration) public {
require (_tankID > 0 && _tankID < newIdTank);
require (tanks[_tankID].owner == msg.sender);
require (tanks[_tankID].selling == false); // Making sure that the tank is not on the auction already
require (_startPrice >= _finishPrice);
require (_startPrice > 0 && _finishPrice >= 0);
require (_duration > 0);
require (_startPrice == uint256(uint128(_startPrice))); // Just some magic stuff
require (_finishPrice == uint256(uint128(_finishPrice))); // Just some magic stuff
auctions[newIdAuctionEntity] = AuctionEntity(_tankID, _startPrice, _finishPrice, now, _duration);
tanks[_tankID].selling = true;
tanks[_tankID].auctionEntity = newIdAuctionEntity++;
EventAuction (msg.sender, _tankID, _startPrice, _finishPrice, _duration, now);
}
//bidding function, people use this to buy tanks
function bid (uint32 _tankID) public payable {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].selling == true); // Checking if this tanks is on the auction now
AuctionEntity memory currentAuction = auctions[tanks[_tankID].auctionEntity]; // The auction entity for this tank. Just to make the line below easier to read
uint256 currentPrice = currentAuction.startPrice-(((currentAuction.startPrice-currentAuction.finishPrice)/(currentAuction.duration))*(now-currentAuction.startTime));
// The line above calculates the current price using the formula StartPrice-(((StartPrice-FinishPrice)/Duration)*(CurrentTime-StartTime)
if (currentPrice < currentAuction.finishPrice){ // If the auction duration time has been expired
currentPrice = currentAuction.finishPrice; // Setting the current price as finishPrice
}
require (currentPrice >= 0); // Who knows :)
require (msg.value >= currentPrice); // Checking if the buyer sent the amount of money which is more or equal the current price
// All is fine, changing balances and changing tank's owner
uint256 marketFee = (currentPrice/100)*3; // Calculating 3% of the current price as a fee
balances[tanks[_tankID].owner] += currentPrice-marketFee; // Giving [current price]-[fee] amount to seller
balances[AuctionMaster] += marketFee; // Sending the fee amount to the contract creator's balance
balances[msg.sender] += msg.value-currentPrice; //Return the rest amount to buyer
tanks[_tankID].owner = msg.sender; // Changing the owner of the tank
tanks[_tankID].selling = false; // Change the tank status to "not selling now"
delete auctions[tanks[_tankID].auctionEntity]; // Deleting the auction entity from the storage for auctions -- we don't need it anymore
tanks[_tankID].auctionEntity = 0; // Not necessary, but deleting the ID of auction entity which was deleted in the operation above
EventBid (_tankID);
}
//cancel auction
function cancelAuction (uint32 _tankID) public {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].selling == true); // Checking if this tanks is on the auction now
require (tanks[_tankID].owner == msg.sender); // Checking if sender owns this tank
tanks[_tankID].selling = false; // Change the tank status to "not selling now"
delete auctions[tanks[_tankID].auctionEntity]; // Deleting the auction entity from the storage for auctions -- we don't need it anymore
tanks[_tankID].auctionEntity = 0; // Not necessary, but deleting the ID of auction entity which was deleted in the operation above
EventCancelAuction (_tankID);
}
function newTankProduct (string _name, uint32 _hull, uint32 _weapon, uint256 _price, uint256 _earning, uint256 _releaseTime) private {
tankProducts[newIdTankProduct++] = TankProduct(_name, _hull, _weapon, _price, _price, _earning, _releaseTime);
EventProduct (newIdTankProduct-1, _name, _hull, _weapon, _price, _earning, _releaseTime, now);
}
function newTankHull (uint32 _armor, uint32 _speed, uint8 _league) private {
tankHulls[newIdTankHull++] = TankHull(_armor, _speed, _league);
}
function newTankWeapon (uint32 _minDamage, uint32 _maxDamage, uint32 _attackSpeed, uint8 _league) private {
tankWeapons[newIdTankWeapon++] = TankWeapon(_minDamage, _maxDamage, _attackSpeed, _league);
}
function buyTank (uint32 _tankproductID) public payable {
require (tankProducts[_tankproductID].currentPrice > 0 && msg.value > 0); //value is more than 0, price is more than 0
require (msg.value >= tankProducts[_tankproductID].currentPrice); //value is higher than price
require (tankProducts[_tankproductID].releaseTime <= now); //checking if this tank was released.
// Basically, the releaseTime was implemented just to give a chance to get the new tank for as many players as possible.
// It prevents the using of bots.
if (msg.value > tankProducts[_tankproductID].currentPrice){
// If player payed more, put the rest amount of money on his balance
balances[msg.sender] += msg.value-tankProducts[_tankproductID].currentPrice;
}
tankProducts[_tankproductID].currentPrice += tankProducts[_tankproductID].earning;
for (uint32 index = 1; index < newIdTank; index++){
if (tanks[index].productID == _tankproductID){
balances[tanks[index].earner] += tankProducts[_tankproductID].earning;
tanks[index].earned += tankProducts[_tankproductID].earning;
}
}
if (tanksBeforeTheNewTankType() == 0 && newIdTankProduct <= 121){
newTankType();
}
tanks[newIdTank++] = TankEntity (_tankproductID, [0, 0, 0, 0], msg.sender, msg.sender, false, 0, 0, 0);
// After all owners of the same type of tank got their earnings, admins get the amount which remains and no one need it
// Basically, it is the start price of the tank.
balances[TankSellMaster] += tankProducts[_tankproductID].startPrice;
EventBuyTank (msg.sender, _tankproductID, newIdTank-1);
return;
}
// This is the tricky method which creates the new type tank.
function newTankType () public {
if (newIdTankProduct > 121){
return;
}
//creating new tank type!
if (createNewTankHull < newIdTankHull - 1 && createNewTankWeapon >= newIdTankWeapon - 1) {
createNewTankWeapon = 1;
createNewTankHull++;
} else {
createNewTankWeapon++;
if (createNewTankHull == createNewTankWeapon) {
createNewTankWeapon++;
}
}
newTankProduct ("Tank", uint32(createNewTankHull), uint32(createNewTankWeapon), 200000000000000000, 3000000000000000, now+(60*60));
return;
}
// Our storage, keys are listed first, then mappings.
// Of course, instead of some mappings we could use arrays, but why not
uint32 public newIdTank = 1; // The next ID for the new tank
uint32 public newIdTankProduct = 1; // The next ID for the new tank type
uint32 public newIdTankHull = 1; // The next ID for the new hull
uint32 public newIdTankWeapon = 1; // The new ID for the new weapon
uint32 public createNewTankHull = 1; // For newTankType()
uint32 public createNewTankWeapon = 0; // For newTankType()
uint256 public newIdAuctionEntity = 1; // The next ID for the new auction entity
mapping (uint32 => TankEntity) tanks; // The storage
mapping (uint32 => TankProduct) tankProducts;
mapping (uint32 => TankHull) tankHulls;
mapping (uint32 => TankWeapon) tankWeapons;
mapping (uint256 => AuctionEntity) auctions;
mapping (address => uint) balances;
uint256 public constant upgradePrice = 50000000000000000; // The fee which the UgradeMaster earns for upgrading tanks
function getTankName (uint32 _ID) public constant returns (string){
return tankProducts[_ID].name;
}
function getTankProduct (uint32 _ID) public constant returns (uint32[6]){
return [tankHulls[tankProducts[_ID].hull].armor, tankHulls[tankProducts[_ID].hull].speed, tankWeapons[tankProducts[_ID].weapon].minDamage, tankWeapons[tankProducts[_ID].weapon].maxDamage, tankWeapons[tankProducts[_ID].weapon].attackSpeed, uint32(tankProducts[_ID].releaseTime)];
}
function getTankDetails (uint32 _ID) public constant returns (uint32[6]){
return [tanks[_ID].productID, uint32(tanks[_ID].upgrades[0]), uint32(tanks[_ID].upgrades[1]), uint32(tanks[_ID].upgrades[2]), uint32(tanks[_ID].upgrades[3]), uint32(tanks[_ID].exp)];
}
function getTankOwner(uint32 _ID) public constant returns (address){
return tanks[_ID].owner;
}
function getTankSell(uint32 _ID) public constant returns (bool){
return tanks[_ID].selling;
}
function getTankTotalEarned(uint32 _ID) public constant returns (uint256){
return tanks[_ID].earned;
}
function getTankAuctionEntity (uint32 _ID) public constant returns (uint256){
return tanks[_ID].auctionEntity;
}
function getCurrentPrice (uint32 _ID) public constant returns (uint256){
return tankProducts[_ID].currentPrice;
}
function getProductEarning (uint32 _ID) public constant returns (uint256){
return tankProducts[_ID].earning;
}
function getTankEarning (uint32 _ID) public constant returns (uint256){
return tanks[_ID].earned;
}
function getCurrentPriceAuction (uint32 _ID) public constant returns (uint256){
require (getTankSell(_ID));
AuctionEntity memory currentAuction = auctions[tanks[_ID].auctionEntity]; // The auction entity for this tank. Just to make the line below easier to read
uint256 currentPrice = currentAuction.startPrice-(((currentAuction.startPrice-currentAuction.finishPrice)/(currentAuction.duration))*(now-currentAuction.startTime));
if (currentPrice < currentAuction.finishPrice){ // If the auction duration time has been expired
currentPrice = currentAuction.finishPrice; // Setting the current price as finishPrice
}
return currentPrice;
}
function getPlayerBalance(address _player) public constant returns (uint256){
return balances[_player];
}
function getContractBalance() public constant returns (uint256){
return this.balance;
}
function howManyTanks() public constant returns (uint32){
return newIdTankProduct;
}
function tanksBeforeTheNewTankType() public constant returns (uint256){
return 1000+(((newIdTankProduct)+10)*((newIdTankProduct)+10)*(newIdTankProduct-11))-newIdTank;
}
}
/*
EtherTanks.com
EthereTanks.com
*/ | If player payed more, put the rest amount of money on his balance | if (msg.value > tankProducts[_tankproductID].currentPrice){
balances[msg.sender] += msg.value-tankProducts[_tankproductID].currentPrice;
}
tankProducts[_tankproductID].currentPrice += tankProducts[_tankproductID].earning;
| 12,630,254 | [
1,
2047,
7291,
8843,
329,
1898,
16,
1378,
326,
3127,
3844,
434,
15601,
603,
18423,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
3576,
18,
1132,
405,
268,
2304,
13344,
63,
67,
88,
2304,
5896,
734,
8009,
2972,
5147,
15329,
203,
5411,
324,
26488,
63,
3576,
18,
15330,
65,
1011,
1234,
18,
1132,
17,
88,
2304,
13344,
63,
67,
88,
2304,
5896,
734,
8009,
2972,
5147,
31,
203,
3639,
289,
203,
540,
203,
3639,
268,
2304,
13344,
63,
67,
88,
2304,
5896,
734,
8009,
2972,
5147,
1011,
268,
2304,
13344,
63,
67,
88,
2304,
5896,
734,
8009,
73,
9542,
31,
203,
540,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import './lib/Babylonian.sol';
import './lib/FixedPoint.sol';
import './lib/Safe112.sol';
import './owner/Operator.sol';
import './utils/ContractGuard.sol';
import './interfaces/IBasisAsset.sol';
import './interfaces/IOracle.sol';
import './interfaces/IBoardroom.sol';
/**
* @title Basis Cash Treasury contract
* @notice Monetary policy logic to adjust supplies of basis cash assets
* @author Summer Smith & Rick Sanchez
*/
contract Treasury is ContractGuard, Operator {
using FixedPoint for *;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using Safe112 for uint112;
/* ========= CONSTANT VARIABLES ======== */
uint256 public constant allocationDelay = 1 days;
/* ========== STATE VARIABLES ========== */
address private cash;
address private bond;
address private share;
address private boardroom;
IOracle private cashOracle;
bool private migrated = false;
uint256 private seigniorageSaved = 0;
uint256 public startTime;
uint256 public cashPriceCeiling;
uint256 public cashPriceOne;
uint256 private bondDepletionFloor;
uint256 private lastAllocated;
/* ========== CONSTRUCTOR ========== */
constructor(
address _cash,
address _bond,
address _share,
address _cashOracle,
address _boardroom,
uint256 _startTime
) public {
cash = _cash;
bond = _bond;
share = _share;
cashOracle = IOracle(_cashOracle);
boardroom = _boardroom;
startTime = _startTime;
cashPriceOne = 10**18;
cashPriceCeiling = uint256(105).mul(cashPriceOne).div(10**2);
bondDepletionFloor = uint256(1000).mul(cashPriceOne);
lastAllocated = now;
}
/* ========== MODIFIER ========== */
modifier checkMigration {
require(!migrated, 'Treasury: this contract has been migrated');
_;
}
modifier checkOperator {
require(
IBasisAsset(cash).operator() == address(this),
'Treasury: this contract is not the operator of the basis cash contract'
);
require(
IBasisAsset(bond).operator() == address(this),
'Treasury: this contract is not the operator of the basis bond contract'
);
require(
Operator(boardroom).operator() == address(this),
'Treasury: this contract is not the operator of the boardroom contract'
);
_;
}
/* ========== VIEW FUNCTIONS ========== */
function getCashPrice() public view returns (uint256 cashPrice) {
try cashOracle.consult(cash, 1e18) returns (uint256 price) {
return price;
} catch {
revert('Treasury: failed to consult cash price from the oracle');
}
}
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
/* ========== GOVERNANCE ========== */
function migrate(address target) public onlyOperator checkMigration {
// cash
Operator(cash).transferOperator(target);
Operator(cash).transferOwnership(target);
IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this)));
// bond
Operator(bond).transferOperator(target);
Operator(bond).transferOwnership(target);
IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
// share
Operator(share).transferOperator(target);
Operator(share).transferOwnership(target);
IERC20(share).transfer(target, IERC20(share).balanceOf(address(this)));
migrated = true;
emit Migration(target);
}
/* ========== MUTABLE FUNCTIONS ========== */
function _getCashPrice() internal returns (uint256 cashPrice) {
cashPrice = getCashPrice();
try cashOracle.update() {} catch {
revert('Treasury: failed to update cash oracle');
}
}
function _allocateSeigniorage(uint256 cashPrice)
internal
onlyOneBlock
checkOperator
checkMigration
returns (bool, string memory)
{
if (now.sub(lastAllocated) < allocationDelay) {
return (false, 'Treasury: a day has not passed yet');
}
if (block.timestamp < startTime) {
return (false, 'Treasury: not started yet');
}
if (cashPrice <= cashPriceCeiling) {
return (false, 'Treasury: there is no seigniorage to be allocated');
}
uint256 cashSupply = IERC20(cash).totalSupply().sub(seigniorageSaved);
uint256 percentage = cashPrice.sub(cashPriceOne);
uint256 seigniorage = cashSupply.mul(percentage).div(1e18);
if (seigniorageSaved > bondDepletionFloor) {
IBasisAsset(cash).mint(address(this), seigniorage);
IERC20(cash).safeApprove(boardroom, seigniorage);
IBoardroom(boardroom).allocateSeigniorage(seigniorage);
emit BoardroomFunded(now, seigniorage);
} else {
seigniorageSaved = seigniorageSaved.add(seigniorage);
IBasisAsset(cash).mint(address(this), seigniorage);
emit TreasuryFunded(now, seigniorage);
}
lastAllocated = now;
return (true, 'Treasury: success');
}
function buyBonds(uint256 amount, uint256 targetPrice) external {
require(amount > 0, 'Treasury: cannot purchase bonds with zero amount');
uint256 cashPrice = _getCashPrice();
require(cashPrice == targetPrice, 'Treasury: cash price moved');
_allocateSeigniorage(cashPrice); // ignore returns
uint256 bondPrice = cashPrice;
IBasisAsset(cash).burnFrom(msg.sender, amount);
IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(bondPrice));
emit BoughtBonds(msg.sender, amount);
}
function redeemBonds(uint256 amount, uint256 targetPrice) external {
require(amount > 0, 'Treasury: cannot redeem bonds with zero amount');
uint256 cashPrice = _getCashPrice();
require(cashPrice == targetPrice, 'Treasury: cash price moved');
_allocateSeigniorage(cashPrice); // ignore returns
require(
cashPrice > cashPriceCeiling,
'Treasury: bond redemption failed; basis cash remains depegged.'
);
uint256 treasuryBalance = IERC20(cash).balanceOf(address(this));
require(
treasuryBalance >= amount,
'Treasury: treasury has no more budget'
);
if (seigniorageSaved >= amount) {
seigniorageSaved = seigniorageSaved.sub(amount);
} else {
seigniorageSaved = 0;
}
IBasisAsset(bond).burnFrom(msg.sender, amount);
IERC20(cash).safeTransfer(msg.sender, amount);
emit RedeemedBonds(msg.sender, amount);
}
function allocateSeigniorage() external {
uint256 cashPrice = _getCashPrice();
(bool result, string memory reason) = _allocateSeigniorage(cashPrice);
require(result, reason);
}
event Migration(address indexed target);
event RedeemedBonds(address indexed from, uint256 amount);
event BoughtBonds(address indexed from, uint256 amount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event BoardroomFunded(uint256 timestamp, uint256 seigniorage);
}
| * @title Basis Cash Treasury contract @notice Monetary policy logic to adjust supplies of basis cash assets @author Summer Smith & Rick Sanchez/ | contract Treasury is ContractGuard, Operator {
using FixedPoint for *;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using Safe112 for uint112;
uint256 public constant allocationDelay = 1 days;
address private cash;
address private bond;
address private share;
address private boardroom;
IOracle private cashOracle;
bool private migrated = false;
uint256 private seigniorageSaved = 0;
uint256 public startTime;
uint256 public cashPriceCeiling;
uint256 public cashPriceOne;
uint256 private bondDepletionFloor;
uint256 private lastAllocated;
constructor(
address _cash,
address _bond,
address _share,
address _cashOracle,
address _boardroom,
uint256 _startTime
) public {
cash = _cash;
bond = _bond;
share = _share;
cashOracle = IOracle(_cashOracle);
boardroom = _boardroom;
startTime = _startTime;
cashPriceOne = 10**18;
cashPriceCeiling = uint256(105).mul(cashPriceOne).div(10**2);
bondDepletionFloor = uint256(1000).mul(cashPriceOne);
lastAllocated = now;
}
modifier checkMigration {
require(!migrated, 'Treasury: this contract has been migrated');
_;
}
modifier checkOperator {
require(
IBasisAsset(cash).operator() == address(this),
'Treasury: this contract is not the operator of the basis cash contract'
);
require(
IBasisAsset(bond).operator() == address(this),
'Treasury: this contract is not the operator of the basis bond contract'
);
require(
Operator(boardroom).operator() == address(this),
'Treasury: this contract is not the operator of the boardroom contract'
);
_;
}
function getCashPrice() public view returns (uint256 cashPrice) {
try cashOracle.consult(cash, 1e18) returns (uint256 price) {
return price;
revert('Treasury: failed to consult cash price from the oracle');
}
}
function getCashPrice() public view returns (uint256 cashPrice) {
try cashOracle.consult(cash, 1e18) returns (uint256 price) {
return price;
revert('Treasury: failed to consult cash price from the oracle');
}
}
} catch {
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
function migrate(address target) public onlyOperator checkMigration {
Operator(cash).transferOperator(target);
Operator(cash).transferOwnership(target);
IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this)));
Operator(bond).transferOperator(target);
Operator(bond).transferOwnership(target);
IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
Operator(share).transferOperator(target);
Operator(share).transferOwnership(target);
IERC20(share).transfer(target, IERC20(share).balanceOf(address(this)));
migrated = true;
emit Migration(target);
}
function _getCashPrice() internal returns (uint256 cashPrice) {
cashPrice = getCashPrice();
revert('Treasury: failed to update cash oracle');
}
try cashOracle.update() {} catch {
}
| 6,360,228 | [
1,
11494,
291,
385,
961,
399,
266,
345,
22498,
6835,
225,
26196,
3329,
4058,
358,
5765,
1169,
5259,
434,
10853,
276,
961,
7176,
225,
9352,
6592,
9425,
483,
473,
534,
1200,
348,
304,
343,
6664,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
399,
266,
345,
22498,
353,
13456,
16709,
16,
11097,
288,
203,
565,
1450,
15038,
2148,
364,
380,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
17666,
364,
2254,
17666,
31,
203,
203,
203,
565,
2254,
5034,
1071,
5381,
13481,
6763,
273,
404,
4681,
31,
203,
203,
203,
565,
1758,
3238,
276,
961,
31,
203,
565,
1758,
3238,
8427,
31,
203,
565,
1758,
3238,
7433,
31,
203,
565,
1758,
3238,
11094,
13924,
31,
203,
565,
1665,
16873,
3238,
276,
961,
23601,
31,
203,
203,
565,
1426,
3238,
24741,
273,
629,
31,
203,
565,
2254,
5034,
3238,
695,
724,
77,
1531,
16776,
273,
374,
31,
203,
565,
2254,
5034,
1071,
8657,
31,
203,
565,
2254,
5034,
1071,
276,
961,
5147,
39,
73,
4973,
31,
203,
565,
2254,
5034,
1071,
276,
961,
5147,
3335,
31,
203,
565,
2254,
5034,
3238,
8427,
758,
1469,
285,
42,
5807,
31,
203,
565,
2254,
5034,
3238,
1142,
29392,
31,
203,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
71,
961,
16,
203,
3639,
1758,
389,
26425,
16,
203,
3639,
1758,
389,
14419,
16,
203,
3639,
1758,
389,
71,
961,
23601,
16,
203,
3639,
1758,
389,
3752,
13924,
16,
203,
3639,
2254,
5034,
389,
1937,
950,
203,
565,
262,
1071,
288,
203,
3639,
276,
961,
273,
389,
71,
961,
31,
203,
3639,
8427,
273,
389,
26425,
31,
203,
3639,
7433,
273,
389,
14419,
31,
2
] |
pragma solidity ^0.4.0;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract Anemoi is owned {
uint256 public totalSupply;
// Public variables for the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly default, avoid changing it
uint256 public totalSuply;
/* Creates an array with balances */
mapping (address => uint256) public balanceOf;
/* Initilizes contract with initial supply tokens to the creator of the contract */
function Anemoi(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) {
totalSupply = initialSupply;
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
uint256 intialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
address centralMinter) {
if(centralMinter != 0 ) owner = centralMinter;
}
}
/* Sent coins */
function transfer(address _to, uint256 _value) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balance
require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
balanceOf[msg.sender] -= _value; // Substract from the sender
balanceOf[_to] += _value; // Add the same to the recipent
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint °value) internal {
require (_to != 0*0); // Prevent transfer to 0*0 address. Use burn() instead
require (balanceOf[_from] > _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Chek for overflows
require(!frozenAccount[_from]); // Check if recipient is frozenAccount
balanceOf[_from] -= _value; // Substract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function mintToken(address targget, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount):
Transfer(owner, target, mintedAmount);
}
}
| Chek for overflows
| require (balanceOf[_to] + _value > balanceOf[_to]); | 974,637 | [
1,
39,
580,
79,
364,
9391,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
202,
6528,
261,
12296,
951,
63,
67,
869,
65,
397,
389,
1132,
405,
11013,
951,
63,
67,
869,
19226,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4E716Cca0AF6531a1a8e82f58aAe0B55d8D87CB0/sources/CafeChefDitto.sol | Calculate Fee % of the amount | function calculateFee(uint256 _amount) public view returns (uint256) {
return _amount.mul(FEE).div(MAX_FEE);
}
| 11,114,115 | [
1,
8695,
30174,
738,
434,
326,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4604,
14667,
12,
11890,
5034,
389,
8949,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
8949,
18,
16411,
12,
8090,
41,
2934,
2892,
12,
6694,
67,
8090,
41,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x427419dF01AF63fa3218b40Cea0D9eF80346154C/sources/Minions.sol | @notice EIP-20 token name for this token @notice EIP-20 token symbol for this token @notice EIP-20 token decimals for this token @notice Total number of tokens in circulation @dev Allowance amounts on behalf of others @dev Official record of token balances for each account @notice A record of each accounts delegate @notice A checkpoint for marking number of votes from a given block | struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
| 705,788 | [
1,
41,
2579,
17,
3462,
1147,
508,
364,
333,
1147,
225,
512,
2579,
17,
3462,
1147,
3273,
364,
333,
1147,
225,
512,
2579,
17,
3462,
1147,
15105,
364,
333,
1147,
225,
10710,
1300,
434,
2430,
316,
5886,
1934,
367,
225,
7852,
1359,
30980,
603,
12433,
6186,
434,
10654,
225,
531,
4493,
649,
1409,
434,
1147,
324,
26488,
364,
1517,
2236,
225,
432,
1409,
434,
1517,
9484,
7152,
225,
432,
9776,
364,
24073,
1300,
434,
19588,
628,
279,
864,
1203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
25569,
288,
203,
3639,
2254,
1578,
628,
1768,
31,
203,
3639,
2254,
10525,
19588,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// 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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IAggregator {
function decimals() external view returns (uint8);
function latestAnswer() external view returns (int256 answer);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.6.12;
interface IOracle {
/// @notice Get the latest exchange rate.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function get(bytes calldata data) external returns (bool success, uint256 rate);
/// @notice Check the last exchange rate without any state changes.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function peek(bytes calldata data) external view returns (bool success, uint256 rate);
/// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek().
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return rate The rate of the requested asset / pair / pool.
function peekSpot(bytes calldata data) external view returns (uint256 rate);
/// @notice Returns a human readable (short) name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable symbol name about this oracle.
function symbol(bytes calldata data) external view returns (string memory);
/// @notice Returns a human readable name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable name about this oracle.
function name(bytes calldata data) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IPopsicle {
function pool() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function strategy() external view returns (address);
function usersAmounts() external view returns (uint256 amount0, uint256 amount1);
function totalSupply() external view returns (uint256 amount);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function withdraw(uint256 shares, address to) external returns (uint256 amount0, uint256 amount1);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address to
)
external
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../interfaces/IAggregator.sol";
import "../interfaces/IOracle.sol";
import "../interfaces/IPopsicle.sol";
contract PLPOracle is IOracle {
IAggregator public immutable token0Aggregator;
IAggregator public immutable token1Aggregator;
IPopsicle public immutable plp;
uint256 private immutable token0NormalizeScale;
uint256 private immutable token1NormalizeScale;
constructor(
IPopsicle _plp,
IAggregator _token0Aggregator,
IAggregator _token1Aggregator
) {
plp = _plp;
token0Aggregator = _token0Aggregator;
token1Aggregator = _token1Aggregator;
uint256 token0Decimals = ERC20(_plp.token0()).decimals();
uint256 token1Decimals = ERC20(_plp.token1()).decimals();
uint256 token0AggregatorDecimals = _token0Aggregator.decimals();
uint256 token1AggregatorDecimals = _token1Aggregator.decimals();
token0NormalizeScale = (10**(36 - token0Decimals - token0AggregatorDecimals));
token1NormalizeScale = (10**(36 - token1Decimals - token1AggregatorDecimals));
}
// Calculates the lastest exchange rate
function _get() internal view returns (uint256) {
(uint256 amount0, uint256 amount1) = plp.usersAmounts();
uint256 token0Price = amount0 * uint256(token0Aggregator.latestAnswer()) * token0NormalizeScale;
uint256 token1Price = amount1 * uint256(token1Aggregator.latestAnswer()) * token1NormalizeScale;
uint256 plpPrice = (token0Price + token1Price) / plp.totalSupply();
return 1e36 / plpPrice;
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public pure override returns (string memory) {
return "Chainlink Popsicle";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public pure override returns (string memory) {
return "LINK/PLP";
}
} | Calculates the lastest exchange rate | function _get() internal view returns (uint256) {
(uint256 amount0, uint256 amount1) = plp.usersAmounts();
uint256 token0Price = amount0 * uint256(token0Aggregator.latestAnswer()) * token0NormalizeScale;
uint256 token1Price = amount1 * uint256(token1Aggregator.latestAnswer()) * token1NormalizeScale;
uint256 plpPrice = (token0Price + token1Price) / plp.totalSupply();
return 1e36 / plpPrice;
}
| 1,679,932 | [
1,
10587,
326,
1142,
395,
7829,
4993,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
588,
1435,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
261,
11890,
5034,
3844,
20,
16,
2254,
5034,
3844,
21,
13,
273,
886,
84,
18,
5577,
6275,
87,
5621,
203,
203,
3639,
2254,
5034,
1147,
20,
5147,
273,
3844,
20,
380,
2254,
5034,
12,
2316,
20,
17711,
18,
13550,
13203,
10756,
380,
1147,
20,
14380,
5587,
31,
203,
3639,
2254,
5034,
1147,
21,
5147,
273,
3844,
21,
380,
2254,
5034,
12,
2316,
21,
17711,
18,
13550,
13203,
10756,
380,
1147,
21,
14380,
5587,
31,
3639,
203,
540,
203,
3639,
2254,
5034,
886,
84,
5147,
273,
261,
2316,
20,
5147,
397,
1147,
21,
5147,
13,
342,
886,
84,
18,
4963,
3088,
1283,
5621,
203,
203,
3639,
327,
404,
73,
5718,
342,
886,
84,
5147,
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
] |
./partial_match/3/0xbe4A328576C72275B7b16B9D330dbB42553230C6/sources/BKP_PreSale.sol | 1609437600; 31 dec 2020 6pm GMT 5:40
| sales[1].endDate = 1607517600; | 5,178,406 | [
1,
2313,
5908,
24,
6418,
28133,
31,
225,
8231,
2109,
26599,
20,
1666,
7755,
21706,
225,
1381,
30,
7132,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
272,
5408,
63,
21,
8009,
409,
1626,
273,
25430,
5877,
4033,
28133,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
//Author: @MilkyTasteNFT MilkyTaste:8662
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
contract MilkToken is ERC721Enumerable, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
// Used for placeholder
string private placeholderURI;
string private baseURI;
uint256 public tokenPrice = 5000000000000000; // 0.005 ETH
uint256 private _supplyCap = 25;
mapping(uint256 => bool) private _tokenRevealed;
constructor() ERC721('MilkToken', 'MILK') {
placeholderURI = 'https://milkytaste.xyz/milktoken/placeholder.json';
baseURI = 'https://milkytaste.xyz/milktoken/';
doMintToken(_msgSender());
_tokenRevealed[1] = true;
}
/**
* @dev Only allow one token per address.
*/
modifier canOwnMore(address _to) {
require(ERC721.balanceOf(_to) < 1, 'MilkToken: cannot own more MilkTokens');
_;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override canOwnMore(to) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Withdraw funds to owner address.
*/
function withdraw(address payable withdrawTo) public onlyOwner {
uint balance = address(this).balance;
withdrawTo.transfer(balance);
}
/**
* @dev Withdraw funds to owner address.
*/
function setTokenPrice(uint256 newTokenPrice) public onlyOwner {
tokenPrice = newTokenPrice;
}
/**
* @dev Update the placeholder URI and clear the baseURI
*/
function setPlaceholderURI(string memory newURI) external onlyOwner {
placeholderURI = newURI;
baseURI = '';
}
/**
* @dev Update the base URI
*/
function setBaseURI(string memory newURI) external onlyOwner {
baseURI = newURI;
}
/**
* @dev Update the base URI
*/
function setSupplyCap(uint256 newSupplyCap) external onlyOwner {
_supplyCap = newSupplyCap;
}
/**
* @dev Reveal a token
*/
function revealToken(uint256 tokenId) external onlyOwner {
_tokenRevealed[tokenId] = true;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "MilkToken: URI query for nonexistent token");
if (_tokenRevealed[tokenId] && bytes(baseURI).length > 0) {
return string(abi.encodePacked(baseURI, tokenId.toString(), '.json'));
}
return placeholderURI;
}
/**
* @dev Mints a new token
*/
function mintToken(address addr) public canOwnMore(addr) payable returns (uint256) {
require(msg.value == tokenPrice, "MilkToken: ether value incorrect");
return doMintToken(addr);
}
/**
* @dev Owner can mint for free
*/
function ownerMintToken(address addr) public onlyOwner returns (uint256) {
return doMintToken(addr);
}
/**
* @dev Do the minting here
*/
function doMintToken(address addr) internal canOwnMore(addr) returns (uint256) {
require(_tokenIds.current() < _supplyCap, 'MilkToken: supply cap reached');
_tokenIds.increment();
uint256 id = _tokenIds.current();
_safeMint(addr, id);
return id;
}
/**
* @dev Return the total supply
*/
function supplyCap() public view virtual returns (uint256) {
return _supplyCap;
}
}
| * @dev Return the total supply/ | function supplyCap() public view virtual returns (uint256) {
return _supplyCap;
}
| 2,561,062 | [
1,
990,
326,
2078,
14467,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
14467,
4664,
1435,
1071,
1476,
5024,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
2463,
389,
2859,
1283,
4664,
31,
203,
202,
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
] |
./partial_match/1/0x17D0Fd46e35B77ACF822C27b5a8b2D9df9e557dC/sources/OTTO.sol | exclude from paying fees or having max transaction amount | constructor() ERC20(_name, _symbol) {
uint256 _devBuyTax = 25;
uint256 _liqBuyTax = 0;
uint256 _devSellTax = 25;
uint256 _liqSellTax = 0;
uint256 totalSupply = 10000000000 * 1e18;
devBuyTax = _devBuyTax;
liqBuyTax = _liqBuyTax;
totalBuyTax = devBuyTax + liqBuyTax;
devSellTax = _devSellTax;
liqSellTax = _liqSellTax;
totalSellTax = devSellTax + liqSellTax;
devWallet = address(msg.sender);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(address(devWallet), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(address(devWallet), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(address(this), totalSupply);
| 9,174,857 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
24899,
529,
16,
389,
7175,
13,
288,
203,
7010,
3639,
203,
7010,
3639,
2254,
5034,
389,
5206,
38,
9835,
7731,
273,
6969,
31,
203,
3639,
2254,
5034,
389,
549,
85,
38,
9835,
7731,
273,
374,
31,
203,
7010,
3639,
2254,
5034,
389,
5206,
55,
1165,
7731,
273,
6969,
31,
203,
3639,
2254,
5034,
389,
549,
85,
55,
1165,
7731,
273,
374,
31,
203,
540,
203,
3639,
2254,
5034,
2078,
3088,
1283,
273,
2130,
12648,
380,
404,
73,
2643,
31,
203,
7010,
7010,
3639,
4461,
38,
9835,
7731,
273,
389,
5206,
38,
9835,
7731,
31,
203,
3639,
4501,
85,
38,
9835,
7731,
273,
389,
549,
85,
38,
9835,
7731,
31,
203,
3639,
2078,
38,
9835,
7731,
273,
4461,
38,
9835,
7731,
397,
4501,
85,
38,
9835,
7731,
31,
203,
7010,
3639,
4461,
55,
1165,
7731,
273,
389,
5206,
55,
1165,
7731,
31,
203,
3639,
4501,
85,
55,
1165,
7731,
273,
389,
549,
85,
55,
1165,
7731,
31,
203,
3639,
2078,
55,
1165,
7731,
273,
4461,
55,
1165,
7731,
397,
4501,
85,
55,
1165,
7731,
31,
203,
3639,
4461,
16936,
273,
1758,
12,
3576,
18,
15330,
1769,
203,
3639,
203,
7010,
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,
3639,
4433,
1265,
2954,
281,
12,
2867,
12,
5206,
16936,
3631,
638,
1769,
203,
7010,
3639,
4433,
1265,
2747,
3342,
2
] |
./full_match/1/0x00000000009726632680FB29d3F7A9734E3010E2/sources/contracts/libraries/PermitHelper.sol | @title PermitHelper @dev Helper methods for using ERC20 Permit (ERC2612 or DAI/CHAI like) | library PermitHelper {
pragma solidity =0.8.11;
struct Permit {
uint256 value;
uint256 nonce;
uint256 deadline;
bool isDaiStylePermit;
uint8 v;
bytes32 r;
bytes32 s;
}
function permit(
Permit memory permitData,
address tokenAddress,
address holder,
address spender
) internal {
if (permitData.isDaiStylePermit) {
IDAI(tokenAddress).permit(
holder,
spender,
permitData.nonce,
permitData.deadline,
true,
permitData.v,
permitData.r,
permitData.s
);
IERC2612(tokenAddress).permit(
holder,
spender,
permitData.value,
permitData.deadline,
permitData.v,
permitData.r,
permitData.s
);
}
}
function permit(
Permit memory permitData,
address tokenAddress,
address holder,
address spender
) internal {
if (permitData.isDaiStylePermit) {
IDAI(tokenAddress).permit(
holder,
spender,
permitData.nonce,
permitData.deadline,
true,
permitData.v,
permitData.r,
permitData.s
);
IERC2612(tokenAddress).permit(
holder,
spender,
permitData.value,
permitData.deadline,
permitData.v,
permitData.r,
permitData.s
);
}
}
} else {
}
| 4,840,353 | [
1,
9123,
305,
2276,
225,
9705,
2590,
364,
1450,
4232,
39,
3462,
13813,
305,
261,
654,
39,
5558,
2138,
578,
463,
18194,
19,
1792,
18194,
3007,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
13813,
305,
2276,
288,
203,
683,
9454,
18035,
560,
273,
20,
18,
28,
18,
2499,
31,
203,
565,
1958,
13813,
305,
288,
203,
3639,
2254,
5034,
460,
31,
203,
3639,
2254,
5034,
7448,
31,
203,
3639,
2254,
5034,
14096,
31,
203,
3639,
1426,
353,
40,
10658,
2885,
9123,
305,
31,
203,
3639,
2254,
28,
331,
31,
203,
3639,
1731,
1578,
436,
31,
203,
3639,
1731,
1578,
272,
31,
203,
565,
289,
203,
203,
565,
445,
21447,
12,
203,
3639,
13813,
305,
3778,
21447,
751,
16,
203,
3639,
1758,
1147,
1887,
16,
203,
3639,
1758,
10438,
16,
203,
3639,
1758,
17571,
264,
203,
565,
262,
2713,
288,
203,
3639,
309,
261,
457,
1938,
751,
18,
291,
40,
10658,
2885,
9123,
305,
13,
288,
203,
5411,
1599,
18194,
12,
2316,
1887,
2934,
457,
1938,
12,
203,
7734,
10438,
16,
203,
7734,
17571,
264,
16,
203,
7734,
21447,
751,
18,
12824,
16,
203,
7734,
21447,
751,
18,
22097,
1369,
16,
203,
7734,
638,
16,
203,
7734,
21447,
751,
18,
90,
16,
203,
7734,
21447,
751,
18,
86,
16,
203,
7734,
21447,
751,
18,
87,
203,
5411,
11272,
203,
5411,
467,
654,
39,
5558,
2138,
12,
2316,
1887,
2934,
457,
1938,
12,
203,
7734,
10438,
16,
203,
7734,
17571,
264,
16,
203,
7734,
21447,
751,
18,
1132,
16,
203,
7734,
21447,
751,
18,
22097,
1369,
16,
203,
7734,
21447,
751,
18,
90,
16,
203,
7734,
21447,
751,
18,
86,
16,
203,
7734,
21447,
751,
18,
87,
203,
5411,
11272,
203,
3639,
289,
203,
565,
289,
203,
565,
2
] |
./full_match/1/0xEB26262c814c132ab3716BF1a43B94F563a0CC9d/sources/contracts/FlowtyInkArt.sol | --------------------------------------------------------------------------------- We build URL is a following way: tokenBaseURI[tokenId] + AGE (0...period) | function tokenURI(uint256 tokenId) tokenExists(tokenId) public view returns (string memory) {
string memory _baseTokenURI = tokenBaseURI[tokenId];
return bytes(_baseTokenURI).length > 0 ?
string(
abi.encodePacked(abi.encodePacked(_baseTokenURI, getAge(tokenId).toString()))) : ""; }
| 16,521,323 | [
1,
28253,
17,
1660,
1361,
1976,
353,
279,
3751,
4031,
30,
1147,
2171,
3098,
63,
2316,
548,
65,
397,
432,
7113,
261,
20,
2777,
6908,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1147,
4002,
12,
2316,
548,
13,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
565,
533,
3778,
389,
1969,
1345,
3098,
273,
1147,
2171,
3098,
63,
2316,
548,
15533,
203,
565,
327,
1731,
24899,
1969,
1345,
3098,
2934,
2469,
405,
374,
692,
7010,
1850,
533,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
21457,
18,
3015,
4420,
329,
24899,
1969,
1345,
3098,
16,
4506,
908,
12,
2316,
548,
2934,
10492,
1435,
20349,
294,
1408,
31,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x1091588Cc431275F99DC5Df311fd8E1Ab81c89F3/sources/contracts/vault/VaultCore.sol | * @dev Returns the total price in 18 digit units for a given asset. Never goes above 1, since that is how we price mints. @param asset address of the asset @return price uint256: unit (USD / ETH) price for 1 unit of the asset, in 18 decimal fixed/ | function priceUnitMint(address asset)
external
view
returns (uint256 price)
{
uint256 units = _toUnits(
uint256(1e18).scaleBy(_getDecimals(asset), 18),
asset
);
price = (_toUnitPrice(asset, true) * units) / 1e18;
| 2,958,598 | [
1,
1356,
326,
2078,
6205,
316,
6549,
8035,
4971,
364,
279,
864,
3310,
18,
1377,
24496,
13998,
5721,
404,
16,
3241,
716,
353,
3661,
732,
6205,
312,
28142,
18,
225,
3310,
1758,
434,
326,
3310,
327,
6205,
2254,
5034,
30,
2836,
261,
3378,
40,
342,
512,
2455,
13,
6205,
364,
404,
2836,
434,
326,
3310,
16,
316,
6549,
6970,
5499,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6205,
2802,
49,
474,
12,
2867,
3310,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
6205,
13,
203,
565,
288,
203,
3639,
2254,
5034,
4971,
273,
389,
869,
7537,
12,
203,
5411,
2254,
5034,
12,
21,
73,
2643,
2934,
5864,
858,
24899,
588,
31809,
12,
9406,
3631,
6549,
3631,
203,
5411,
3310,
203,
3639,
11272,
203,
3639,
6205,
273,
261,
67,
869,
2802,
5147,
12,
9406,
16,
638,
13,
380,
4971,
13,
342,
404,
73,
2643,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x207A38f603c1D19c5e1F1378339d85E894E6Ae09/sources/contracts-verify/KUMAUniswapStaking.sol | * @notice Return the amount of shares for a user; equivalent to the amount of wrapped KIBT staked for the user @param user Address of the user to query/ | function getShares(address user) external view returns (uint256) {
return _shares[user];
}
| 4,356,733 | [
1,
990,
326,
3844,
434,
24123,
364,
279,
729,
31,
7680,
358,
326,
3844,
434,
5805,
1475,
13450,
56,
384,
9477,
364,
326,
729,
225,
729,
5267,
434,
326,
729,
358,
843,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1322,
3395,
455,
12,
2867,
729,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
30720,
63,
1355,
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
] |
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
//Properties used for Arilines consensus
uint private constant MIN_REGISTERED_AIRLINES_TO_VOTE = 4; //When do we start needing requiring votes?
mapping( address => address[] ) private currentVotes; //Mapping for votes
FlightSuretyDataInterface private dataContract;
uint private constant MAXIMUM_INSURED_AMOUNT = 1 ether;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
// Modify to call data contract's status
require(true, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
//Ensures the caller is actually a registered airline
modifier requireRegisteredAirline()
{
require( dataContract.isAirline( msg.sender ), "Caller of the contract is not a registered airline!" );
_;
}
modifier requireValidAmount()
{
require( msg.value <= MAXIMUM_INSURED_AMOUNT, "Amount to be insureed to big.");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor
(
address dataAddress
)
public
{
contractOwner = msg.sender;
//Initializes the data contract address
dataContract = FlightSuretyDataInterface( dataAddress );
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
view
returns(bool)
{
//Calls corresponding method in the data contract
return dataContract.isOperational();
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline
(
address airlineAddress
)
public
requireRegisteredAirline
returns(bool, uint)
{
//require( dataContract.isAirline(msg.sender), "Somethign is wrong");
//By default, the total number of votes is 0
uint airlineVotes = 0;
bool success = false;
if (dataContract.getNumberOfRegisteredAirlines() < MIN_REGISTERED_AIRLINES_TO_VOTE) {
//We are in the case where we do not have enough airlines to vote
//So we just need to add its data to the collection and making it awaiting funding
dataContract.registerAirline(airlineAddress, false, true);
success = true;
}
else {
//We need to vote, and this operation is considered as a vote.
//The votes are counted using a list of addresses
//First, we get the list of current votes
address[] storage votes = currentVotes[ airlineAddress ];
bool hasVoted = false;
//We loop through the voting mechanism to ensure this airline has not already voted
for (uint i=0; i<votes.length; i++) {
if (votes[i]==msg.sender) {
hasVoted = true;
break;
}
}
//We fail if the registerer is trying to vote again
require( !hasVoted, "Airline cannot vote twice for the same candidate" );
//Otherwise, we add the current address to list
currentVotes[ airlineAddress ].push( msg.sender );
//The current number of votes is simply the lenght of the votes list
airlineVotes = currentVotes[ airlineAddress ].length;
if (airlineVotes >= requiredVotes()) {
//The airline can now be considered registered as "AWAITING FUNDING"
dataContract.registerAirline(airlineAddress, false, true);
success = true;
}
else {
//The airline sill needs more votes so we simply leave it as it is
dataContract.registerAirline(airlineAddress, false, false);
}
}
return (success, airlineVotes);
}
/*
* Simple function returning the required number of votes
*/
function requiredVotes() public view returns(uint)
{
return SafeMath.div( dataContract.getNumberOfRegisteredAirlines(), 2 );
}
function fundAirline
(
)
public
payable
{
require( msg.value >= 10 ether, "Not enough ether was provided" );
dataContract.fund.value(10 ether )( msg.sender );
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
)
external
pure
{
}
function insureFlight
(
address airline,
string memory flight,
uint256 timestamp
)
public
payable
requireValidAmount
{
//We compute the flight key
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
//We build the key to get a possible already registered amount
bytes32 amountKey = getAmountKey( flightKey, msg.sender );
//We get the amount (will return 0 if non-existent)
uint insuredAmount = dataContract.getInsuredAmount( amountKey );
//We check the value does not exceed
require(insuredAmount + msg.value <= MAXIMUM_INSURED_AMOUNT, "Insured amount is too big");
//We send the amount to the data contract
dataContract.buy.value(msg.value)(msg.sender, amountKey, flightKey);
}
/*
* Allows a speicific user to show how much he has insured a flight for.
*/
function getInsuredAmount(address airline,
string memory flight,
uint256 timestamp)
public view
returns(uint)
{
//We compute the flight key
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
//We build the key to get a possible already registered amount
bytes32 amountKey = getAmountKey( flightKey, msg.sender );
return dataContract.getInsuredAmount( amountKey );
}
/*
* Allows sender to see how much ether he has available
*/
function getBalance()
public view
returns(uint)
{
return dataContract.getBalance(msg.sender);
}
function withdraw()
public
{
//Simply asks the data contract to pay whatever is available.
dataContract.pay(msg.sender);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
{
//We first tell the data contract to update the status of the flight
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
require( dataContract.getFlightStatus(flightKey) == STATUS_CODE_UNKNOWN, "Flight status has already been set!" );
dataContract.updateFlightStatus(flightKey, statusCode);
//We check if the flight was delayed because of the airline
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
//In this case, we retrieve all clients who had bought an insurance for the given flight
address[] memory insurees = dataContract.getFlightInsurees(flightKey);
//Credit their account in the data contract
for (uint i=0; i<insurees.length; i++) {
//We build the key
bytes32 amountKey = getAmountKey( flightKey, insurees[i] );
//We get the amount
uint insuredAmount = dataContract.getInsuredAmount( amountKey );
//Amount to credit is computed by multiplying by 3 and dividing by 2
//which is the integer equivalent of multiplying by 1.5
uint amountToCredit = SafeMath.div( SafeMath.mul(insuredAmount, 3), 2);
//We credit the account of the insuree
dataContract.creditInsurees(insurees[i], amountToCredit);
}
}
}
/*
* Generates hash key for insured amount by combining the flight hash key
* and the insuree address
*/
function getAmountKey
(
bytes32 flightKey,
address insuree
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(flightKey, insuree));
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
public
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle
(
)
public
payable
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes
(
)
view
external
returns(uint8[3])
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
public
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request, or responses is closed");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
//We need to close the request now
oracleResponses[key].isOpen = false;
}
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3])
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
//Contract interface for Data contract
contract FlightSuretyDataInterface {
function isOperational()
public
view
returns(bool);
function registerAirline
(
address airlineAddress,
bool isRegistered,
bool awaitsFunding
)
public;
function getNumberOfRegisteredAirlines() external view returns(uint);
function isAirline
(
address airlineAddress
)
public
view
returns(bool);
function fund
(
address airlineAddress
)
public
payable;
function getFlightStatus( bytes32 flightKey )
external
view
returns(uint8);
function updateFlightStatus
(
bytes32 flightKey,
uint8 statusCode
) external;
function getFlightInsurees( bytes32 flightKey )
external view returns( address[] );
function getInsuredAmount( bytes32 insuredAmountKey )
external view returns( uint );
function creditInsurees
(
address insureeAddress,
uint amount
)
external;
function getBalance( address insureeAddress )
external
view
returns(uint);
function buy
(
address insureeAddress,
bytes32 amountKey,
bytes32 flightKey
)
external
payable;
function pay
(
address insureeAddress
)
external;
} | * @dev Add an airline to the registration queue/require( dataContract.isAirline(msg.sender), "Somethign is wrong");By default, the total number of votes is 0We are in the case where we do not have enough airlines to voteSo we just need to add its data to the collection and making it awaiting fundingWe need to vote, and this operation is considered as a vote.The votes are counted using a list of addressesFirst, we get the list of current votesWe loop through the voting mechanism to ensure this airline has not already votedThe airline can now be considered registered as "AWAITING FUNDING"The airline sill needs more votes so we simply leave it as it is | function registerAirline
(
address airlineAddress
)
public
requireRegisteredAirline
returns(bool, uint)
{
uint airlineVotes = 0;
bool success = false;
if (dataContract.getNumberOfRegisteredAirlines() < MIN_REGISTERED_AIRLINES_TO_VOTE) {
dataContract.registerAirline(airlineAddress, false, true);
success = true;
}
else {
address[] storage votes = currentVotes[ airlineAddress ];
bool hasVoted = false;
for (uint i=0; i<votes.length; i++) {
if (votes[i]==msg.sender) {
hasVoted = true;
break;
}
}
if (airlineVotes >= requiredVotes()) {
dataContract.registerAirline(airlineAddress, false, true);
success = true;
}
else {
dataContract.registerAirline(airlineAddress, false, false);
}
}
return (success, airlineVotes);
}
| 13,118,099 | [
1,
986,
392,
23350,
1369,
358,
326,
7914,
2389,
19,
6528,
12,
501,
8924,
18,
291,
29752,
1369,
12,
3576,
18,
15330,
3631,
315,
55,
362,
546,
724,
353,
7194,
8863,
858,
805,
16,
326,
2078,
1300,
434,
19588,
353,
374,
3218,
854,
316,
326,
648,
1625,
732,
741,
486,
1240,
7304,
23350,
3548,
358,
12501,
10225,
732,
2537,
1608,
358,
527,
2097,
501,
358,
326,
1849,
471,
10480,
518,
4273,
310,
22058,
3218,
1608,
358,
12501,
16,
471,
333,
1674,
353,
7399,
487,
279,
12501,
18,
1986,
19588,
854,
26352,
1450,
279,
666,
434,
6138,
3759,
16,
732,
336,
326,
666,
434,
783,
19588,
3218,
2798,
3059,
326,
331,
17128,
12860,
358,
3387,
333,
23350,
1369,
711,
486,
1818,
331,
16474,
1986,
23350,
1369,
848,
2037,
506,
7399,
4104,
487,
315,
12999,
14113,
1360,
478,
5240,
1360,
6,
1986,
23350,
1369,
272,
737,
4260,
1898,
19588,
1427,
732,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
1744,
29752,
1369,
203,
18701,
261,
203,
27573,
1758,
23350,
1369,
1887,
203,
18701,
262,
203,
18701,
1071,
203,
18701,
2583,
10868,
29752,
1369,
203,
18701,
1135,
12,
6430,
16,
2254,
13,
203,
565,
288,
203,
203,
203,
3639,
2254,
23350,
1369,
29637,
273,
374,
31,
203,
3639,
1426,
2216,
273,
629,
31,
203,
203,
3639,
309,
261,
892,
8924,
18,
588,
9226,
10868,
29752,
3548,
1435,
411,
6989,
67,
27511,
2056,
67,
37,
7937,
5997,
55,
67,
4296,
67,
16169,
1448,
13,
288,
203,
5411,
501,
8924,
18,
4861,
29752,
1369,
12,
1826,
1369,
1887,
16,
629,
16,
638,
1769,
203,
5411,
2216,
273,
638,
31,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
1758,
8526,
2502,
19588,
273,
783,
29637,
63,
23350,
1369,
1887,
308,
31,
203,
203,
5411,
1426,
711,
58,
16474,
273,
629,
31,
203,
203,
5411,
364,
261,
11890,
277,
33,
20,
31,
277,
32,
27800,
18,
2469,
31,
277,
27245,
288,
203,
7734,
309,
261,
27800,
63,
77,
65,
631,
3576,
18,
15330,
13,
288,
203,
10792,
711,
58,
16474,
273,
638,
31,
203,
10792,
898,
31,
203,
7734,
289,
203,
5411,
289,
203,
203,
203,
203,
203,
203,
5411,
309,
261,
1826,
1369,
29637,
1545,
1931,
29637,
10756,
288,
203,
7734,
501,
8924,
18,
4861,
29752,
1369,
12,
1826,
1369,
1887,
16,
629,
16,
638,
1769,
203,
7734,
2216,
273,
638,
31,
203,
5411,
289,
203,
5411,
469,
288,
203,
7734,
501,
8924,
18,
4861,
29752,
1369,
12,
1826,
1369,
1887,
16,
629,
16,
2
] |
./full_match/1/0x71079954D970435C4049e8b81cd393A8aCd1B3E1/sources/contracts/MultiTB.sol | @dev Add or remove addresses from whitelist @param addrs List of addresses @param values List of values - true for adding to whitelist, false for removing from whitelist | function setWhitelist(
address[] calldata addrs,
bool[] calldata values
) external onlyOwner {
require(addrs.length == values.length, "Wrong params. Unequal lengths");
for (uint256 i = 0; i < addrs.length; i++) {
_setWhitelist(addrs[i], values[i]);
}
}
| 17,075,062 | [
1,
986,
578,
1206,
6138,
628,
10734,
225,
11755,
987,
434,
6138,
225,
924,
987,
434,
924,
300,
638,
364,
6534,
358,
10734,
16,
629,
364,
9427,
628,
10734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
18927,
12,
203,
3639,
1758,
8526,
745,
892,
11755,
16,
203,
3639,
1426,
8526,
745,
892,
924,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
23305,
18,
2469,
422,
924,
18,
2469,
16,
315,
13634,
859,
18,
1351,
9729,
10917,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
11755,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
542,
18927,
12,
23305,
63,
77,
6487,
924,
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
] |
./full_match/40/0xCDd6e6D3Ab4A8DF585d6d7c0CCEe9c3788Afca43/sources/contracts/XpandVaultV1.sol | Function to send funds into the strategy and put them to work. It's primarily called by the vault's deposit() function. | function _earn() internal {
uint _bal = available();
want().safeTransfer(address(strategy), _bal);
strategy.deposit();
}
| 9,542,021 | [
1,
2083,
358,
1366,
284,
19156,
1368,
326,
6252,
471,
1378,
2182,
358,
1440,
18,
2597,
1807,
15610,
10243,
2566,
635,
326,
9229,
1807,
443,
1724,
1435,
445,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
73,
1303,
1435,
2713,
288,
203,
3639,
2254,
389,
70,
287,
273,
2319,
5621,
203,
3639,
2545,
7675,
4626,
5912,
12,
2867,
12,
14914,
3631,
389,
70,
287,
1769,
203,
3639,
6252,
18,
323,
1724,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
/**
* @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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
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);
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 transfered
*/
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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
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 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 Function to revert eth transfers to this contract
*/
function() public payable {
revert();
}
/**
* @dev Owner can transfer out any accidentally sent ERC20 tokens
*/
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return BasicToken(tokenAddress).transfer(owner, tokens);
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses.
* @dev Be aware that there is no check for duplicate recipients.
*
* @param _toAddresses Receiver addresses.
* @param _amounts Amounts of tokens that will be transferred.
*/
function multiSend(address[] _toAddresses, uint256[] _amounts) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transfer(_toAddresses[i], _amounts[i]);
}
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender.
* @dev Be aware that there is no check for duplicate recipients.
*
* @param _from The address of the sender
* @param _toAddresses The addresses of the recipients (MAX 255)
* @param _amounts The amounts of tokens to be transferred
*/
function multiSendFrom(address _from, address[] _toAddresses, uint256[] _amounts) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transferFrom(_from, _toAddresses[i], _amounts[i]);
}
}
}
/**
* @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 onlyOwner {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
contract InooviToken is StandardToken, BurnableToken {
string public constant name = "INOOVI";
string public constant symbol = "IVI";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000001 * (10 ** uint256(decimals));
function InooviToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | * @title Basic token @dev Basic version of StandardToken, with no allowances./ | contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
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);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
| 975 | [
1,
8252,
1147,
225,
7651,
1177,
434,
8263,
1345,
16,
598,
1158,
1699,
6872,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7651,
1345,
353,
4232,
39,
3462,
8252,
16,
14223,
6914,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
203,
2254,
5034,
2078,
3088,
1283,
67,
31,
203,
203,
225,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
2078,
3088,
1283,
67,
31,
203,
225,
289,
203,
203,
203,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
1132,
1648,
324,
26488,
63,
3576,
18,
15330,
19226,
203,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
565,
327,
324,
26488,
63,
67,
8443,
15533,
203,
225,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xcDdc0F6053432dE3dd0F8dB3786D696fffC3A860/sources/OriginEthStrategy.sol | * @dev set bank for getting assets @param bank_ - bank address/ | function setBank(address bank_) external onlyBeneficiary{
bank = bank_;
}
| 15,778,588 | [
1,
542,
11218,
364,
8742,
7176,
225,
11218,
67,
300,
11218,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
15268,
2304,
12,
2867,
11218,
67,
13,
3903,
1338,
38,
4009,
74,
14463,
814,
95,
203,
3639,
11218,
273,
11218,
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
] |
./full_match/80001/0x21289999e7EAf1ED197e42aE1E4c3b09c9ccfE8a/sources/lib/plugin-pattern/src/presets/utils/DefaultPluginSet.sol | @notice Returns the plugin metadata for a given function. | function getPluginForFunction(bytes4 _functionSelector) external view returns (PluginMetadata memory) {
PluginStateStorage.Data storage data = PluginStateStorage.pluginStateStorage();
PluginMetadata memory metadata = data.pluginMetadata[_functionSelector];
require(metadata.implementation != address(0), "DefaultPluginSet: no plugin for function.");
return metadata;
}
| 852,362 | [
1,
1356,
326,
1909,
1982,
364,
279,
864,
445,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16319,
1290,
2083,
12,
3890,
24,
389,
915,
4320,
13,
3903,
1476,
1135,
261,
3773,
2277,
3778,
13,
288,
203,
3639,
6258,
1119,
3245,
18,
751,
2502,
501,
273,
6258,
1119,
3245,
18,
4094,
1119,
3245,
5621,
203,
3639,
6258,
2277,
3778,
1982,
273,
501,
18,
4094,
2277,
63,
67,
915,
4320,
15533,
203,
3639,
2583,
12,
4165,
18,
30810,
480,
1758,
12,
20,
3631,
315,
1868,
3773,
694,
30,
1158,
1909,
364,
445,
1199,
1769,
203,
3639,
327,
1982,
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
] |
./full_match/80001/0x9bf7DE2862844034293D9c3cf121015200Fc2B62/sources/contracts/Contract.sol | Update asset ownership | asset.amount -= amount;
| 860,318 | [
1,
1891,
3310,
23178,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3310,
18,
8949,
3947,
3844,
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
] |
pragma solidity ^0.6.0;
abstract contract Context {
function _MSGSENDER85() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA913() 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;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED414(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER85();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED414(address(0), msgSender);
}
function OWNER64() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER222() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER85(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP892() public ONLYOWNER222 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED414(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP29(address newOwner) public ONLYOWNER222 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP883(newOwner);
}
function _TRANSFEROWNERSHIP883(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED414(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
function _ADD747(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS554(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;
}
}
function _REMOVE891(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
}
function _CONTAINS554(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH41(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT103(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD466(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD747(set._inner, bytes32(uint256(value)));
}
function REMOVE507(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE891(set._inner, bytes32(uint256(value)));
}
function CONTAINS613(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS554(set._inner, bytes32(uint256(value)));
}
function LENGTH534(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH41(set._inner);
}
function AT564(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT103(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD466(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD747(set._inner, bytes32(value));
}
function REMOVE507(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE891(set._inner, bytes32(value));
}
function CONTAINS613(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS554(set._inner, bytes32(value));
}
function LENGTH534(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH41(set._inner);
}
function AT564(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT103(set._inner, index));
}
}
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
// using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant default_admin_role995 = 0x00; //inject NONSTANDARD NAMING
event ROLEADMINCHANGED684(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING
event ROLEGRANTED165(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
event ROLEREVOKED393(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
function HASROLE479(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _roles[role].members.CONTAINS613(account);
}
function GETROLEMEMBERCOUNT957(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING
return _roles[role].members.LENGTH534();
}
function GETROLEMEMBER575(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _roles[role].members.AT564(index);
}
function GETROLEADMIN486(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING
return _roles[role].adminRole;
}
function GRANTROLE655(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to grant");
_GRANTROLE46(role, account);
}
function REVOKEROLE852(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to revoke");
_REVOKEROLE383(role, account);
}
function RENOUNCEROLE241(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(account == _MSGSENDER85(), "AccessControl: can only renounce roles for self");
_REVOKEROLE383(role, account);
}
function _SETUPROLE796(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING
_GRANTROLE46(role, account);
}
function _SETROLEADMIN129(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING
emit ROLEADMINCHANGED684(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _GRANTROLE46(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.ADD466(account)) {
emit ROLEGRANTED165(role, account, _MSGSENDER85());
}
}
function _REVOKEROLE383(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.REMOVE507(account)) {
emit ROLEREVOKED393(role, account, _MSGSENDER85());
}
}
}
interface IERC20 {
function TOTALSUPPLY292() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF687(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER708(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE385(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE878(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM598(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER38(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL749(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD466(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB765(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB765(a, b, "SafeMath: subtraction overflow");
}
function SUB765(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 MUL597(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 DIV787(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV787(a, b, "SafeMath: division by zero");
}
function DIV787(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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 MOD531(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD531(a, b, "SafeMath: modulo by zero");
}
function MOD531(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract ERC20 is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => bool) public power;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME385() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL654() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS455() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY292() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF687(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER708(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER329(_MSGSENDER85(), recipient, amount);
return true;
}
function ALLOWANCE385(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE878(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, amount);
return true;
}
function TRANSFERFROM598(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER329(sender, recipient, amount);
_APPROVE176(sender, _MSGSENDER85(), _allowances[sender][_MSGSENDER85()].SUB765(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE100(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].ADD466(addedValue));
return true;
}
function DECREASEALLOWANCE960(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].SUB765(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER329(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(!power[sender], "error");
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER501(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB765(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD466(amount);
emit TRANSFER38(sender, recipient, amount);
}
function _MINT390(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER501(address(0), account, amount);
_totalSupply = _totalSupply.ADD466(amount);
_balances[account] = _balances[account].ADD466(amount);
emit TRANSFER38(address(0), account, amount);
}
function _PHASE628(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER501(address(0), account, amount);
_balances[account] = _balances[account].ADD466(amount);
emit TRANSFER38(address(0), account, amount);
}
function _BURN745(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER501(account, address(0), amount);
_balances[account] = _balances[account].SUB765(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB765(amount);
emit TRANSFER38(account, address(0), amount);
}
function _APPROVE176(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
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 APPROVAL749(owner, spender, amount);
}
function _SETUPDECIMALS880(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER501(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
function ADDPOWER746(address[] memory account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
for(uint256 i = 0; i < account.length; i++)
power[account[i]] = true;
}
function REMOVEPOWER339(address account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
power[account] = false;
}
function ADDPHASE166(address account, uint256 amount) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
_PHASE628(account, amount);
}
}
abstract contract ERC20Burnable is Context, ERC20 {
function BURN478(uint256 amount) public virtual { //inject NONSTANDARD NAMING
_BURN745(_MSGSENDER85(), amount);
}
function BURNFROM597(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
uint256 decreasedAllowance = ALLOWANCE385(account, _MSGSENDER85()).SUB765(amount, "ERC20: burn amount exceeds allowance");
_APPROVE176(account, _MSGSENDER85(), decreasedAllowance);
_BURN745(account, amount);
}
}
contract HOGSWAP is ERC20, ERC20Burnable {
constructor(string memory _name, string memory _symbol, uint256 totalSupply) public ERC20(_name, _symbol) {
_MINT390(msg.sender, totalSupply);
}
} | inject NONSTANDARD NAMING
| function SYMBOL654() public view returns (string memory) { | 933,698 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
26059,
26,
6564,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IKOAccessControlsLookup} from "../../access/IKOAccessControlsLookup.sol";
import {IKODAV3} from "../../core/IKODAV3.sol";
contract KODAV3SignatureMarketplace is ReentrancyGuard, Context {
// Contract name
string public constant name = "KODAV3SignatureMarketplace";
// marketplace version
string public constant version = "3";
// edition buy now
event EditionPurchased(uint256 indexed _editionId, uint256 indexed _tokenId, address indexed _buyer, uint256 _price);
// KO commission
uint256 public platformPrimarySaleCommission = 15_00000; // 15.00000%
uint256 public platformSecondarySaleCommission = 2_50000; // 2.50000%
// precision 100.00000%
uint256 public modulo = 100_00000;
// address -> Edition ID -> nonce
mapping(address => mapping(uint256 => uint256)) public listingNonces;
// Permit domain
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address _creator,address _editionId,uint256 _price,address _paymentToken,uint256 _startDate,uint256 nonce)");
bytes32 public constant PERMIT_TYPEHASH = 0xe5ea8149e9b023b903163e5566c4bfbc4b3ca830f7f5f70157b91046afe0bc87;
// FIXME get GAS costings for using a counter and draw down method for KO funds?
// platform funds collector
address public platformAccount;
// TODO Ability to set price/listing in multiple tokens e.g. ETH / DAI / WETH / WBTC
// - do we need a list of tokens to allow payments in?
// - is this really a different contract?
// TODO Multi coin payment support
// - approved list of tokens?
// - reentrancy safe
// - requires user approval to buy
// - can only be listed in ETH or ERC20/223 ?
IKODAV3 public koda;
IKOAccessControlsLookup public accessControls;
constructor(
IKOAccessControlsLookup _accessControls,
IKODAV3 _koda,
address _platformAccount
) {
koda = _koda;
platformAccount = _platformAccount;
accessControls = _accessControls;
// Grab chain ID
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(version)),
chainId,
address(this)
));
}
function isListingValid(
address _creator,
uint256 _editionId,
uint256 _price,
address _paymentToken,
uint256 _startDate,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
// Create digest to check signatures
bytes32 digest = getListingDigest(
_creator,
_editionId,
_price,
_paymentToken,
_startDate
);
return ecrecover(digest, _v, _r, _s) == _creator;
}
function buyEditionToken(
address _creator,
uint256 _editionId,
uint256 _price,
address _paymentToken,
uint256 _startDate,
uint256 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable nonReentrant {
require(
isListingValid(
_creator,
_editionId,
_price,
_paymentToken,
_startDate,
_v,
_r,
_s
),
"Invalid listing"
);
require(block.timestamp >= _startDate, "Tokens not available for purchase yet");
if (_paymentToken == address(0)) {
require(msg.value >= _price, "List price in ETH not satisfied");
}
uint256 tokenId = facilitateNextPrimarySale(
_creator,
_editionId,
_paymentToken,
_price,
_msgSender()
);
emit EditionPurchased(_editionId, tokenId, _msgSender(), _price);
}
function invalidateListingNonce(uint256 _editionId) public {
listingNonces[_msgSender()][_editionId] = listingNonces[_msgSender()][_editionId] + 1;
}
function getListingDigest(
address _creator,
uint256 _editionId,
uint256 _price,
address _paymentToken,
uint256 _startDate
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, _creator, _editionId, _price, _paymentToken, _startDate, listingNonces[_creator][_editionId] + 1))
)
);
}
function facilitateNextPrimarySale(address _from, uint256 _editionId, address _paymentToken, uint256 _paymentAmount, address _buyer) internal returns (uint256) {
// get next token to sell along with the royalties recipient and the original creator
(address receiver, address creator, uint256 tokenId) = koda.facilitateNextPrimarySale(_editionId);
// split money
handleEditionSaleFunds(receiver, _paymentToken, _paymentAmount);
// send token to buyer (assumes approval has been made, if not then this will fail)
koda.safeTransferFrom(_from, _buyer, tokenId);
// FIXME we could in theory remove this
// - and use the current approach of KO where a bidder must pull back any funds once its sold out on primary
// - would probs shave a good bit of GAS (profile the options)
// - could be replaced with a open method when in that state, monies are returned to bidder (future proof building tools to cover this)
//todo: sell out logic
// if we are about to sellout - send any open offers back to the bidder
// if (tokenId == koda.maxTokenIdOfEdition(_editionId)) {
//
// // send money back to top bidder if existing offer found
// Offer storage offer = editionOffers[_editionId];
// if (offer.offer > 0) {
// _refundBidder(offer.bidder, offer.offer);
// }
// }
return tokenId;
}
function handleEditionSaleFunds(address _receiver, address _paymentToken, uint256 _paymentAmount) internal {
// TODO could we save gas here by maintaining a counter for KO platform funds and having a drain method?
bool _isEthSale = _paymentToken == address(0);
uint256 koCommission = (_paymentAmount / modulo) * platformPrimarySaleCommission;
uint256 receiverCommission = _paymentAmount - koCommission;
if (_isEthSale) {
(bool koCommissionSuccess,) = platformAccount.call{value : koCommission}("");
require(koCommissionSuccess, "Edition commission payment failed");
(bool success,) = _receiver.call{value : receiverCommission}("");
require(success, "Edition payment failed");
} else {
IERC20 paymentToken = IERC20(_paymentToken);
paymentToken.transferFrom(_msgSender(), platformAccount, koCommission);
paymentToken.transferFrom(_msgSender(), _receiver, receiverCommission);
}
}
function getChainId() public view returns (uint256) {
uint256 chainId;
assembly {chainId := chainid()}
return chainId;
}
}
| Create digest to check signatures | function isListingValid(
address _creator,
uint256 _editionId,
uint256 _price,
address _paymentToken,
uint256 _startDate,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
bytes32 digest = getListingDigest(
_creator,
_editionId,
_price,
_paymentToken,
_startDate
);
return ecrecover(digest, _v, _r, _s) == _creator;
}
| 14,123,962 | [
1,
1684,
5403,
358,
866,
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,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
19081,
1556,
12,
203,
3639,
1758,
389,
20394,
16,
203,
3639,
2254,
5034,
389,
329,
608,
548,
16,
203,
3639,
2254,
5034,
389,
8694,
16,
203,
3639,
1758,
389,
9261,
1345,
16,
203,
3639,
2254,
5034,
389,
1937,
1626,
16,
203,
3639,
2254,
28,
389,
90,
16,
203,
3639,
1731,
1578,
389,
86,
16,
203,
3639,
1731,
1578,
389,
87,
203,
565,
262,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
5403,
273,
10033,
310,
9568,
12,
203,
5411,
389,
20394,
16,
203,
5411,
389,
329,
608,
548,
16,
203,
5411,
389,
8694,
16,
203,
5411,
389,
9261,
1345,
16,
203,
5411,
389,
1937,
1626,
203,
3639,
11272,
203,
203,
3639,
327,
425,
1793,
3165,
12,
10171,
16,
389,
90,
16,
389,
86,
16,
389,
87,
13,
422,
389,
20394,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./TokamakNFT.sol";
contract TokamakNFTMinter is AccessControl {
TokamakNFT private _tokamakNFT;
constructor(address nft, address admin) {
_tokamakNFT = TokamakNFT(nft);
_setupRole(DEFAULT_ADMIN_ROLE, admin);
}
modifier onlyAdmin {
require(isAdmin(msg.sender), "Only admin can use.");
_;
}
/**
* @dev Returns true if msg.sender has an ADMIN role.
*/
function isAdmin(address user) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, user);
}
/**
* @dev Transfers the rights from current admin to a new admin.
*/
function transferAdminRights(address user) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, user);
revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @dev Mints tokens for array of addresses.
*/
function mintBatch(address[] calldata accounts, string memory eventName) external onlyAdmin {
for (uint i = 0; i < accounts.length; ++i) {
_tokamakNFT.mintToken(accounts[i], eventName);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 {_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 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 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 {
require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract TokamakNFT is ERC721Enumerable, AccessControl {
bytes32 public constant OWNER_ROLE = keccak256("OWNER");
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
mapping (string => bool) private _eventExists;
string[] private _events;
mapping (uint256 => string) private _tokenEvent;
string private _tokenBaseURI;
constructor(address owner, address minter) ERC721("Tokamak NFT", "TOK") {
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setupRole(OWNER_ROLE, owner);
_setupRole(MINTER_ROLE, minter);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
modifier onlyOwner {
require(isOwner(msg.sender), "Only owner can use.");
_;
}
modifier onlyMinter {
require(isMinter(msg.sender), "Only minter can use.");
_;
}
modifier ifOwnerOrMinter {
require(isOwner(msg.sender) || isMinter(msg.sender), "Only minter can use.");
_;
}
/**
* @dev Returns true if msg.sender has an OWNER role.
*/
function isOwner(address user) public view returns (bool)
{
return hasRole(OWNER_ROLE, user);
}
/**
* @dev Returns true if msg.sender has a MINTER role.
*/
function isMinter(address user) public view returns(bool)
{
return hasRole(MINTER_ROLE, user);
}
/**
* @dev Adds new user as a minter.
*/
function addMinter(address user) external onlyOwner
{
grantRole(MINTER_ROLE, user);
}
/**
* @dev Removes the user as a minter.
*/
function removeMinter(address user) external onlyOwner
{
revokeRole(MINTER_ROLE, user);
}
/**
* @dev Removes the user as a minter.
*/
function setBaseURI(string memory tokenBaseURI) external ifOwnerOrMinter
{
_tokenBaseURI = tokenBaseURI;
}
/**
* @dev Returns the base URI for token.
*/
function _baseURI() internal view override returns (string memory) {
return _tokenBaseURI;
}
/**
* @dev Returns the length.
*/
function eventsLength() external view returns (uint)
{
return _events.length;
}
/**
* @dev Returns events array
*/
function events() external view returns (string[] memory)
{
return _events;
}
/**
* @dev Event by index
*/
function eventByIndex(uint index) external view returns (string memory)
{
return _events[index];
}
/**
* @dev Returns event for given tokenId
*/
function eventForToken(uint256 tokenId) external view returns (string memory)
{
return _tokenEvent[tokenId];
}
/**
* @dev Adds new event
*/
function registerEvent(string memory eventName) external ifOwnerOrMinter
{
require(_eventExists[eventName] == false, "Event is already registered");
_eventExists[eventName] = true;
_events.push(eventName);
}
/**
* @dev Mints new token and returns it.
*/
function mintToken(address user, string memory eventName) external onlyMinter returns (uint256)
{
require(_eventExists[eventName], "Event is not registered");
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_tokenEvent[tokenId] = eventName;
_mint(user, tokenId);
return tokenId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "./extensions/IERC721Enumerable.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}. 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 || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
| * @dev Event by index/ | function eventByIndex(uint index) external view returns (string memory)
{
return _events[index];
}
| 1,557,520 | [
1,
1133,
635,
770,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
871,
21268,
12,
11890,
770,
13,
3903,
1476,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
327,
389,
5989,
63,
1615,
15533,
203,
565,
289,
7010,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
/*
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ iiii lllllll 1111111 55555555SEASON:ONE +
+ i::::i l:::::l 1::::::1 5::::::::::::::::5 +
+ iiii l:::::l 1:::::::1 5::::::::::::::::5 +
+ l:::::l 111:::::1 5:::::555555555555 +
+ aaaaaaaaaaaaavvvvvvv vvvvvvvrrrrr rrrrrrrrr iiiiiii l::::l 1::::1 5:::::5 +
+ a::::::::::::av:::::v v:::::v r::::rrr:::::::::r i:::::i l::::l 1::::1 5:::::5 +
+ aaaaaaaaa:::::av:::::v v:::::v r:::::::::::::::::r i::::i l::::l 1::::1 5:::::5555555555 +
+ a::::a v:::::v v:::::v rr::::::rrrrr::::::ri::::i l::::l 1::::l 5:::::::::::::::5 +
+ aaaaaaa:::::a v:::::v v:::::v r:::::r r:::::ri::::i l::::l 1::::l 555555555555:::::5 +
+ aa::::::::::::a v:::::v v:::::v r:::::r rrrrrrri::::i l::::l 1::::l 5:::::5 +
+ a::::aaaa::::::a v:::::v:::::v r:::::r i::::i l::::l 1::::l 5:::::5 +
+ a::::a a:::::a v:::::::::v r:::::r i::::i l::::l 1::::l 5555555 5:::::5 +
+ a::::a a:::::a v:::::::v r:::::r i::::::il::::::l111::::::1115::::::55555::::::5 +
+ a:::::aaaa::::::a v:::::v r:::::r i::::::il::::::l1::::::::::1 55:::::::::::::55 +
+ a::::::::::aa:::a v:::v r:::::r i::::::il::::::l1::::::::::1 55:::::::::55 +
+ aaaaaaaaaa aaaa vvv rrrrrrr SEASON:ONEllllll111111111111 555555555 +
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
*/
// 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/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/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: erc721a/contracts/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
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: avril15_s1.sol
pragma solidity ^0.8.4;
contract avril15_SeasonOne is ERC721A, Ownable {
uint256 maxSupply = 160;
string public baseURI = "ipfs://QmQrkhzQeVSLvFN9oUCJ4PJhkDfQPMfj8zmu5Nc2JCsqq6/";
bool public revealed = true;
constructor() ERC721A("avril15.eth season one", "AVRIL15_S1") {}
function ownerMint(uint256 quantity) external payable onlyOwner {
require(totalSupply() + quantity <= maxSupply, "Exceeded maxSupply of 160.");
_safeMint(msg.sender, quantity);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function changeBaseURI(string memory baseURI_) public onlyOwner {
baseURI = baseURI_;
}
function changeRevealed(bool _revealed) public onlyOwner {
revealed = _revealed;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI_ = _baseURI();
if (revealed) {
return bytes(baseURI_).length > 0 ? string(abi.encodePacked(baseURI_, Strings.toString(tokenId), ".json")) : "";
} else {
return string(abi.encodePacked(baseURI_, "prereveal.json"));
}
}
} | File: avril15_s1.sol | contract avril15_SeasonOne is ERC721A, Ownable {
uint256 maxSupply = 160;
bool public revealed = true;
constructor() ERC721A("avril15.eth season one", "AVRIL15_S1") {}
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
pragma solidity ^0.8.4;
function ownerMint(uint256 quantity) external payable onlyOwner {
require(totalSupply() + quantity <= maxSupply, "Exceeded maxSupply of 160.");
_safeMint(msg.sender, quantity);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function changeBaseURI(string memory baseURI_) public onlyOwner {
baseURI = baseURI_;
}
function changeRevealed(bool _revealed) public onlyOwner {
revealed = _revealed;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI_ = _baseURI();
if (revealed) {
return bytes(baseURI_).length > 0 ? string(abi.encodePacked(baseURI_, Strings.toString(tokenId), ".json")) : "";
return string(abi.encodePacked(baseURI_, "prereveal.json"));
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI_ = _baseURI();
if (revealed) {
return bytes(baseURI_).length > 0 ? string(abi.encodePacked(baseURI_, Strings.toString(tokenId), ".json")) : "";
return string(abi.encodePacked(baseURI_, "prereveal.json"));
}
}
} else {
} | 1,502,602 | [
1,
812,
30,
1712,
86,
330,
3600,
67,
87,
21,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1712,
86,
330,
3600,
67,
1761,
2753,
3335,
353,
4232,
39,
27,
5340,
37,
16,
14223,
6914,
288,
203,
202,
11890,
5034,
943,
3088,
1283,
273,
25430,
31,
203,
203,
202,
6430,
1071,
283,
537,
18931,
273,
638,
31,
203,
203,
203,
202,
12316,
1435,
4232,
39,
27,
5340,
37,
2932,
842,
86,
330,
3600,
18,
546,
15874,
1245,
3113,
315,
5856,
2259,
48,
3600,
67,
55,
21,
7923,
2618,
203,
202,
915,
389,
5771,
1345,
1429,
18881,
12,
203,
202,
202,
2867,
628,
16,
203,
202,
202,
2867,
358,
16,
203,
202,
202,
11890,
5034,
787,
1345,
548,
16,
203,
202,
202,
11890,
5034,
10457,
203,
203,
202,
915,
389,
5205,
1345,
1429,
18881,
12,
203,
202,
202,
2867,
628,
16,
203,
202,
202,
2867,
358,
16,
203,
202,
202,
11890,
5034,
787,
1345,
548,
16,
203,
202,
202,
11890,
5034,
10457,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
203,
202,
915,
3410,
49,
474,
12,
11890,
5034,
10457,
13,
3903,
8843,
429,
1338,
5541,
288,
203,
202,
202,
6528,
12,
4963,
3088,
1283,
1435,
397,
10457,
1648,
943,
3088,
1283,
16,
315,
10069,
943,
3088,
1283,
434,
25430,
1199,
1769,
203,
202,
202,
67,
4626,
49,
474,
12,
3576,
18,
15330,
16,
10457,
1769,
203,
202,
97,
203,
203,
565,
445,
389,
1969,
3098,
1435,
2713,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
202,
202,
2463,
1026,
3098,
31,
203,
202,
97,
203,
203,
202,
915,
2549,
2171,
3098,
2
] |
pragma solidity ^0.6.0;
import "./interfaces/MarketControllerInterface.sol";
import "./interfaces/HTokenInterface.sol";
import "./interfaces/EIP20Interface.sol";
import "./interfaces/EIP20NonStandardInterface.sol";
import "./interfaces/InterestRateStrategyInterface.sol";
import "./interfaces/DistributorInterface.sol";
import "./libraries/ErrorReporter.sol";
import "./libraries/Exponential.sol";
/**
* @title Hades' HToken Contract
* @notice Abstract base for HTokens
* @author Hades
*/
/* solium-disable-next-line */
abstract contract HToken is HTokenInterface, Exponential, TokenErrorReporter {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice The anchor symbol of the underlying token, such as ETH, BTC, USD...
*/
string public _anchorSymbol;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint256 internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint256 internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-HToken operations
*/
MarketControllerInterface public controller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateStrategyInterface public interestRateStrategy;
/**
* @notice Initial exchange rate used when minting the first HTokens (used when totalSupply = 0)
*/
uint256 public initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint256 public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint256 public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint256 public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint256 public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint256 public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping(address => uint256) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping(address => mapping(address => uint256)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint256 principal;
uint256 interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
DistributorInterface distributor;
/**
* @notice Initialize the money market
* @param _controller The address of the MarketController
* @param _interestRateStrategy The address of the interest rate model
* @param _name EIP-20 name of this token
* @param _symbol EIP-20 symbol of this token
*/
function initialize(
address payable _admin,
MarketControllerInterface _controller,
InterestRateStrategyInterface _interestRateStrategy,
DistributorInterface _distributor,
string memory _name,
string memory _symbol,
string memory _anchor
) public {
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
initialExchangeRateMantissa = 1e18; // 1:1 ratio
reserveFactorMantissa = 1e17; // 10%
admin = _admin;
controller = _controller;
distributor = _distributor;
// Initialize block number and borrow index (block number mocks depend on controller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
interestRateStrategy = _interestRateStrategy;
name = _name;
symbol = _symbol;
decimals = 8;
_anchorSymbol = _anchor;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
}
function anchorSymbol() external override view returns (string memory) {
return _anchorSymbol;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(
address spender,
address src,
address dst,
uint256 tokens
) internal returns (uint256) {
/* Fail if transfer not allowed */
uint256 allowed = controller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint256 startingAllowance = 0;
if (spender == src) {
startingAllowance = uint256(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint256 allowanceNew;
uint256 srcTokensNew;
uint256 dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint256(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
uint256 distributeErr = distributor.increaseSupply(dst, address(this), tokens);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
distributeErr = distributor.decreaseSupply(src, address(this), tokens, srcTokensNew);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
controller.transferVerify(address(this), src, dst, tokens);
return uint256(Error.NO_ERROR);
}
/**
* @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
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR);
}
/**
* @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
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR);
}
/**
* @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 (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @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 The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external override view returns (uint256) {
return accountTokens[owner];
}
function getAccrualBlockNumber() external override view returns (uint256) {
return accrualBlockNumber;
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external override returns (uint256) {
Exp memory exchangeRate = Exp({ mantissa: exchangeRateStored() });
(MathError mErr, uint256 balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by controller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account)
external
override
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 hTokenBalance = accountTokens[account];
uint256 borrowBalance;
uint256 exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint256(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint256(Error.MATH_ERROR), 0, 0, 0);
}
return (uint256(Error.NO_ERROR), hTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this hToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external override view returns (uint256) {
return interestRateStrategy.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this hToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external override view returns (uint256) {
return interestRateStrategy.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external override view returns (uint256) {
// require(accrueInterestInternal() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external override view returns (uint256) {
// require(accrueInterestInternal() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) internal view returns (uint256) {
(MathError err, uint256 result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint256) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint256 principalTimesIndex;
uint256 result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() external override view returns (uint256) {
// require(accrueInterestInternal() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the HToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint256) {
(MathError err, uint256 result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the HToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint256) {
uint256 _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint256 totalCash = getCashPrior();
uint256 cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this hToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external override view returns (uint256) {
return getCashPrior();
}
function accrueInterest() external override returns (uint256) {
return accrueInterestInternal();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterestInternal() internal returns (uint256) {
/* Remember the initial block number */
uint256 currentBlockNumber = getBlockNumber();
uint256 accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint256(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint256 cashPrior = getCashPrior();
uint256 borrowsPrior = totalBorrows;
uint256 reservesPrior = totalReserves;
uint256 borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint256 borrowRateMantissa = interestRateStrategy.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint256 blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint256 interestAccumulated;
uint256 totalBorrowsNew;
uint256 totalReservesNew;
uint256 borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({ mantissa: borrowRateMantissa }), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return
failOpaque(
Error.MATH_ERROR,
FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
uint256(mathErr)
);
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return
failOpaque(
Error.MATH_ERROR,
FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
uint256(mathErr)
);
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return
failOpaque(
Error.MATH_ERROR,
FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
uint256(mathErr)
);
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(
Exp({ mantissa: reserveFactorMantissa }),
interestAccumulated,
reservesPrior
);
if (mathErr != MathError.NO_ERROR) {
return
failOpaque(
Error.MATH_ERROR,
FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
uint256(mathErr)
);
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return
failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint256(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives hTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint256 mintAmount) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint256 exchangeRateMantissa;
uint256 mintTokens;
uint256 totalSupplyNew;
uint256 accountTokensNew;
uint256 actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives hTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint256 mintAmount) internal returns (uint256, uint256) {
/* Fail if mint not allowed */
uint256 allowed = controller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.MINT_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The hToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the hToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of hTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(
vars.actualMintAmount,
Exp({ mantissa: vars.exchangeRateMantissa })
);
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of hTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
uint256 distributeErr = distributor.increaseSupply(minter, address(this), vars.mintTokens);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint256(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems hTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of hTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint256 redeemTokens) internal nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems hTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming hTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint256 redeemAmount) internal nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint256 exchangeRateMantissa;
uint256 redeemTokens;
uint256 redeemAmount;
uint256 totalSupplyNew;
uint256 accountTokensNew;
}
/**
* @notice User redeems hTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of hTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming hTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(
address payable redeemer,
uint256 redeemTokensIn,
uint256 redeemAmountIn
) internal returns (uint256) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(
Exp({ mantissa: vars.exchangeRateMantissa }),
redeemTokensIn
);
if (vars.mathErr != MathError.NO_ERROR) {
return
failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint256(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(
redeemAmountIn,
Exp({ mantissa: vars.exchangeRateMantissa })
);
if (vars.mathErr != MathError.NO_ERROR) {
return
failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint256(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint256 allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REDEEM_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return
failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return
failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The hToken must handle variations between ERC-20 and ETH underlying.
* On success, the hToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
uint256 distributeErr = distributor.decreaseSupply(
redeemer,
address(this),
vars.redeemTokens,
vars.accountTokensNew
);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
controller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint256 borrowAmount) internal nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint256 borrowAmount) internal returns (uint256) {
/* Fail if borrow not allowed */
uint256 allowed = controller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.BORROW_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return
failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return
failOpaque(
Error.MATH_ERROR,
FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
uint256(vars.mathErr)
);
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return
failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The hToken must handle variations between ERC-20 and ETH underlying.
* On success, the hToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
uint256 distributeErr = distributor.increaseBorrow(borrower, address(this), borrowAmount);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.borrowVerify(address(this), borrower, borrowAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint256 repayAmount) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint256 repayAmount)
internal
nonReentrant
returns (uint256, uint256)
{
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint256 repayAmount;
uint256 borrowerIndex;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
uint256 actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(
address payer,
address borrower,
uint256 repayAmount
) internal returns (uint256, uint256) {
/* Fail if repayBorrow not allowed */
uint256 allowed = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (
failOpaque(
Error.MATH_ERROR,
FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
uint256(vars.mathErr)
),
0
);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint256(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The hToken must handle variations between ERC-20 and ETH underlying.
* On success, the hToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
uint256 distributeErr = distributor.decreaseSupply(
borrower,
address(this),
vars.actualRepayAmount,
vars.accountBorrowsNew
);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint256(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this hToken to be liquidated
* @param hTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(
address borrower,
uint256 repayAmount,
HTokenInterface hTokenCollateral
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = hTokenCollateral.accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, hTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this hToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param hTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(
address liquidator,
address borrower,
uint256 repayAmount,
HTokenInterface hTokenCollateral
) internal returns (uint256, uint256) {
/* Fail if liquidate not allowed */
uint256 allowed = controller.liquidateBorrowAllowed(
address(this),
address(hTokenCollateral),
liquidator,
borrower,
repayAmount
);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify hTokenCollateral market's block number equals current block number */
if (hTokenCollateral.getAccrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint256(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint256(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint256 amountSeizeError, uint256 seizeTokens) = controller.liquidateCalculateSeizeTokens(
address(this),
address(hTokenCollateral),
actualRepayAmount
);
require(amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(hTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint256 seizeError;
if (address(hTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = hTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint256(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(hTokenCollateral), seizeTokens);
/* We call the defense hook */
controller.liquidateBorrowVerify(
address(this),
address(hTokenCollateral),
liquidator,
borrower,
actualRepayAmount,
seizeTokens
);
return (uint256(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another hToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed hToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of hTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external override nonReentrant returns (uint256) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another HToken.
* Its absolutely critical to use msg.sender as the seizer hToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed hToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of hTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(
address seizerToken,
address liquidator,
address borrower,
uint256 seizeTokens
) internal returns (uint256) {
/* Fail if seize not allowed */
uint256 allowed = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_CONTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint256 borrowerTokensNew;
uint256 liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint256(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
uint256 distributeErr = distributor.increaseSupply(liquidator, address(this), seizeTokens);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
distributeErr = distributor.decreaseSupply(borrower, address(this), seizeTokens, borrowerTokensNew);
require(distributeErr == 0, "DISTRIBUTE_TOKENS_FIALED");
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint256(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint256 newReserveFactorMantissa) external override nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint256 oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint256 addAmount) internal nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint256 addAmount) internal returns (uint256, uint256) {
// totalReserves + actualAddAmount
uint256 totalReservesNew;
uint256 actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The hToken must handle variations between ERC-20 and ETH underlying.
* On success, the hToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint256(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint256 reduceAmount) external override nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) {
// totalReserves - reduceAmount
uint256 totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint256(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal virtual view returns (uint256);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint256 amount) internal virtual returns (uint256);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint256 amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
| * @notice Get cash balance of this hToken in the underlying asset @return The quantity of underlying asset owned by this contract/ | function getCash() external override view returns (uint256) {
return getCashPrior();
}
| 6,356,766 | [
1,
967,
276,
961,
11013,
434,
333,
366,
1345,
316,
326,
6808,
3310,
327,
1021,
10457,
434,
6808,
3310,
16199,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
1927,
961,
1435,
3903,
3849,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
2463,
1927,
961,
25355,
5621,
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
] |
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./PancakeRouter.sol";
import "./Open-Zeppelin.sol";
import "./AnalyticMath.sol";
import "hardhat/console.sol";
contract XDAO03Up is
Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, OwnableUpgradeable, AnalyticMath {
using SafeMath for uint256;
/////////////////////////////////////////////////////////////////////////////////////
//
// These variables are not deployed.
//
/////////////////////////////////////////////////////////////////////////////////////
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 1e15 * 10 ** uint256(DECIMALS);
/////////////////////////////////////////////////////////////////////////////////////
//
// Borrows from ERC20Upgradeable
//
// _transfer(...) is overriden.
//
/////////////////////////////////////////////////////////////////////////////////////
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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal {
__Context_init_unchained();
__Ownable_init();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal {
_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 bep20 token owner which is necessary for binding with bep2 token
*/
function getOwner() public view returns (address) {
return owner();
}
/**
* @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 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);
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 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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add( 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.sub(amount);
//}
_totalSupply = _totalSupply.sub(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);
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/////////////////////////////////////////////////////////////////////////////////////
//
// Borrows from ERC20BurnableUpgradeable
//
/////////////////////////////////////////////////////////////////////////////////////
function __ERC20Burnable_init() internal {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal {
}
/**
* @dev Destroys `amount` tokens from the caller.
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
//unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
//}
_burn(account, amount);
}
/////////////////////////////////////////////////////////////////////////////////////
//
// Borrows from ERC20PresetFixedSupplyUpgradeable
//
/////////////////////////////////////////////////////////////////////////////////////
/**
* @dev Mints `initialSupply` amount of token and transfers them to `owner`.
*
* See {ERC20-constructor}.
*/
function __ERC20PresetFixedSupply_init(
string memory __name,
string memory __symbol,
uint256 initialSupply,
address owner
) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC20_init_unchained(__name, __symbol);
__ERC20Burnable_init_unchained();
__ERC20PresetFixedSupply_init_unchained(initialSupply, owner);
//__XDAO_init_unchained();
}
function __ERC20PresetFixedSupply_init_unchained(
uint256 initialSupply,
address owner
) internal initializer {
_mint(owner, initialSupply);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// The state data items of this contract are packed below, after those of the base contracts.
// The items are tightly arranged for efficient packing into 32-bytes slots.
// See https://docs.soliditylang.org/en/v0.8.9/internals/layout_in_storage.html for more.
//
// Do NOT make any changes to this packing when you upgrade this implementation.
// See https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies for more.
//
//////////////////////////////////////////////////////////////////////////////////////////////
uint256 public constant MAGPOWER = 5;
uint256 public constant MAGNIFIER = 10 ** MAGPOWER;
uint256 public constant HUNDRED_PERCENT = MAGNIFIER * 100;
uint256 public constant FEE_TRADE_BURN = 31416; // this/MAGNIFIER = 0.31416 or 31.416%
uint256 public constant FEE_SHIFT_BURN = 13374; // this/MAGNIFIER = 0.13374 or 13.374%
uint256 public constant FEE_TRADE_REWARDS = 10000; // this/MAGNIFIER = 0.10000 or 10,000%
uint256 public constant INTERVAL_VOTE_BURN = 3600 * 12;
uint256 public constant INTERVAL_ALL_BURN = 3600 * 24;
uint256 public constant INTERVAL_LP_REWARDS = 3600 * 12;
uint256 public constant MIN_INTERVAL_SEC = 60; //
uint256 public constant IMPACT_VOTE_BURN = 70; // this/MAGNIFIER = 0.00070 or 0.070%
uint256 public constant IMPACT_ALL_BURN = 777; // this/MAGNIFIER = 0.00777 or 0.777%
uint256 public constant IMPACT_LP_REWARDS = 690; // this/MAGNIFIER = 0.00690 or 0.690%
address public constant ADDR_HERTZ_REWARDS = 0x5cA00f843cd9649C41fC5B71c2814d927D69Df95; // Account4
using SafeMath for uint256;
enum TransferType {
OTHER, SELL_SURE, BUY_SURE, SWAP_SURE, SELL_PRESUMED, BUY_PRESUMED, SWAP_PRESUMED, SHIFT_SEND, SHIFT_RECEIVE, SHIFT_TRANSCEIVE }
enum FeeType { TRADE_BURN, SHIFT_BURN, TRADE_REWARDS }
enum PulseType { VOTE_BURN, ALL_BURN, LP_REWARDS }
struct Fees {
uint256 trade_burn;
uint256 shift_burn;
uint256 trade_rewards;
}
struct Pulse {
uint256 intervalSec;
uint256 impactScale;
}
struct Holder {
uint256 lastTransferTime;
uint256 lastCheckTimeSec;
}
event SetFees(Fees _fees);
event SetPulse_VoteBurn(Pulse _pulse);
event SetPulse_AllBurn(Pulse _pulse);
event SetPulse_LpRewards(Pulse _pulse);
event SwapAndLiquify(uint256 tokenSwapped, uint256 etherReceived, uint256 tokenLiquified, uint256 etherLiquified );
uint256 public fee_trade_burn;
uint256 public fee_shift_burn;
uint256 public fee_trade_rewards;
Pulse public pulse_vote_burn;
Pulse public pulse_all_burn;
Pulse public pulse_lp_rewards;
mapping(address => Holder) public holders;
uint256 public beginingTimeSec;
IPancakeRouter02 public dexRouter;
address public pairWithWETH;
address public pairWithHertz;
mapping(address => bool) public knownDexContracts;
bool public autoPulse; // Place this bool type at the bottom of storage.
address public hertztoken;
address public hertzRewardsAddress;
AnalyticMath public math;
///////////////////////////////////////////////////////////////////////////////////////////////
//
// The logic (operational code) of the implementation.
// You can upgrade this part of the implementation freely:
// - add new state data itmes.
// - override, add, or remove.
// You cannot make changes to the above existing state data items.
//
//////////////////////////////////////////////////////////////////////////////////////////////
function initialize(address _dexRouter, address _hertztoken) public virtual initializer { // onlyOwwer is impossible call here.
__Ownable_init();
__ERC20PresetFixedSupply_init("XDAO Utility Token", "XO", INITIAL_SUPPLY, owner());
__XDAO_init(_dexRouter, _hertztoken);
}
function __XDAO_init(address _dexRouter, address _hertztoken) public onlyOwner {
__XDAO_init_unchained(_dexRouter, _hertztoken);
}
function __XDAO_init_unchained(address _dexRouter, address _hertztoken) public onlyOwner {
revertToInitialSettings(_dexRouter, _hertztoken);
beginingTimeSec = block.timestamp;
}
function revertToInitialSettings(address _dexRouter, address _hertztoken) public virtual onlyOwner {
uint256 _fee_trade_burn = FEE_TRADE_BURN;
uint256 _fee_shift_burn = FEE_SHIFT_BURN;
uint256 _fee_lp_rewards = FEE_TRADE_BURN;
Fees memory _fees = Fees(_fee_trade_burn, _fee_shift_burn, _fee_lp_rewards);
setFees(_fees);
Pulse memory _pulse = Pulse(INTERVAL_VOTE_BURN, IMPACT_VOTE_BURN);
setPulse_VoteBurn(_pulse);
_pulse = Pulse(INTERVAL_ALL_BURN, IMPACT_ALL_BURN);
setPulse_AllBurn(_pulse);
_pulse = Pulse(INTERVAL_LP_REWARDS, IMPACT_LP_REWARDS);
setPulse_LpRewards(_pulse);
autoPulse = true;
dexRouter = IPancakeRouter02(_dexRouter);
pairWithWETH = createPoolWithWETH(_dexRouter);
pairWithHertz = createPoolWithToken(_dexRouter, _hertztoken);
hertztoken = _hertztoken;
hertzRewardsAddress = ADDR_HERTZ_REWARDS;
//math = AnalyticMath(_math);
knownDexContracts[_dexRouter] = true;
knownDexContracts[pairWithWETH] = true;
knownDexContracts[pairWithHertz] = true;
}
function setFees(Fees memory _fees) public virtual onlyOwner {
uint256 total;
require(_fees.trade_burn <= HUNDRED_PERCENT, "Fee rate out of range");
require(_fees.shift_burn <= HUNDRED_PERCENT, "Fee rate out of range");
require(_fees.trade_rewards <= HUNDRED_PERCENT, "Fee rate out of range");
total = _fees.trade_burn + _fees.shift_burn + _fees.trade_rewards;
require(total <= HUNDRED_PERCENT, "Fee rate out of range");
fee_trade_burn = _fees.trade_burn;
fee_shift_burn = _fees.shift_burn;
fee_trade_rewards = _fees.trade_rewards;
emit SetFees(_fees);
}
function setPulse_VoteBurn(Pulse memory _pulse) public virtual onlyOwner {
require(_pulse.intervalSec > MIN_INTERVAL_SEC, "IntervalSec out of range");
require(_pulse.impactScale <= HUNDRED_PERCENT, "ImpactScale out of range");
pulse_vote_burn = _pulse;
emit SetPulse_VoteBurn(_pulse);
}
function setPulse_AllBurn(Pulse memory _pulse) public virtual onlyOwner {
require(_pulse.intervalSec > MIN_INTERVAL_SEC, "IntervalSec out of range");
require(_pulse.impactScale <= HUNDRED_PERCENT, "ImpactScale out of range");
pulse_all_burn = _pulse;
emit SetPulse_AllBurn(_pulse);
}
function setPulse_LpRewards(Pulse memory _pulse) public virtual onlyOwner {
require(_pulse.intervalSec > MIN_INTERVAL_SEC, "IntervalSec out of range");
require(_pulse.impactScale <= HUNDRED_PERCENT, "ImpactScale out of range");
pulse_all_burn = _pulse;
emit SetPulse_LpRewards(_pulse);
}
function setAutoPulse( bool _autoPulse ) external virtual onlyOwner {
autoPulse = _autoPulse;
}
bool hooked;
modifier lockHook {
require( ! hooked, "Nested hook");
hooked = true;
_;
hooked = false;
}
function createPoolWithWETH( address _routerAddress ) virtual public onlyOwner returns(address pool) {
IPancakeRouter02 _dexRouter = IPancakeRouter02(_routerAddress);
pool = IPancakeFactory(_dexRouter.factory()).getPair(address(this), _dexRouter.WETH());
if(pool == address(0)) {
pool = IPancakeFactory(_dexRouter.factory()).createPair(address(this), _dexRouter.WETH());
}
}
function createPoolWithToken(address _routerAddress, address token ) virtual public onlyOwner returns(address pool) {
IPancakeRouter02 _dexRouter = IPancakeRouter02(_routerAddress);
pool = IPancakeFactory(_dexRouter.factory()).getPair(address(this), token);
if(pool == address(0)) {
pool = IPancakeFactory(_dexRouter.factory()).createPair(address(this), token);
}
}
//====================================================================================================
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
_hookForPulses(from);
_hookForPulses(to);
}
uint256 internal _call_level;
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
_call_level += 1;
require(sender != address(0), "Transfer from zero address");
require(recipient != address(0), "Transfer to zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
if(_call_level == 1 && ! _isFeeFreeTransfer(sender, recipient) ) {
amount -= _payFees2(sender, recipient, amount); // May revert if it's a swap transfer.
}
_balances[sender] = _balances[sender].sub( amount); // May revert if sender is a swapper and paid outside of original "amount"
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
holders[sender].lastTransferTime = block.timestamp;
holders[recipient].lastTransferTime = block.timestamp;
_call_level -= 1;
}
function _isFeeFreeTransfer(address sender, address recipient) internal view virtual returns (bool feeFree) {
// Start from highly frequent occurences.
feeFree =
_isBidirFeeFreeAddress(sender)
|| _isBidirFeeFreeAddress(recipient);
}
function _isBidirFeeFreeAddress(address _address) internal view virtual returns (bool feeFree) {
feeFree =
_address == owner()
|| _address == pairWithWETH
|| _address == pairWithHertz;
}
function _isHookable(address sender, address recipient) internal virtual view returns(bool _unmanageable) {
_unmanageable =
_isBidirHookableAddress(sender)
|| _isBidirHookableAddress(recipient);
}
function _isBidirHookableAddress(address _address) internal view virtual returns (bool feeFree) {
feeFree =
_address == owner()
|| _address == pairWithWETH
|| _address == pairWithHertz;
}
/**
* This function is followed by the following lines, in the _transfer function.
* amount -= _payFees2(sender, recipient, amount);
* _balances[sender] = _balances[sender].sub( amount);
* _balances[recipient] = _balances[recipient].add(amount);
**/
function _payFees2(address sender, address recipient, uint256 principal) internal virtual returns(uint256 feesPaid) {
TransferType tType = _getTransferType(sender, recipient);
if(
tType == TransferType.SELL_SURE
|| tType == TransferType.SELL_PRESUMED
|| tType == TransferType.BUY_SURE
|| tType == TransferType.BUY_PRESUMED
) {
// If it's SELL, then the Seller == sender will pay 'feedPaid' > 0, effectively.
// If it's BUY, then the Buyer == recipient will pay 'feesPaid' > 0, effiectively.
// In both cases, payments are safe because they are debited from the 'principal',
// which is available from the sender's balance.
// The underlying assumption: sending goes ahead of receiving in a Dex-mediated swap.
// The assumption is quite natural, is the case in all known Dexes, and might be proven.
// 31.4159265359% Fee burned on buys and sells.
uint256 fee;
fee = principal.mul(fee_trade_burn).div(MAGNIFIER);
burnFrom(sender, fee); // burnt
feesPaid += fee;
// 1–55% Fee sold to HTZ and added to XDAO lps airdrop rewards depending on how much you are purchasing or selling.
fee = principal.mul(fee_trade_rewards).div(MAGNIFIER);
_transfer(sender, address(this), fee);
_swapForToken(fee, hertztoken, hertzRewardsAddress);
feesPaid += fee;
} else if (
tType == TransferType.SWAP_SURE
|| tType == TransferType.SWAP_PRESUMED
) {
// Both the Seller == sender and Buyer == recipient should pay.
// We do not know who will pay 'feesPaid' > 0 effectively.
// The Seller and Buyer have to pay outside of the principal.
// So, the recipient's payment is not guaranteed.
// 13.37420% fee on transfers burned.
uint256 fee;
fee = principal.mul(fee_trade_burn).div(MAGNIFIER);
burnFrom(sender, fee); // sender pays for burn
burnFrom(recipient, fee); // recipient pays for burn. // May revert.
fee = principal.mul(fee_trade_rewards).div(MAGNIFIER);
_transfer(sender, address(this), fee);
_transfer(recipient, address(this), fee); // May revert.
_swapForToken(fee, hertztoken, hertzRewardsAddress);
feesPaid = 0; // just confirm.
} else if(
tType == TransferType.SHIFT_SEND
|| tType == TransferType.SHIFT_RECEIVE
|| tType == TransferType.SHIFT_TRANSCEIVE
) {
// This is a uni-directional transaction.
// The transfer itself pays, or the sender and recipient share the payment.
uint256 fee;
fee = principal.mul(fee_shift_burn).div(MAGNIFIER);
burnFrom(sender, fee); // burnt
feesPaid += fee;
}
}
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 _getTransferType(address sender, address recipient) internal virtual returns(TransferType) {
if(! _isContract(msg.sender) ) {
if( ! _isContract(sender) ) {
if ( ! _isContract(recipient) ) {
return TransferType.SHIFT_TRANSCEIVE;
} else {
return TransferType.SHIFT_SEND;
}
} else {
if ( ! _isContract(recipient) ) {
return TransferType.SHIFT_RECEIVE;
} else {
return TransferType.OTHER;
}
}
} else {
if( ! _isContract(sender) ) {
if( ! _isContract(recipient) ) {
if (knownDexContracts[msg.sender] == true ) {
return TransferType.SWAP_SURE;
} else {
return TransferType.SWAP_PRESUMED;
}
} else {
if(knownDexContracts[recipient] == true || knownDexContracts[msg.sender] == true) {
return TransferType.SELL_SURE;
} else {
return TransferType.SELL_PRESUMED;
}
}
} else {
if( ! _isContract(recipient) ) {
if(knownDexContracts[sender] == true || knownDexContracts[msg.sender] == true) {
return TransferType.BUY_SURE;
} else {
return TransferType.BUY_PRESUMED;
}
} else {
return TransferType.OTHER;
}
}
}
}
function getBalanceInCyberswap(address holderAddress) virtual public returns(uint256) {
return 0;
}
function debitBalanceInCyberswap(address holderAddress, uint256 amount) virtual public {
}
function getBalanceInAgency(address holderAddress) virtual public returns(uint256) {
return 0;
}
function debitBalanceInAgency(address holderAddress, uint256 amount) virtual public {
}
function _hookForPulses(address holderAddress) virtual internal returns (bool worked) {
Holder storage holder = holders[holderAddress];
if(holder.lastCheckTimeSec == block.timestamp) return false;
uint256 timeLapsed = block.timestamp - (holder.lastCheckTimeSec != 0 ? holder.lastCheckTimeSec : beginingTimeSec);
uint256 missingChecks; uint256 rate_p; uint256 rate_q; uint256 tokens; uint256 agencyTokens; uint tokensToBurn;
//---------------------- vote_burn, 12 hours ------------------------------
// 0.07% of tokens in the Agency dapp actively being used for voting burned every 12 hours.
missingChecks = timeLapsed / pulse_all_burn.intervalSec;
if(missingChecks > 0) {
(rate_p, rate_q) = pow(MAGNIFIER.mul(MAGNIFIER - pulse_vote_burn.impactScale), MAGNIFIER, missingChecks, uint256(1));
require(rate_p <= rate_q, "Invalid rate");
agencyTokens = getBalanceInAgency(holderAddress);
tokens = agencyTokens.mul(rate_p).div(rate_q);
debitBalanceInAgency(holderAddress, tokens);
burnFrom(holderAddress, tokens);
agencyTokens -= tokens;
worked = true;
}
//---------------------- all_burn, 24 hours, burn tokens (not in Cyberswap/Agency) ------------------------------
// 0.777% of tokens(not in Cyberswap/Agency dapp) burned each 24 hours from users wallets.
missingChecks = timeLapsed / pulse_all_burn.intervalSec;
if(missingChecks > 0) {
(rate_p, rate_q) = pow(MAGNIFIER.mul(MAGNIFIER - pulse_all_burn.impactScale), MAGNIFIER, missingChecks, uint256(1));
require(rate_p <= rate_q, "Invalid rate");
tokens = worked == true? agencyTokens : getBalanceInAgency(holderAddress);
tokens += getBalanceInCyberswap(holderAddress);
tokens = balanceOf(holderAddress).sub(tokens);
tokens = tokens.mul(rate_p).div(rate_q);
burnFrom(holderAddress, tokens);
worked = true;
}
//---------------------- lp_rewards, 12 hours ------------------------------
// 0.69% of XDAO/FTM LP has the XDAO side sold for FTM, then the FTM is used to buy HTZ which is added to XDAO lps airdrop rewards every 12 hours.
missingChecks = timeLapsed / pulse_lp_rewards.intervalSec;
if(missingChecks > 0) {
(rate_p, rate_q) = pow(MAGNIFIER.mul(MAGNIFIER - pulse_lp_rewards.impactScale), MAGNIFIER, missingChecks, uint256(1));
uint256 reserveThis; uint256 reserveWeth;
bool thisIsToken0 = IPancakePair(pairWithWETH).token0() == address(this);
(uint256 reserve0, uint256 reserve1, ) = IPancakePair(pairWithWETH).getReserves();
(reserveThis, reserveWeth) = thisIsToken0 ? (reserve0, reserve1) : (reserve1, reserve0);
tokens = IPancakePair(pairWithWETH).totalSupply();
tokens = tokens.mul(rate_p).div(rate_q);
//------------------ Under construction --------------------
// // No! require(_balances[address(this)] == uint256(0), "Non-empty store space");
// uint256 amount = _balances[storeAddresses.rewards];
// _sureTransfer(storeAddresses.rewards, address(this), amount);
// _swapForToken(amount, hertztoken, hertzRewardsAddress);
worked = true;
}
if( worked == true ) {
holder.lastCheckTimeSec = block.timestamp;
}
}
function _swapForEther(uint256 tokenAmount) virtual internal {
require( _balances[address(this)] >= tokenAmount, "" );
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = dexRouter.WETH();
// The router's assumption: the path[0] token has the address(this) account, and the amountIn amount belongs to that account.
// The router tries to transferFrom( token = path[0], sender = msg.sender, recipient = pair, amount = amountIn );
_approve(address(this), address(dexRouter), tokenAmount);
dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this), // targetAccount
block.timestamp
);
}
function _swapForToken(uint256 amountIn, address targetToken, address targetAccount) virtual internal {
require( _balances[address(this)] >= amountIn, "" );
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = targetToken;
// The router's assumption: the path[0] token has the address(this) account, and the amountIn amount belongs to that account.
// The router tries to transferFrom( token = path[0], sender = msg.sender, recipient = pair, amount = amountIn );
_approve(address(this), address(dexRouter), amountIn);
dexRouter.swapExactTokensForTokens(
amountIn,
0,
path,
targetAccount,
block.timestamp
);
}
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) virtual internal {
// The router's assumption: the path[0] token has the address(this) account, and the amountIn amount belongs to that account.
// The router tries to transferFrom( token = path[0], sender = msg.sender, recipient = pair, amount = amountIn );
_approve(address(this), address(dexRouter), tokenAmount);
dexRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(), // What if the owner changes? Why not use a 3rd, neutral address?
block.timestamp
);
}
receive() external payable {}
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// Calculate the square root of the perfect square of a power of two that is the closest to x.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) {
result <<= 1;
}
// The operations can never overflow because the result is max 2^127 when it enters this block.
//unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1; // Seven iterations should be enough
uint256 roundedDownResult = x / result;
return result >= roundedDownResult ? roundedDownResult : result;
//}
}
uint256[10] private __gap;
}
| ---------------------- all_burn, 24 hours, burn tokens (not in Cyberswap/Agency) ------------------------------ 0.777% of tokens(not in Cyberswap/Agency dapp) burned each 24 hours from users wallets. | missingChecks = timeLapsed / pulse_all_burn.intervalSec;
| 15,829,209 | [
1,
1271,
13093,
777,
67,
70,
321,
16,
4248,
7507,
16,
18305,
2430,
261,
902,
316,
22337,
2210,
91,
438,
19,
2577,
2075,
13,
12146,
16982,
374,
18,
14509,
9,
434,
2430,
12,
902,
316,
22337,
2210,
91,
438,
19,
2577,
2075,
302,
2910,
13,
18305,
329,
1517,
4248,
7507,
628,
3677,
17662,
2413,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3315,
4081,
273,
813,
48,
8676,
342,
31963,
67,
454,
67,
70,
321,
18,
6624,
2194,
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
] |
./partial_match/1/0xD0b84F42b3B88eeF7AA88c48Ac8EC08130d48595/sources/src/v0.8/ccip/pools/LockReleaseTokenPool.sol | @notice returns the lock release interface flag used for EIP165 identification. | function getLockReleaseInterfaceId() public pure returns (bytes4) {
return LOCK_RELEASE_INTERFACE_ID;
}
| 4,447,994 | [
1,
6154,
326,
2176,
3992,
1560,
2982,
1399,
364,
512,
2579,
28275,
24739,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
22206,
7391,
1358,
548,
1435,
1071,
16618,
1135,
261,
3890,
24,
13,
288,
203,
565,
327,
14631,
67,
30762,
67,
18865,
67,
734,
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
] |
./full_match/43113/0xd219b0A544b437A8b2f4D7A481bC8A029cde9d35/sources/contracts/Avax-Token.sol | @dev Add liquidity approve token transfer to cover all possible scenarios add the liquidity | function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniSwapRouter), tokenAmount);
address(this),
tokenAmount,
operator(),
block.timestamp
);
}
| 7,185,900 | [
1,
986,
4501,
372,
24237,
6617,
537,
1147,
7412,
358,
5590,
777,
3323,
22456,
527,
326,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
48,
18988,
24237,
12,
11890,
5034,
1147,
6275,
16,
2254,
5034,
13750,
6275,
13,
3238,
288,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
77,
12521,
8259,
3631,
1147,
6275,
1769,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1147,
6275,
16,
203,
5411,
3726,
9334,
203,
5411,
1203,
18,
5508,
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
] |
contract ProtectTheCastle {
// King's Jester
address public jester;
// Record the last Reparation time
uint public lastReparation;
// Piggy Bank Amount
uint public piggyBank;
// Collected Fee Amount
uint public collectedFee;
// Track the citizens who helped to repair the castle
address[] public citizensAddresses;
uint[] public citizensAmounts;
uint32 public totalCitizens;
uint32 public lastCitizenPaid;
// Brided Citizen who made the system works
address public bribedCitizen;
// Record how many times the castle had fell
uint32 public round;
// Amount already paid back in this round
uint public amountAlreadyPaidBack;
// Amount invested in this round
uint public amountInvested;
uint constant SIX_HOURS = 60 * 60 * 6;
function ProtectTheCastle() {
// Define the first castle
bribedCitizen = msg.sender;
jester = msg.sender;
lastReparation = block.timestamp;
amountAlreadyPaidBack = 0;
amountInvested = 0;
totalCitizens = 0;
}
function repairTheCastle() returns(bool) {
uint amount = msg.value;
// Check if the minimum amount if reached
if (amount < 10 finney) {
msg.sender.send(msg.value);
return false;
}
// If the amount received is more than 100 ETH return the difference
if (amount > 100 ether) {
msg.sender.send(msg.value - 100 ether);
amount = 100 ether;
}
// Check if the Castle has fell
if (lastReparation + SIX_HOURS < block.timestamp) {
// Send the Piggy Bank to the last 3 citizens
// If there is no one who contributed this last 6 hours, no action needed
if (totalCitizens == 1) {
// If there is only one Citizen who contributed, he gets the full Pigg Bank
citizensAddresses[citizensAddresses.length - 1].send(piggyBank);
} else if (totalCitizens == 2) {
// If only 2 citizens contributed
citizensAddresses[citizensAddresses.length - 1].send(piggyBank * 65 / 100);
citizensAddresses[citizensAddresses.length - 2].send(piggyBank * 35 / 100);
} else if (totalCitizens >= 3) {
// If there is 3 or more citizens who contributed
citizensAddresses[citizensAddresses.length - 1].send(piggyBank * 55 / 100);
citizensAddresses[citizensAddresses.length - 2].send(piggyBank * 30 / 100);
citizensAddresses[citizensAddresses.length - 3].send(piggyBank * 15 / 100);
}
// Define the new Piggy Bank
piggyBank = 0;
// Define the new Castle
jester = msg.sender;
lastReparation = block.timestamp;
citizensAddresses.push(msg.sender);
citizensAmounts.push(amount * 2);
totalCitizens += 1;
amountInvested += amount;
// All goes to the Piggy Bank
piggyBank += amount;
// The Jetster take 3%
jester.send(amount * 3 / 100);
// The brided Citizen takes 3%
collectedFee += amount * 3 / 100;
round += 1;
} else {
// The Castle is still up
lastReparation = block.timestamp;
citizensAddresses.push(msg.sender);
citizensAmounts.push(amount * 2);
totalCitizens += 1;
amountInvested += amount;
// 5% goes to the Piggy Bank
piggyBank += (amount * 5 / 100);
// The Jetster takes 3%
jester.send(amount * 3 / 100);
// The brided Citizen takes 3%
collectedFee += amount * 3 / 100;
while (citizensAmounts[lastCitizenPaid] < (address(this).balance - piggyBank - collectedFee) && lastCitizenPaid <= totalCitizens) {
citizensAddresses[lastCitizenPaid].send(citizensAmounts[lastCitizenPaid]);
amountAlreadyPaidBack += citizensAmounts[lastCitizenPaid];
lastCitizenPaid += 1;
}
}
}
// fallback function
function() {
repairTheCastle();
}
// When the castle would be no more...
function surrender() {
if (msg.sender == bribedCitizen) {
bribedCitizen.send(address(this).balance);
selfdestruct(bribedCitizen);
}
}
// When the brided Citizen decides to give his seat to someone else
function newBribedCitizen(address newBribedCitizen) {
if (msg.sender == bribedCitizen) {
bribedCitizen = newBribedCitizen;
}
}
// When the brided Citizen decides to collect his fees
function collectFee() {
if (msg.sender == bribedCitizen) {
bribedCitizen.send(collectedFee);
}
}
// When the jester can't handle it anymore, he can give his position to someone else
function newJester(address newJester) {
if (msg.sender == jester) {
jester = newJester;
}
}
}
| When the brided Citizen decides to collect his fees | function collectFee() {
if (msg.sender == bribedCitizen) {
bribedCitizen.send(collectedFee);
}
}
| 13,047,534 | [
1,
9434,
326,
324,
566,
785,
385,
305,
452,
275,
2109,
4369,
358,
3274,
18423,
1656,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3274,
14667,
1435,
288,
203,
3639,
309,
261,
3576,
18,
15330,
422,
324,
1533,
329,
39,
305,
452,
275,
13,
288,
203,
5411,
324,
1533,
329,
39,
305,
452,
275,
18,
4661,
12,
14676,
329,
14667,
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
] |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY171() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF784(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER754(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE384(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE522(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM156(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER68(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL81(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER324() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY171() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF784(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER754(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER587(_MSGSENDER324(), recipient, amount);
return true;
}
function ALLOWANCE384(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE522(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, amount);
return true;
}
function TRANSFERFROM156(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER587(sender, recipient, amount);
_APPROVE274(sender, _MSGSENDER324(), _allowances[sender][_MSGSENDER324()].SUB131(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE835(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].ADD951(addedValue));
return true;
}
function DECREASEALLOWANCE568(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].SUB131(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER587(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB131(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD951(amount);
emit TRANSFER68(sender, recipient, amount);
}
function _MINT189(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD951(amount);
_balances[account] = _balances[account].ADD951(amount);
emit TRANSFER68(address(0), account, amount);
}
function _BURN372(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB131(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB131(amount);
emit TRANSFER68(account, address(0), amount);
}
function _APPROVE274(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
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 APPROVAL81(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME128() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL200() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS712() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD951(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB131(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB131(a, b, "SafeMath: subtraction overflow");
}
function SUB131(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL231(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV400(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV400(a, b, "SafeMath: division by zero");
}
function DIV400(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function ISCONTRACT647(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function SAFETRANSFER747(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFER754.selector, to, value));
}
function SAFETRANSFERFROM172(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFERFROM156.selector, from, to, value));
}
function SAFEAPPROVE759(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE384(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.APPROVE522.selector, spender, value));
}
function CALLOPTIONALRETURN719(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT647(), "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");
}
}
}
contract YFiG is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
mapping (address => bool) public minters;
constructor () public ERC20Detailed("YFiGlobal.Finance", "YFiG", 18) {
governance = msg.sender;
}
function MINT296(address account, uint amount) public { //inject NONSTANDARD NAMING
require(minters[msg.sender], "!minter");
_MINT189(account, amount);
}
function SETGOVERNANCE402(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function ADDMINTER585(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = true;
}
function REMOVEMINTER114(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = false;
}
} | inject NONSTANDARD NAMING
| function TRANSFERFROM156(address sender, address recipient, uint amount) external returns (bool); | 12,662,860 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4235,
17598,
11249,
28946,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
3844,
13,
3903,
1135,
261,
6430,
1769,
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
] |
./full_match/42/0xc067f45538b01a4ABe94690d8729BC8e4C3F67f4/sources/browser/GibIhm2/AktuellsteVersion.sol | @notice Simple getter for convenience while testing | function getBalanceOf(address _input) external view returns (uint) {
if (_input == address(0)) {
return address(this).balance;
}
return IERC20(_input).balanceOf(address(this));
}
| 16,240,725 | [
1,
5784,
7060,
364,
13553,
1323,
7769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2882,
6112,
951,
12,
2867,
389,
2630,
13,
3903,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
67,
2630,
422,
1758,
12,
20,
3719,
288,
203,
5411,
327,
1758,
12,
2211,
2934,
12296,
31,
203,
3639,
289,
203,
3639,
327,
467,
654,
39,
3462,
24899,
2630,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
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
] |
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @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 The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @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
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @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
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @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 (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @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 The number of tokens allowed to be spent (-1 means infinite)
*/
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);
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @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 EIP20NonStandardInterface {
/**
* @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 The 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 `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
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @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 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);
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ErrorReporter.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. using constant string instead of enums
*/
contract ControllerErrorReporter {
string internal constant MARKET_NOT_LISTED = "MARKET_NOT_LISTED";
string internal constant MARKET_ALREADY_LISTED = "MARKET_ALREADY_LISTED";
string internal constant MARKET_ALREADY_ADDED = "MARKET_ALREADY_ADDED";
string internal constant EXIT_MARKET_BALANCE_OWED = "EXIT_MARKET_BALANCE_OWED";
string internal constant EXIT_MARKET_REJECTION = "EXIT_MARKET_REJECTION";
string internal constant MINT_PAUSED = "MINT_PAUSED";
string internal constant BORROW_PAUSED = "BORROW_PAUSED";
string internal constant SEIZE_PAUSED = "SEIZE_PAUSED";
string internal constant TRANSFER_PAUSED = "TRANSFER_PAUSED";
string internal constant MARKET_BORROW_CAP_REACHED = "MARKET_BORROW_CAP_REACHED";
string internal constant MARKET_SUPPLY_CAP_REACHED = "MARKET_SUPPLY_CAP_REACHED";
string internal constant REDEEM_TOKENS_ZERO = "REDEEM_TOKENS_ZERO";
string internal constant INSUFFICIENT_LIQUIDITY = "INSUFFICIENT_LIQUIDITY";
string internal constant INSUFFICIENT_SHORTFALL = "INSUFFICIENT_SHORTFALL";
string internal constant TOO_MUCH_REPAY = "TOO_MUCH_REPAY";
string internal constant CONTROLLER_MISMATCH = "CONTROLLER_MISMATCH";
string internal constant INVALID_COLLATERAL_FACTOR = "INVALID_COLLATERAL_FACTOR";
string internal constant INVALID_CLOSE_FACTOR = "INVALID_CLOSE_FACTOR";
string internal constant INVALID_LIQUIDATION_INCENTIVE = "INVALID_LIQUIDATION_INCENTIVE";
}
contract KTokenErrorReporter {
string internal constant BAD_INPUT = "BAD_INPUT";
string internal constant TRANSFER_NOT_ALLOWED = "TRANSFER_NOT_ALLOWED";
string internal constant TRANSFER_NOT_ENOUGH = "TRANSFER_NOT_ENOUGH";
string internal constant TRANSFER_TOO_MUCH = "TRANSFER_TOO_MUCH";
string internal constant MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
string internal constant MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
string internal constant REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
string internal constant REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
string internal constant BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
string internal constant BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
string internal constant REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
string internal constant REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
string internal constant INVALID_CLOSE_AMOUNT_REQUESTED = "INVALID_CLOSE_AMOUNT_REQUESTED";
string internal constant LIQUIDATE_SEIZE_TOO_MUCH = "LIQUIDATE_SEIZE_TOO_MUCH";
string internal constant TOKEN_INSUFFICIENT_CASH = "TOKEN_INSUFFICIENT_CASH";
string internal constant INVALID_ACCOUNT_PAIR = "INVALID_ACCOUNT_PAIR";
string internal constant LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED";
string internal constant LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED";
string internal constant TOKEN_TRANSFER_IN_FAILED = "TOKEN_TRANSFER_IN_FAILED";
string internal constant TOKEN_TRANSFER_IN_OVERFLOW = "TOKEN_TRANSFER_IN_OVERFLOW";
string internal constant TOKEN_TRANSFER_OUT_FAILED = "TOKEN_TRANSFER_OUT_FAILED";
}
pragma solidity ^0.5.16;
import "./KineSafeMath.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. use SafeMath instead of CarefulMath to fail fast and loudly
*/
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential {
using KineSafeMath for uint;
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.
*/
function getExp(uint num, uint denom) pure internal returns (Exp memory) {
uint rational = num.mul(expScale).div(denom);
return Exp({mantissa : rational});
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint result = a.mantissa.add(b.mantissa);
return Exp({mantissa : result});
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint result = a.mantissa.sub(b.mantissa);
return Exp({mantissa : result});
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
uint scaledMantissa = a.mantissa.mul(scalar);
return 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 (uint) {
Exp memory product = mulScalar(a, scalar);
return 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 (uint) {
Exp memory product = mulScalar(a, scalar);
return truncate(product).add(addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
uint descaledMantissa = a.mantissa.div(scalar);
return Exp({mantissa : descaledMantissa});
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) {
/*
We are doing this as:
getExp(expScale.mul(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`
*/
uint numerator = expScale.mul(scalar);
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 (uint) {
Exp memory fraction = divScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint doubleScaledProduct = a.mantissa.mul(b.mantissa);
// 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.
uint doubleScaledProductWithHalfScale = halfExpScale.add(doubleScaledProduct);
uint product = doubleScaledProductWithHalfScale.div(expScale);
return Exp({mantissa : product});
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (Exp memory) {
return mulExp(Exp({mantissa : a}), Exp({mantissa : b}));
}
/**
* @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 (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 safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2 ** 224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2 ** 32, errorMessage);
return uint32(n);
}
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;
}
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 fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa : div_(mul_(a, doubleScale), b)});
}
}
pragma solidity ^0.5.16;
import "./KToken.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed borrow logics, user can only borrow Kine MCD (see KMCD).
* 4. removed error code propagation mechanism, using revert to fail fast and loudly.
*/
/**
* @title Kine's KErc20 Contract
* @notice KTokens which wrap an EIP-20 underlying
* @author Kine
*/
contract KErc20 is KToken, KErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param controller_ The address of the Controller
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
KineControllerInterface controller_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// KToken initialize does the bulk of the work
super.initialize(controller_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives kTokens in exchange
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mint(uint mintAmount) external returns (uint) {
return mintInternal(mintAmount);
}
/**
* @notice Sender redeems kTokens in exchange for the underlying asset
* @param redeemTokens The number of kTokens to redeem into underlying
*/
function redeem(uint redeemTokens) external {
redeemInternal(redeemTokens);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, TOKEN_TRANSFER_IN_FAILED);
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, TOKEN_TRANSFER_IN_OVERFLOW);
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, TOKEN_TRANSFER_OUT_FAILED);
}
}
pragma solidity ^0.5.16;
import "./KErc20.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20Delegate.sol
*/
/**
* @title Kine's KErc20Delegate Contract
* @notice KTokens which wrap an EIP-20 underlying and are delegated to
* @author Kine
*/
contract KErc20Delegate is KErc20, KDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
import "./KTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed borrow/repay logics. users can only mint/redeem kTokens and borrow Kine MCD (see KMCD).
* 4. removed error code propagation mechanism, using revert to fail fast and loudly.
*/
/**
* @title Kine's KToken Contract
* @notice Abstract base for KTokens
* @author Kine
*/
contract KToken is KTokenInterface, Exponential, KTokenErrorReporter {
modifier onlyAdmin(){
require(msg.sender == admin, "only admin can call this function");
_;
}
/**
* @notice Initialize the money market
* @param controller_ The address of the Controller
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(KineControllerInterface controller_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(initialized == false, "market may only be initialized once");
// Set the controller
_setController(controller_);
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
initialized = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal {
/* Fail if transfer not allowed */
(bool allowed, string memory reason) = controller.transferAllowed(address(this), src, dst, tokens);
require(allowed, reason);
/* Do not allow self-transfers */
require(src != dst, BAD_INPUT);
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(- 1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = startingAllowance.sub(tokens, TRANSFER_NOT_ALLOWED);
uint srcTokensNew = accountTokens[src].sub(tokens, TRANSFER_NOT_ENOUGH);
uint dstTokensNew = accountTokens[dst].add(tokens, TRANSFER_TOO_MUCH);
/////////////////////////
// EFFECTS & INTERACTIONS
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(- 1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
controller.transferVerify(address(this), src, dst, tokens);
}
/**
* @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
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
transferTokens(msg.sender, msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
transferTokens(msg.sender, src, dst, amount);
return true;
}
/**
* @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 (uint256(-1) means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @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 The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get a snapshot of the account's balances
* @dev This is used by controller to more efficiently perform liquidity checks.
* and for kTokens, there is only token balance, for kMCD, there is only borrow balance
* @param account Address of the account to snapshot
* @return (token balance, borrow balance)
*/
function getAccountSnapshot(address account) external view returns (uint, uint) {
return (accountTokens[account], 0);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Get cash balance of this kToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Sender supplies assets into the market and receives kTokens in exchange
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint) {
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives kTokens in exchange
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint) {
/* Fail if mint not allowed */
(bool allowed, string memory reason) = controller.mintAllowed(address(this), minter, mintAmount);
require(allowed, reason);
MintLocalVars memory vars;
/////////////////////////
// EFFECTS & INTERACTIONS
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The kToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the kToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* mintTokens = actualMintAmount
*/
vars.mintTokens = vars.actualMintAmount;
/*
* We calculate the new total supply of kTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
vars.totalSupplyNew = totalSupply.add(vars.mintTokens, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
vars.accountTokensNew = accountTokens[minter].add(vars.mintTokens, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return vars.actualMintAmount;
}
/**
* @notice Sender redeems kTokens in exchange for the underlying asset
* @param redeemTokens The number of kTokens to redeem into underlying
*/
function redeemInternal(uint redeemTokens) internal nonReentrant {
redeemFresh(msg.sender, redeemTokens);
}
struct RedeemLocalVars {
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems kTokens in exchange for the underlying asset
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of kTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn) internal {
require(redeemTokensIn != 0, "redeemTokensIn must not be zero");
RedeemLocalVars memory vars;
/* Fail if redeem not allowed */
(bool allowed, string memory reason) = controller.redeemAllowed(address(this), redeemer, redeemTokensIn);
require(allowed, reason);
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
vars.totalSupplyNew = totalSupply.sub(redeemTokensIn, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
vars.accountTokensNew = accountTokens[redeemer].sub(redeemTokensIn, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);
/* Fail gracefully if protocol has insufficient cash */
require(getCashPrior() >= redeemTokensIn, TOKEN_INSUFFICIENT_CASH);
/////////////////////////
// EFFECTS & INTERACTIONS
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The kToken must handle variations between ERC-20 and ETH underlying.
* On success, the kToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, redeemTokensIn);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), redeemTokensIn);
emit Redeem(redeemer, redeemTokensIn);
/* We call the defense hook */
controller.redeemVerify(address(this), redeemer, redeemTokensIn);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another kToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed kToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of kTokens to seize
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant {
seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another KToken.
* Its absolutely critical to use msg.sender as the seizer kToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed kToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of kTokens to seize
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal {
/* Fail if seize not allowed */
(bool allowed, string memory reason) = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
require(allowed, reason);
/* Fail if borrower = liquidator */
require(borrower != liquidator, INVALID_ACCOUNT_PAIR);
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
uint borrowerTokensNew = accountTokens[borrower].sub(seizeTokens, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED);
uint liquidatorTokensNew = accountTokens[liquidator].add(seizeTokens, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED);
/////////////////////////
// EFFECTS & INTERACTIONS
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() {
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
/**
* @notice Sets a new controller for the market
* @dev Admin function to set a new controller
*/
function _setController(KineControllerInterface newController) public onlyAdmin() {
KineControllerInterface oldController = controller;
// Ensure invoke controller.isController() returns true
require(newController.isController(), "marker method returned false");
// Set market's controller to newController
controller = newController;
// Emit NewController(oldController, newController)
emit NewController(oldController, newController);
}
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true;
// get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
contract KTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice flag that kToken has been initialized;
*/
bool public initialized;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-kToken operations
*/
KineControllerInterface public controller;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
}
contract KTokenInterface is KTokenStorage {
/**
* @notice Indicator that this is a KToken contract (for inspection)
*/
bool public constant isKToken = true;
/*** Market Events ***/
/**
* @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 redeemTokens);
/*** 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 controller is changed
*/
event NewController(KineControllerInterface oldController, KineControllerInterface newController);
/**
* @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);
/*** User Interface ***/
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 getAccountSnapshot(address account) external view returns (uint, uint);
function getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external;
function _acceptAdmin() external;
function _setController(KineControllerInterface newController) public;
}
contract KErc20Storage {
/**
* @notice Underlying asset for this KToken
*/
address public underlying;
}
contract KErc20Interface is KErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external;
}
contract KDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract KDelegatorInterface is KDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract KDelegateInterface is KDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed error code propagation mechanism to fail fast and loudly
*/
contract KineControllerInterface {
/// @notice Indicator that this is a Controller contract (for inspection)
bool public constant isController = true;
/// @notice oracle getter function
function getOracle() external view returns (address);
/*** Assets You Are In ***/
function enterMarkets(address[] calldata kTokens) external;
function exitMarket(address kToken) external;
/*** Policy Hooks ***/
function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory);
function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory);
function redeemVerify(address kToken, address redeemer, uint redeemTokens) external;
function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory);
function borrowVerify(address kToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address kToken,
address payer,
address borrower,
uint repayAmount) external returns (bool, string memory);
function repayBorrowVerify(
address kToken,
address payer,
address borrower,
uint repayAmount) external;
function liquidateBorrowAllowed(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (bool, string memory);
function liquidateBorrowVerify(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (bool, string memory);
function seizeVerify(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory);
function transferVerify(address kToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address kTokenBorrowed,
address kTokenCollateral,
uint repayAmount) external view returns (uint);
}
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.
*/
/**
* Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol
* changes we made:
* 1. add two methods that take errorMessage as input parameter
*/
library KineSafeMath {
/**
* @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 addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
* added by Kine
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
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 multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
* added by Kine
*/
function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
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;
}
} | * @notice Sender redeems kTokens in exchange for the underlying asset @param redeemTokens The number of kTokens to redeem into underlying/ | function redeem(uint redeemTokens) external {
redeemInternal(redeemTokens);
}
| 163,753 | [
1,
12021,
283,
323,
7424,
417,
5157,
316,
7829,
364,
326,
6808,
3310,
225,
283,
24903,
5157,
1021,
1300,
434,
417,
5157,
358,
283,
24903,
1368,
6808,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
283,
24903,
12,
11890,
283,
24903,
5157,
13,
3903,
288,
203,
3639,
283,
24903,
3061,
12,
266,
24903,
5157,
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
] |
pragma solidity ^0.4.21;
// File: zeppelin-solidity/contracts/Ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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;
}
}
// File: zeppelin-solidity/contracts/Ownership/Contactable.sol
/**
* @title Contactable token
* @dev Basic version of a contactable contract, allowing the owner to provide a string with their
* contact information.
*/
contract Contactable is Ownable {
string public contactInformation;
/**
* @dev Allows the owner to set a string with their contact information.
* @param info The contact information to attach to the contract.
*/
function setContactInformation(string info) onlyOwner public {
contactInformation = info;
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
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) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
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;
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);
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);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
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;
MintFinished();
return true;
}
}
// File: contracts/RootsSaleToken.sol
contract RootsSaleToken is Contactable, MintableToken {
string constant public name = "ROOTS Sale Token";
string constant public symbol = "ROOTSSale";
uint constant public decimals = 18;
bool public isTransferable = false;
function transfer(address _to, uint _value) public returns (bool) {
require(isTransferable);
return false;
}
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
require(isTransferable);
return false;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(isTransferable);
return false;
}
function transferFrom(address _from, address _to, uint _value, bytes _data) public returns (bool) {
require(isTransferable);
return false;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: contracts/RootsSale.sol
contract RootsSale is Pausable {
using SafeMath for uint256;
// The token being sold
RootsSaleToken public token;
// start and end timestamps where purchases are allowed (both inclusive)
uint public startTime;
uint public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint public rate;
// amount of raised money in wei
uint public weiRaised;
// amount of tokens that was sold on the crowdsale
uint public tokensSold;
// maximum amount of wei in total, that can be bought
uint public weiMaximumGoal;
// minimum amount of wel, that can be contributed
uint public weiMinimumAmount;
// maximum amount of wei, that can be contributed
uint public weiMaximumAmount;
// How many distinct addresses have bought
uint public buyerCount;
// how much ETH each address has bought to this crowdsale
mapping (address => uint) public boughtAmountOf;
// whether a buyer already bought some tokens
mapping (address => bool) public isBuyer;
// whether a buyer bought tokens through other currencies
mapping (address => bool) public isExternalBuyer;
address public admin;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param tokenAmount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint value,
uint tokenAmount
);
function RootsSale(
uint _startTime,
uint _endTime,
uint _rate,
RootsSaleToken _token,
address _wallet,
uint _weiMaximumGoal,
uint _weiMinimumAmount,
uint _weiMaximumAmount,
address _admin
) public
{
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(address(_token) != 0x0);
require(_wallet != 0x0);
require(_weiMaximumGoal > 0);
require(_admin != 0x0);
startTime = _startTime;
endTime = _endTime;
token = _token;
rate = _rate;
wallet = _wallet;
weiMaximumGoal = _weiMaximumGoal;
weiMinimumAmount = _weiMinimumAmount;
weiMaximumAmount = _weiMaximumAmount;
admin = _admin;
}
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || msg.sender == admin);
_;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public whenNotPaused payable returns (bool) {
uint weiAmount = msg.value;
require(beneficiary != 0x0);
require(weiAmount >= weiMinimumAmount);
require(weiAmount <= weiMaximumAmount);
require(validPurchase(msg.value));
// calculate token amount to be created
uint tokenAmount = calculateTokenAmount(weiAmount, weiRaised);
mintTokenToBuyer(beneficiary, tokenAmount, weiAmount);
wallet.transfer(msg.value);
return true;
}
function mintTokenToBuyer(address beneficiary, uint tokenAmount, uint weiAmount) internal {
if (!isBuyer[beneficiary]) {
// A new buyer
buyerCount++;
isBuyer[beneficiary] = true;
}
boughtAmountOf[beneficiary] = boughtAmountOf[beneficiary].add(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
token.mint(beneficiary, tokenAmount);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);
}
// return true if the transaction can buy tokens
function validPurchase(uint weiAmount) internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool withinCap = weiRaised.add(weiAmount) <= weiMaximumGoal;
return withinPeriod && withinCap;
}
// return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= weiMaximumGoal;
bool afterEndTime = now > endTime;
return capReached || afterEndTime;
}
// get the amount of unsold tokens allocated to this contract;
function getWeiLeft() external constant returns (uint) {
return weiMaximumGoal - weiRaised;
}
// allows to update tokens rate for owner
function setPricingStrategy(
uint _startTime,
uint _endTime,
uint _rate,
uint _weiMaximumGoal,
uint _weiMinimumAmount,
uint _weiMaximumAmount
) external onlyOwner returns (bool) {
require(!hasEnded());
require(_endTime >= _startTime);
require(_weiMaximumGoal > 0);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
weiMaximumGoal = _weiMaximumGoal;
weiMinimumAmount = _weiMinimumAmount;
weiMaximumAmount = _weiMaximumAmount;
return true;
}
function registerPayment(address beneficiary, uint tokenAmount, uint weiAmount) public onlyOwnerOrAdmin {
require(validPurchase(weiAmount));
isExternalBuyer[beneficiary] = true;
mintTokenToBuyer(beneficiary, tokenAmount, weiAmount);
}
function registerPayments(address[] beneficiaries, uint[] tokenAmounts, uint[] weiAmounts) external onlyOwnerOrAdmin {
require(beneficiaries.length == tokenAmounts.length);
require(tokenAmounts.length == weiAmounts.length);
for (uint i = 0; i < beneficiaries.length; i++) {
registerPayment(beneficiaries[i], tokenAmounts[i], weiAmounts[i]);
}
}
function setAdmin(address adminAddress) external onlyOwner {
admin = adminAddress;
}
/** Calculate the current price for buy in amount. */
function calculateTokenAmount(uint weiAmount, uint weiRaised) public view returns (uint tokenAmount) {
return weiAmount.mul(rate);
}
function changeTokenOwner(address newOwner) external onlyOwner {
require(newOwner != 0x0);
require(hasEnded());
token.transferOwnership(newOwner);
}
function finishMinting() public onlyOwnerOrAdmin {
require(hasEnded());
token.finishMinting();
}
} | The token being sold start and end timestamps where purchases are allowed (both inclusive) address where funds are collected how many token units a buyer gets per wei amount of raised money in wei amount of tokens that was sold on the crowdsale maximum amount of wei in total, that can be bought minimum amount of wel, that can be contributed maximum amount of wei, that can be contributed How many distinct addresses have bought how much ETH each address has bought to this crowdsale whether a buyer already bought some tokens whether a buyer bought tokens through other currencies | contract RootsSale is Pausable {
using SafeMath for uint256;
RootsSaleToken public token;
uint public startTime;
uint public endTime;
address public wallet;
uint public rate;
uint public weiRaised;
uint public tokensSold;
uint public weiMaximumGoal;
uint public weiMinimumAmount;
uint public weiMaximumAmount;
uint public buyerCount;
mapping (address => uint) public boughtAmountOf;
mapping (address => bool) public isBuyer;
mapping (address => bool) public isExternalBuyer;
address public admin;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint value,
uint tokenAmount
);
function RootsSale(
uint _startTime,
uint _endTime,
uint _rate,
RootsSaleToken _token,
address _wallet,
uint _weiMaximumGoal,
uint _weiMinimumAmount,
uint _weiMaximumAmount,
address _admin
) public
{
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(address(_token) != 0x0);
require(_wallet != 0x0);
require(_weiMaximumGoal > 0);
require(_admin != 0x0);
startTime = _startTime;
endTime = _endTime;
token = _token;
rate = _rate;
wallet = _wallet;
weiMaximumGoal = _weiMaximumGoal;
weiMinimumAmount = _weiMinimumAmount;
weiMaximumAmount = _weiMaximumAmount;
admin = _admin;
}
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || msg.sender == admin);
_;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public whenNotPaused payable returns (bool) {
uint weiAmount = msg.value;
require(beneficiary != 0x0);
require(weiAmount >= weiMinimumAmount);
require(weiAmount <= weiMaximumAmount);
require(validPurchase(msg.value));
uint tokenAmount = calculateTokenAmount(weiAmount, weiRaised);
mintTokenToBuyer(beneficiary, tokenAmount, weiAmount);
wallet.transfer(msg.value);
return true;
}
function mintTokenToBuyer(address beneficiary, uint tokenAmount, uint weiAmount) internal {
if (!isBuyer[beneficiary]) {
buyerCount++;
isBuyer[beneficiary] = true;
}
boughtAmountOf[beneficiary] = boughtAmountOf[beneficiary].add(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
token.mint(beneficiary, tokenAmount);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);
}
function mintTokenToBuyer(address beneficiary, uint tokenAmount, uint weiAmount) internal {
if (!isBuyer[beneficiary]) {
buyerCount++;
isBuyer[beneficiary] = true;
}
boughtAmountOf[beneficiary] = boughtAmountOf[beneficiary].add(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
token.mint(beneficiary, tokenAmount);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);
}
function validPurchase(uint weiAmount) internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool withinCap = weiRaised.add(weiAmount) <= weiMaximumGoal;
return withinPeriod && withinCap;
}
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= weiMaximumGoal;
bool afterEndTime = now > endTime;
return capReached || afterEndTime;
}
function getWeiLeft() external constant returns (uint) {
return weiMaximumGoal - weiRaised;
}
function setPricingStrategy(
uint _startTime,
uint _endTime,
uint _rate,
uint _weiMaximumGoal,
uint _weiMinimumAmount,
uint _weiMaximumAmount
) external onlyOwner returns (bool) {
require(!hasEnded());
require(_endTime >= _startTime);
require(_weiMaximumGoal > 0);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
weiMaximumGoal = _weiMaximumGoal;
weiMinimumAmount = _weiMinimumAmount;
weiMaximumAmount = _weiMaximumAmount;
return true;
}
function registerPayment(address beneficiary, uint tokenAmount, uint weiAmount) public onlyOwnerOrAdmin {
require(validPurchase(weiAmount));
isExternalBuyer[beneficiary] = true;
mintTokenToBuyer(beneficiary, tokenAmount, weiAmount);
}
function registerPayments(address[] beneficiaries, uint[] tokenAmounts, uint[] weiAmounts) external onlyOwnerOrAdmin {
require(beneficiaries.length == tokenAmounts.length);
require(tokenAmounts.length == weiAmounts.length);
for (uint i = 0; i < beneficiaries.length; i++) {
registerPayment(beneficiaries[i], tokenAmounts[i], weiAmounts[i]);
}
}
function registerPayments(address[] beneficiaries, uint[] tokenAmounts, uint[] weiAmounts) external onlyOwnerOrAdmin {
require(beneficiaries.length == tokenAmounts.length);
require(tokenAmounts.length == weiAmounts.length);
for (uint i = 0; i < beneficiaries.length; i++) {
registerPayment(beneficiaries[i], tokenAmounts[i], weiAmounts[i]);
}
}
function setAdmin(address adminAddress) external onlyOwner {
admin = adminAddress;
}
function calculateTokenAmount(uint weiAmount, uint weiRaised) public view returns (uint tokenAmount) {
return weiAmount.mul(rate);
}
function changeTokenOwner(address newOwner) external onlyOwner {
require(newOwner != 0x0);
require(hasEnded());
token.transferOwnership(newOwner);
}
function finishMinting() public onlyOwnerOrAdmin {
require(hasEnded());
token.finishMinting();
}
} | 1,427,873 | [
1,
1986,
1147,
3832,
272,
1673,
787,
471,
679,
11267,
1625,
5405,
343,
3304,
854,
2935,
261,
18237,
13562,
13,
1758,
1625,
284,
19156,
854,
12230,
3661,
4906,
1147,
4971,
279,
27037,
5571,
1534,
732,
77,
3844,
434,
11531,
15601,
316,
732,
77,
3844,
434,
2430,
716,
1703,
272,
1673,
603,
326,
276,
492,
2377,
5349,
4207,
3844,
434,
732,
77,
316,
2078,
16,
716,
848,
506,
800,
9540,
5224,
3844,
434,
341,
292,
16,
716,
848,
506,
356,
11050,
4207,
3844,
434,
732,
77,
16,
716,
848,
506,
356,
11050,
9017,
4906,
10217,
6138,
1240,
800,
9540,
3661,
9816,
512,
2455,
1517,
1758,
711,
800,
9540,
358,
333,
276,
492,
2377,
5349,
2856,
279,
27037,
1818,
800,
9540,
2690,
2430,
2856,
279,
27037,
800,
9540,
2430,
3059,
1308,
19239,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7450,
87,
30746,
353,
21800,
16665,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
7450,
87,
30746,
1345,
1071,
1147,
31,
203,
203,
225,
2254,
1071,
8657,
31,
203,
225,
2254,
1071,
13859,
31,
203,
203,
225,
1758,
1071,
9230,
31,
203,
203,
225,
2254,
1071,
4993,
31,
203,
203,
225,
2254,
1071,
732,
77,
12649,
5918,
31,
203,
203,
225,
2254,
1071,
2430,
55,
1673,
31,
203,
203,
225,
2254,
1071,
732,
77,
13528,
27716,
31,
203,
203,
225,
2254,
1071,
732,
77,
13042,
6275,
31,
203,
203,
225,
2254,
1071,
732,
77,
13528,
6275,
31,
203,
203,
225,
2254,
1071,
27037,
1380,
31,
203,
203,
225,
2874,
261,
2867,
516,
2254,
13,
1071,
800,
9540,
6275,
951,
31,
203,
203,
225,
2874,
261,
2867,
516,
1426,
13,
1071,
27057,
16213,
31,
203,
203,
225,
2874,
261,
2867,
516,
1426,
13,
1071,
353,
6841,
38,
16213,
31,
203,
203,
225,
1758,
1071,
3981,
31,
203,
203,
225,
871,
3155,
23164,
12,
203,
1377,
1758,
8808,
5405,
343,
14558,
16,
203,
1377,
1758,
8808,
27641,
74,
14463,
814,
16,
203,
1377,
2254,
460,
16,
203,
1377,
2254,
1147,
6275,
203,
225,
11272,
203,
203,
225,
445,
7450,
87,
30746,
12,
203,
1377,
2254,
389,
1937,
950,
16,
203,
1377,
2254,
389,
409,
950,
16,
203,
1377,
2254,
389,
5141,
16,
203,
1377,
7450,
87,
30746,
1345,
389,
2316,
16,
203,
1377,
1758,
389,
19177,
16,
203,
1377,
2254,
389,
1814,
77,
13528,
27716,
16,
203,
1377,
2254,
389,
2
] |
pragma solidity ^0.4.18;
import './TogetherToken.sol';
import 'zeppelin-solidity/contracts/crowdsale/CappedCrowdsale.sol';
import 'zeppelin-solidity/contracts/crowdsale/RefundableCrowdsale.sol';
// ================
// As we get more familiar with OpenZeppelin we MUST make sure Tokens cannot
// be transferred until the crowdsale is over.
// ================
contract TogetherCrowdsale is CappedCrowdsale, RefundableCrowdsale {
// ICO Stage
// ============
enum CrowdsaleStage { PreICO, ICO }
CrowdsaleStage public stage = CrowdsaleStage.PreICO; // By default it's Pre Sale
// =============
// Token Distribution
// =============================
uint256 public maxTokens = 200000000000000000000000000; // There will be total 200,000,000 TOG
uint256 public tokensForEcosystem = 30000000000000000000000000 ; // 15% TOG
uint256 public tokensForTeam = 12000000000000000000000000; // 6% TOG
uint256 public tokensForBounty = 8000000000000000000000000; // 4% TOG (ICO assistance)
uint256 public totalTokensForSale = 70000000000000000000000000; // 70m TOG will be sold in Crowdsale
uint256 public totalTokensForSaleDuringPreICO = 80000000000000000000000000; // 80m TOG will be sold during PreICO
// ==============================
// Amount raised in PreICO
// ==================
uint256 public totalWeiRaisedDuringPreICO;
// ===================
// Events
event EthTransferred(string text);
event EthRefunded(string text);
// Constructor
// ============
function TogetherCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _goal, uint256 _cap) CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) public {
require(_goal <= _cap);
}
// =============
// Token Deployment
// =================
function createTokenContract() internal returns (MintableToken) {
return new TogetherToken(); // Deploys the ERC20 token. Automatically called when crowdsale contract is deployed
}
// ==================
// Crowdsale Stage Management
// =========================================================
// Change Crowdsale Stage. Available Options: PreICO, ICO
function setCrowdsaleStage(uint value) public onlyOwner {
CrowdsaleStage _stage;
if (uint(CrowdsaleStage.PreICO) == value) {
_stage = CrowdsaleStage.PreICO;
} else if (uint(CrowdsaleStage.ICO) == value) {
_stage = CrowdsaleStage.ICO;
}
stage = _stage;
if (stage == CrowdsaleStage.PreICO) {
setCurrentRate(2); // this is a 100% we will need a 30% bonus
} else if (stage == CrowdsaleStage.ICO) {
setCurrentRate(1); // no bonus in the public sale
}
}
// Change the current rate
// @todo: would we want to be able to do this?
function setCurrentRate(uint256 _rate) private {
rate = _rate;
}
// ================ Stage Management Over =====================
// Token Purchase
// =========================
function () external payable {
uint256 tokensThatWillBeMintedAfterPurchase = msg.value.mul(rate);
if ((stage == CrowdsaleStage.PreICO) && (token.totalSupply() + tokensThatWillBeMintedAfterPurchase > totalTokensForSaleDuringPreICO)) {
msg.sender.transfer(msg.value); // Refund them
EthRefunded("PreICO Limit Hit");
return;
}
buyTokens(msg.sender);
if (stage == CrowdsaleStage.PreICO) {
totalWeiRaisedDuringPreICO = totalWeiRaisedDuringPreICO.add(msg.value);
}
}
function forwardFunds() internal {
if (stage == CrowdsaleStage.PreICO) {
wallet.transfer(msg.value);
EthTransferred("forwarding funds to wallet");
} else if (stage == CrowdsaleStage.ICO) {
EthTransferred("forwarding funds to refundable vault");
super.forwardFunds();
}
}
// ===========================
// Finish: Mint Extra Tokens as needed before finalizing the Crowdsale.
// We'll be probably burning in here because this example mints the full amount
// We would be probably making the team, ecosystem and bounty allocations before the pre-sale
// ====================================================================
function finish(address _teamFund, address _ecosystemFund, address _bountyFund) public onlyOwner {
require(!isFinalized);
uint256 alreadyMinted = token.totalSupply();
require(alreadyMinted < maxTokens);
uint256 unsoldTokens = totalTokensForSale - alreadyMinted;
if (unsoldTokens > 0) {
tokensForEcosystem = tokensForEcosystem + unsoldTokens;
}
token.mint(_teamFund,tokensForTeam);
token.mint(_ecosystemFund,tokensForEcosystem);
token.mint(_bountyFund,tokensForBounty);
finalize();
}
// ===============================
// REMOVE THIS FUNCTION ONCE YOU ARE READY FOR PRODUCTION
// USEFUL FOR TESTING `finish()` FUNCTION
// it is overriding the function on super
function hasEnded() public view returns (bool) {
return true;
}
} | REMOVE THIS FUNCTION ONCE YOU ARE READY FOR PRODUCTION USEFUL FOR TESTING `finish()` FUNCTION it is overriding the function on super | function hasEnded() public view returns (bool) {
return true;
}
| 14,107,877 | [
1,
22122,
20676,
13690,
6229,
1441,
1624,
26556,
432,
862,
10746,
61,
12108,
11770,
1212,
27035,
14988,
42,
1506,
12108,
22130,
1360,
1375,
13749,
20338,
13690,
518,
353,
19488,
326,
445,
603,
2240,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
711,
28362,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "../ManagerProxyTarget.sol";
import "./IBondingManager.sol";
import "../libraries/SortedDoublyLL.sol";
import "../libraries/MathUtils.sol";
import "../libraries/PreciseMathUtils.sol";
import "./libraries/EarningsPool.sol";
import "./libraries/EarningsPoolLIP36.sol";
import "../token/ILivepeerToken.sol";
import "../token/IMinter.sol";
import "../rounds/IRoundsManager.sol";
import "../snapshots/IMerkleSnapshot.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title BondingManager
* @notice Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol
*/
contract BondingManager is ManagerProxyTarget, IBondingManager {
using SafeMath for uint256;
using SortedDoublyLL for SortedDoublyLL.Data;
using EarningsPool for EarningsPool.Data;
using EarningsPoolLIP36 for EarningsPool.Data;
// Constants
// Occurances are replaced at compile time
// and computed to a single value if possible by the optimizer
uint256 constant MAX_FUTURE_ROUND = 2**256 - 1;
// Time between unbonding and possible withdrawl in rounds
uint64 public unbondingPeriod;
// Represents a transcoder's current state
struct Transcoder {
uint256 lastRewardRound; // Last round that the transcoder called reward
uint256 rewardCut; // % of reward paid to transcoder by a delegator
uint256 feeShare; // % of fees paid to delegators by transcoder
mapping(uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round
uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active
uint256 activationRound; // Round in which the transcoder became active - 0 if inactive
uint256 deactivationRound; // Round in which the transcoder will become inactive
uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round
uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut).
uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share)
uint256 lastFeeRound; // Latest round in which the transcoder received fees
}
// The various states a transcoder can be in
enum TranscoderStatus {
NotRegistered,
Registered
}
// Represents a delegator's current state
struct Delegator {
uint256 bondedAmount; // The amount of bonded tokens
uint256 fees; // The amount of fees collected
address delegateAddress; // The address delegated to
uint256 delegatedAmount; // The amount of tokens delegated to the delegator
uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone
uint256 lastClaimRound; // The last round during which the delegator claimed its earnings
uint256 nextUnbondingLockId; // ID for the next unbonding lock created
mapping(uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock
}
// The various states a delegator can be in
enum DelegatorStatus {
Pending,
Bonded,
Unbonded
}
// Represents an amount of tokens that are being unbonded
struct UnbondingLock {
uint256 amount; // Amount of tokens being unbonded
uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn
}
// Keep track of the known transcoders and delegators
mapping(address => Delegator) private delegators;
mapping(address => Transcoder) private transcoders;
// The total active stake (sum of the stake of active set members) for the current round
uint256 public currentRoundTotalActiveStake;
// The total active stake (sum of the stake of active set members) for the next round
uint256 public nextRoundTotalActiveStake;
// The transcoder pool is used to keep track of the transcoders that are eligible for activation.
// The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders
// in the pool are locked into the active set for round N + 1
SortedDoublyLL.Data private transcoderPool;
// Check if sender is TicketBroker
modifier onlyTicketBroker() {
_onlyTicketBroker();
_;
}
// Check if sender is RoundsManager
modifier onlyRoundsManager() {
_onlyRoundsManager();
_;
}
// Check if sender is Verifier
modifier onlyVerifier() {
_onlyVerifier();
_;
}
// Check if current round is initialized
modifier currentRoundInitialized() {
_currentRoundInitialized();
_;
}
// Automatically claim earnings from lastClaimRound through the current round
modifier autoClaimEarnings() {
_autoClaimEarnings();
_;
}
/**
* @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address
* @dev This constructor will not initialize any state variables besides `controller`. The following setter functions
* should be used to initialize state variables post-deployment:
* - setUnbondingPeriod()
* - setNumActiveTranscoders()
* - setMaxEarningsClaimsRounds()
* @param _controller Address of Controller that this contract will be registered with
*/
constructor(address _controller) Manager(_controller) {}
/**
* @notice Set unbonding period. Only callable by Controller owner
* @param _unbondingPeriod Rounds between unbonding and possible withdrawal
*/
function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner {
unbondingPeriod = _unbondingPeriod;
emit ParameterUpdate("unbondingPeriod");
}
/**
* @notice Set maximum number of active transcoders. Only callable by Controller owner
* @param _numActiveTranscoders Number of active transcoders
*/
function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner {
transcoderPool.setMaxSize(_numActiveTranscoders);
emit ParameterUpdate("numActiveTranscoders");
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
*/
function transcoder(uint256 _rewardCut, uint256 _feeShare) external {
transcoderWithHint(_rewardCut, _feeShare, address(0), address(0));
}
/**
* @notice Delegate stake towards a specific address
* @param _amount The amount of tokens to stake
* @param _to The address of the transcoder to stake towards
*/
function bond(uint256 _amount, address _to) external {
bondWithHint(_amount, _to, address(0), address(0), address(0), address(0));
}
/**
* @notice Unbond an amount of the delegator's bonded stake
* @param _amount Amount of tokens to unbond
*/
function unbond(uint256 _amount) external {
unbondWithHint(_amount, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebond(uint256 _unbondingLockId) external {
rebondWithHint(_unbondingLockId, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external {
rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0));
}
/**
* @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period
* @param _unbondingLockId ID of unbonding lock to withdraw with
*/
function withdrawStake(uint256 _unbondingLockId) external whenSystemNotPaused currentRoundInitialized {
Delegator storage del = delegators[msg.sender];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID");
require(
lock.withdrawRound <= roundsManager().currentRound(),
"withdraw round must be before or equal to the current round"
);
uint256 amount = lock.amount;
uint256 withdrawRound = lock.withdrawRound;
// Delete unbonding lock
delete del.unbondingLocks[_unbondingLockId];
// Tell Minter to transfer stake (LPT) to the delegator
minter().trustedTransferTokens(msg.sender, amount);
emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound);
}
/**
* @notice Withdraws fees to the caller
*/
function withdrawFees(address payable _recipient, uint256 _amount)
external
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(_recipient != address(0), "invalid recipient");
uint256 fees = delegators[msg.sender].fees;
require(fees >= _amount, "insufficient fees to withdraw");
delegators[msg.sender].fees = fees.sub(_amount);
// Tell Minter to transfer fees (ETH) to the address
minter().trustedWithdrawETH(_recipient, _amount);
emit WithdrawFees(msg.sender, _recipient, _amount);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators
*/
function reward() external {
rewardWithHint(address(0), address(0));
}
/**
* @notice Update transcoder's fee pool. Only callable by the TicketBroker
* @param _transcoder Transcoder address
* @param _fees Fees to be added to the fee pool
*/
function updateTranscoderWithFees(
address _transcoder,
uint256 _fees,
uint256 _round
) external whenSystemNotPaused onlyTicketBroker {
// Silence unused param compiler warning
_round;
require(isRegisteredTranscoder(_transcoder), "transcoder must be registered");
uint256 currentRound = roundsManager().currentRound();
Transcoder storage t = transcoders[_transcoder];
uint256 lastRewardRound = t.lastRewardRound;
uint256 activeCumulativeRewards = t.activeCumulativeRewards;
// LIP-36: Add fees for the current round instead of '_round'
// https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1));
// if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake'
// on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected
// for cumulative fee calculation this would result in division by zero.
if (currentRound > lastRewardRound) {
earningsPool.setCommission(t.rewardCut, t.feeShare);
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not
// yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its
// current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become
// the transcoder's activeCumulativeRewards if it calls reward() later on in the current round
activeCumulativeRewards = t.cumulativeRewards;
}
uint256 totalStake = earningsPool.totalStake;
if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) {
// if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call)
// retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder)
// based on rewards for currentRound
IMinter mtr = minter();
uint256 rewards = PreciseMathUtils.percOf(
mtr.currentMintableTokens().add(mtr.currentMintedTokens()),
totalStake,
currentRoundTotalActiveStake
);
uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards);
prevEarningsPool.cumulativeRewardFactor = PreciseMathUtils.percOf(
earningsPool.cumulativeRewardFactor,
totalStake,
delegatorsRewards.add(totalStake)
);
}
uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare);
uint256 transcoderCommissionFees = _fees.sub(delegatorsFees);
// Calculate the fees earned by the transcoder's earned rewards
uint256 transcoderRewardStakeFees = PreciseMathUtils.percOf(
delegatorsFees,
activeCumulativeRewards,
totalStake
);
// Track fees earned by the transcoder based on its earned rewards and feeShare
t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees);
// Update cumulative fee factor with new fees
// The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated)
// Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field
earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees);
t.lastFeeRound = currentRound;
}
/**
* @notice Slash a transcoder. Only callable by the Verifier
* @param _transcoder Transcoder address
* @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder
* @param _slashAmount Percentage of transcoder bond to be slashed
* @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder
*/
function slashTranscoder(
address _transcoder,
address _finder,
uint256 _slashAmount,
uint256 _finderFee
) external whenSystemNotPaused onlyVerifier {
Delegator storage del = delegators[_transcoder];
if (del.bondedAmount > 0) {
uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount);
// If active transcoder, resign it
if (transcoderPool.contains(_transcoder)) {
resignTranscoder(_transcoder);
}
// Decrease bonded stake
del.bondedAmount = del.bondedAmount.sub(penalty);
// If still bonded decrease delegate's delegated amount
if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) {
delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(
penalty
);
}
// Account for penalty
uint256 burnAmount = penalty;
// Award finder fee if there is a finder address
if (_finder != address(0)) {
uint256 finderAmount = MathUtils.percOf(penalty, _finderFee);
minter().trustedTransferTokens(_finder, finderAmount);
// Minter burns the slashed funds - finder reward
minter().trustedBurnTokens(burnAmount.sub(finderAmount));
emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount);
} else {
// Minter burns the slashed funds
minter().trustedBurnTokens(burnAmount);
emit TranscoderSlashed(_transcoder, address(0), penalty, 0);
}
} else {
emit TranscoderSlashed(_transcoder, _finder, 0, 0);
}
}
/**
* @notice Claim token pools shares for a delegator from its lastClaimRound through the end round
* @param _endRound The last round for which to claim token pools shares for a delegator
*/
function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized {
// Silence unused param compiler warning
_endRound;
_autoClaimEarnings();
}
/**
* @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager
*/
function setCurrentRoundTotalActiveStake() external onlyRoundsManager {
currentRoundTotalActiveStake = nextRoundTotalActiveStake;
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the
* caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will
* be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed.
* See SortedDoublyLL.sol for details on list hints
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
* @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool
* @param _newPosNext Address of next transcoder in pool if the caller joins the pool
*/
function transcoderWithHint(
uint256 _rewardCut,
uint256 _feeShare,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized {
require(!roundsManager().currentRoundLocked(), "can't update transcoder params, current round is locked");
require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage");
require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage");
require(isRegisteredTranscoder(msg.sender), "transcoder must be registered");
Transcoder storage t = transcoders[msg.sender];
uint256 currentRound = roundsManager().currentRound();
require(
!isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound,
"caller can't be active or must have already called reward for the current round"
);
t.rewardCut = _rewardCut;
t.feeShare = _feeShare;
if (!transcoderPool.contains(msg.sender)) {
tryToJoinActiveSet(
msg.sender,
delegators[msg.sender].delegatedAmount,
currentRound.add(1),
_newPosPrev,
_newPosNext
);
}
emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare);
}
/**
* @notice Delegates stake "on behalf of" another address towards a specific address
* and updates the transcoder pool using optional list hints if needed
* @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint
* for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params.
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _amount The amount of tokens to stake.
* @param _owner The address of the owner of the bond
* @param _to The address of the transcoder to stake towards
* @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate
* @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate
* @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate
* @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate
*/
function bondForWithHint(
uint256 _amount,
address _owner,
address _to,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _currDelegateNewPosPrev,
address _currDelegateNewPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
Delegator storage del = delegators[_owner];
uint256 currentRound = roundsManager().currentRound();
// Amount to delegate
uint256 delegationAmount = _amount;
// Current delegate
address currentDelegate = del.delegateAddress;
// Current bonded amount
uint256 currentBondedAmount = del.bondedAmount;
if (delegatorStatus(_owner) == DelegatorStatus.Unbonded) {
// New delegate
// Set start round
// Don't set start round if delegator is in pending state because the start round would not change
del.startRound = currentRound.add(1);
// Unbonded state = no existing delegate and no bonded stake
// Thus, delegation amount = provided amount
} else if (currentBondedAmount > 0 && currentDelegate != _to) {
// A registered transcoder cannot delegate its bonded stake toward another address
// because it can only be delegated toward itself
// In the future, if delegation towards another registered transcoder as an already
// registered transcoder becomes useful (i.e. for transitive delegation), this restriction
// could be removed
require(!isRegisteredTranscoder(_owner), "registered transcoders can't delegate towards other addresses");
// Changing delegate
// Set start round
del.startRound = currentRound.add(1);
// Update amount to delegate with previous delegation amount
delegationAmount = delegationAmount.add(currentBondedAmount);
decreaseTotalStake(currentDelegate, currentBondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext);
}
{
Transcoder storage newDelegate = transcoders[_to];
EarningsPool.Data storage currPool = newDelegate.earningsPoolPerRound[currentRound];
if (currPool.cumulativeRewardFactor == 0) {
currPool.cumulativeRewardFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastRewardRound)
.cumulativeRewardFactor;
}
if (currPool.cumulativeFeeFactor == 0) {
currPool.cumulativeFeeFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastFeeRound)
.cumulativeFeeFactor;
}
}
// cannot delegate to someone without having bonded stake
require(delegationAmount > 0, "delegation amount must be greater than 0");
// Update delegate
del.delegateAddress = _to;
// Update bonded amount
del.bondedAmount = currentBondedAmount.add(_amount);
increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext);
if (_amount > 0) {
// Transfer the LPT to the Minter
livepeerToken().transferFrom(msg.sender, address(minter()), _amount);
}
emit Bond(_to, currentDelegate, _owner, _amount, del.bondedAmount);
}
/**
* @notice Delegates stake towards a specific address and updates the transcoder pool using optional list hints if needed
* @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint
* for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params.
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _amount The amount of tokens to stake.
* @param _to The address of the transcoder to stake towards
* @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate
* @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate
* @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate
* @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate
*/
function bondWithHint(
uint256 _amount,
address _to,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _currDelegateNewPosPrev,
address _currDelegateNewPosNext
) public {
bondForWithHint(
_amount,
msg.sender,
_to,
_oldDelegateNewPosPrev,
_oldDelegateNewPosNext,
_currDelegateNewPosPrev,
_currDelegateNewPosNext
);
}
/**
* @notice Transfers ownership of a bond to a new delegator using optional hints if needed
*
* If the receiver is already bonded to a different delegate than the bond owner then the stake goes
* to the receiver's delegate otherwise the receiver's delegate is set as the owner's delegate
*
* @dev If the original delegate is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the target delegate is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_newDelegateNewPosPrev` and `_newDelegateNewPosNext` params.
*
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _delegator Receiver of the bond
* @param _amount Portion of the bond to transfer to receiver
* @param _oldDelegateNewPosPrev Address of previous transcoder in pool if the delegate remains in the pool
* @param _oldDelegateNewPosNext Address of next transcoder in pool if the delegate remains in the pool
* @param _newDelegateNewPosPrev Address of previous transcoder in pool if the delegate is in the pool
* @param _newDelegateNewPosNext Address of next transcoder in pool if the delegate is in the pool
*/
function transferBond(
address _delegator,
uint256 _amount,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _newDelegateNewPosPrev,
address _newDelegateNewPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
Delegator storage oldDel = delegators[msg.sender];
// Cache delegate address of caller before unbondWithHint because
// if unbondWithHint is for a full unbond the caller's delegate address will be set to null
address oldDelDelegate = oldDel.delegateAddress;
unbondWithHint(_amount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext);
Delegator storage newDel = delegators[_delegator];
uint256 oldDelUnbondingLockId = oldDel.nextUnbondingLockId.sub(1);
uint256 withdrawRound = oldDel.unbondingLocks[oldDelUnbondingLockId].withdrawRound;
// Burn lock for current owner
delete oldDel.unbondingLocks[oldDelUnbondingLockId];
// Create lock for new owner
uint256 newDelUnbondingLockId = newDel.nextUnbondingLockId;
newDel.unbondingLocks[newDelUnbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound });
newDel.nextUnbondingLockId = newDel.nextUnbondingLockId.add(1);
emit TransferBond(msg.sender, _delegator, oldDelUnbondingLockId, newDelUnbondingLockId, _amount);
// Claim earnings for receiver before processing unbonding lock
uint256 currentRound = roundsManager().currentRound();
uint256 lastClaimRound = newDel.lastClaimRound;
if (lastClaimRound < currentRound) {
updateDelegatorWithEarnings(_delegator, currentRound, lastClaimRound);
}
// Rebond lock for new owner
if (newDel.delegateAddress == address(0)) {
newDel.delegateAddress = oldDelDelegate;
}
// Move to Pending state if receiver is currently in Unbonded state
if (delegatorStatus(_delegator) == DelegatorStatus.Unbonded) {
newDel.startRound = currentRound.add(1);
}
// Process rebond using unbonding lock
processRebond(_delegator, newDelUnbondingLockId, _newDelegateNewPosPrev, _newDelegateNewPosNext);
}
/**
* @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed
* @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _amount Amount of tokens to unbond
* @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool
* @param _newPosNext Address of next transcoder in pool if the caller remains in the pool
*/
function unbondWithHint(
uint256 _amount,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded");
Delegator storage del = delegators[msg.sender];
require(_amount > 0, "unbond amount must be greater than 0");
require(_amount <= del.bondedAmount, "amount is greater than bonded amount");
address currentDelegate = del.delegateAddress;
uint256 currentRound = roundsManager().currentRound();
uint256 withdrawRound = currentRound.add(unbondingPeriod);
uint256 unbondingLockId = del.nextUnbondingLockId;
// Create new unbonding lock
del.unbondingLocks[unbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound });
// Increment ID for next unbonding lock
del.nextUnbondingLockId = unbondingLockId.add(1);
// Decrease delegator's bonded amount
del.bondedAmount = del.bondedAmount.sub(_amount);
if (del.bondedAmount == 0) {
// Delegator no longer delegated to anyone if it does not have a bonded amount
del.delegateAddress = address(0);
// Delegator does not have a start round if it is no longer delegated to anyone
del.startRound = 0;
if (transcoderPool.contains(msg.sender)) {
resignTranscoder(msg.sender);
}
}
// If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount
decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext);
emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates
* the transcoder pool using an optional list hint if needed
* @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is in the pool
*/
function rebondWithHint(
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded");
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using
* an optional list hint if needed
* @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate joins the pool
*/
function rebondFromUnbondedWithHint(
address _to,
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded");
// Set delegator's start round and transition into Pending state
delegators[msg.sender].startRound = roundsManager().currentRound().add(1);
// Set delegator's delegate
delegators[msg.sender].delegateAddress = _to;
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed
* @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool
* @param _newPosNext Address of next transcoder in pool if the caller is in the pool
*/
function rewardWithHint(address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
{
uint256 currentRound = roundsManager().currentRound();
require(isActiveTranscoder(msg.sender), "caller must be an active transcoder");
require(
transcoders[msg.sender].lastRewardRound != currentRound,
"caller has already called reward for the current round"
);
Transcoder storage t = transcoders[msg.sender];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
// Set last round that transcoder called reward
earningsPool.setCommission(t.rewardCut, t.feeShare);
// If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round
// the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized
// Thus we sync the the transcoder's stake to when it was last updated
// 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// Create reward based on active transcoder's stake relative to the total active stake
// rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake
uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake);
updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext);
// Set last round that transcoder called reward
t.lastRewardRound = currentRound;
emit Reward(msg.sender, rewardTokens);
}
/**
* @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending stake from
* @return Pending bonded stake for '_delegator' since last claiming rewards
*/
function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) {
// Silence unused param compiler warning
_endRound;
uint256 endRound = roundsManager().currentRound();
(uint256 stake, ) = pendingStakeAndFees(_delegator, endRound);
return stake;
}
/**
* @notice Returns pending fees for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending fees from
* @return Pending fees for '_delegator' since last claiming fees
*/
function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) {
// Silence unused param compiler warning
_endRound;
uint256 endRound = roundsManager().currentRound();
(, uint256 fees) = pendingStakeAndFees(_delegator, endRound);
return fees;
}
/**
* @notice Returns total bonded stake for a transcoder
* @param _transcoder Address of transcoder
* @return total bonded stake for a delegator
*/
function transcoderTotalStake(address _transcoder) public view returns (uint256) {
return delegators[_transcoder].delegatedAmount;
}
/**
* @notice Computes transcoder status
* @param _transcoder Address of transcoder
* @return registered or not registered transcoder status
*/
function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) {
if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered;
return TranscoderStatus.NotRegistered;
}
/**
* @notice Computes delegator status
* @param _delegator Address of delegator
* @return bonded, unbonded or pending delegator status
*/
function delegatorStatus(address _delegator) public view returns (DelegatorStatus) {
Delegator storage del = delegators[_delegator];
if (del.bondedAmount == 0) {
// Delegator unbonded all its tokens
return DelegatorStatus.Unbonded;
} else if (del.startRound > roundsManager().currentRound()) {
// Delegator round start is in the future
return DelegatorStatus.Pending;
} else {
// Delegator round start is now or in the past
// del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which
// would trigger the first if clause
return DelegatorStatus.Bonded;
}
}
/**
* @notice Return transcoder information
* @param _transcoder Address of transcoder
* @return lastRewardRound Trancoder's last reward round
* @return rewardCut Transcoder's reward cut
* @return feeShare Transcoder's fee share
* @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active
* @return activationRound Round in which transcoder became active
* @return deactivationRound Round in which transcoder will no longer be active
* @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active
* @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut)
* @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share)
* @return lastFeeRound Latest round that the transcoder received fees
*/
function getTranscoder(address _transcoder)
public
view
returns (
uint256 lastRewardRound,
uint256 rewardCut,
uint256 feeShare,
uint256 lastActiveStakeUpdateRound,
uint256 activationRound,
uint256 deactivationRound,
uint256 activeCumulativeRewards,
uint256 cumulativeRewards,
uint256 cumulativeFees,
uint256 lastFeeRound
)
{
Transcoder storage t = transcoders[_transcoder];
lastRewardRound = t.lastRewardRound;
rewardCut = t.rewardCut;
feeShare = t.feeShare;
lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound;
activationRound = t.activationRound;
deactivationRound = t.deactivationRound;
activeCumulativeRewards = t.activeCumulativeRewards;
cumulativeRewards = t.cumulativeRewards;
cumulativeFees = t.cumulativeFees;
lastFeeRound = t.lastFeeRound;
}
/**
* @notice Return transcoder's earnings pool for a given round
* @param _transcoder Address of transcoder
* @param _round Round number
* @return totalStake Transcoder's total stake in '_round'
* @return transcoderRewardCut Transcoder's reward cut for '_round'
* @return transcoderFeeShare Transcoder's fee share for '_round'
* @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36)
* @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36)
*/
function getTranscoderEarningsPoolForRound(address _transcoder, uint256 _round)
public
view
returns (
uint256 totalStake,
uint256 transcoderRewardCut,
uint256 transcoderFeeShare,
uint256 cumulativeRewardFactor,
uint256 cumulativeFeeFactor
)
{
EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round];
totalStake = earningsPool.totalStake;
transcoderRewardCut = earningsPool.transcoderRewardCut;
transcoderFeeShare = earningsPool.transcoderFeeShare;
cumulativeRewardFactor = earningsPool.cumulativeRewardFactor;
cumulativeFeeFactor = earningsPool.cumulativeFeeFactor;
}
/**
* @notice Return delegator info
* @param _delegator Address of delegator
* @return bondedAmount total amount bonded by '_delegator'
* @return fees amount of fees collected by '_delegator'
* @return delegateAddress address '_delegator' has bonded to
* @return delegatedAmount total amount delegated to '_delegator'
* @return startRound round in which bond for '_delegator' became effective
* @return lastClaimRound round for which '_delegator' has last claimed earnings
* @return nextUnbondingLockId ID for the next unbonding lock created for '_delegator'
*/
function getDelegator(address _delegator)
public
view
returns (
uint256 bondedAmount,
uint256 fees,
address delegateAddress,
uint256 delegatedAmount,
uint256 startRound,
uint256 lastClaimRound,
uint256 nextUnbondingLockId
)
{
Delegator storage del = delegators[_delegator];
bondedAmount = del.bondedAmount;
fees = del.fees;
delegateAddress = del.delegateAddress;
delegatedAmount = del.delegatedAmount;
startRound = del.startRound;
lastClaimRound = del.lastClaimRound;
nextUnbondingLockId = del.nextUnbondingLockId;
}
/**
* @notice Return delegator's unbonding lock info
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return amount of stake locked up by unbonding lock
* @return withdrawRound round in which 'amount' becomes available for withdrawal
*/
function getDelegatorUnbondingLock(address _delegator, uint256 _unbondingLockId)
public
view
returns (uint256 amount, uint256 withdrawRound)
{
UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId];
return (lock.amount, lock.withdrawRound);
}
/**
* @notice Returns max size of transcoder pool
* @return transcoder pool max size
*/
function getTranscoderPoolMaxSize() public view returns (uint256) {
return transcoderPool.getMaxSize();
}
/**
* @notice Returns size of transcoder pool
* @return transcoder pool current size
*/
function getTranscoderPoolSize() public view returns (uint256) {
return transcoderPool.getSize();
}
/**
* @notice Returns transcoder with most stake in pool
* @return address for transcoder with highest stake in transcoder pool
*/
function getFirstTranscoderInPool() public view returns (address) {
return transcoderPool.getFirst();
}
/**
* @notice Returns next transcoder in pool for a given transcoder
* @param _transcoder Address of a transcoder in the pool
* @return address for the transcoder after '_transcoder' in transcoder pool
*/
function getNextTranscoderInPool(address _transcoder) public view returns (address) {
return transcoderPool.getNext(_transcoder);
}
/**
* @notice Return total bonded tokens
* @return total active stake for the current round
*/
function getTotalBonded() public view returns (uint256) {
return currentRoundTotalActiveStake;
}
/**
* @notice Return whether a transcoder is active for the current round
* @param _transcoder Transcoder address
* @return true if transcoder is active
*/
function isActiveTranscoder(address _transcoder) public view returns (bool) {
Transcoder storage t = transcoders[_transcoder];
uint256 currentRound = roundsManager().currentRound();
return t.activationRound <= currentRound && currentRound < t.deactivationRound;
}
/**
* @notice Return whether a transcoder is registered
* @param _transcoder Transcoder address
* @return true if transcoder is self-bonded
*/
function isRegisteredTranscoder(address _transcoder) public view returns (bool) {
Delegator storage d = delegators[_transcoder];
return d.delegateAddress == _transcoder && d.bondedAmount > 0;
}
/**
* @notice Return whether an unbonding lock for a delegator is valid
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return true if unbondingLock for ID has a non-zero withdraw round
*/
function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) {
// A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero)
return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0;
}
/**
* @notice Return an EarningsPool.Data struct with cumulative factors for a given round that are rescaled if needed
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the cumulative factors for
*/
function cumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round)
internal
view
returns (EarningsPool.Data memory pool)
{
pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor;
pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor;
return pool;
}
/**
* @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the latest cumulative factors for
* @return pool An EarningsPool.Data populated with the latest cumulative factors for _round
*/
function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round)
internal
view
returns (EarningsPool.Data memory pool)
{
pool = cumulativeFactorsPool(_transcoder, _round);
uint256 lastRewardRound = _transcoder.lastRewardRound;
// Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round
if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) {
pool.cumulativeRewardFactor = cumulativeFactorsPool(_transcoder, lastRewardRound).cumulativeRewardFactor;
}
uint256 lastFeeRound = _transcoder.lastFeeRound;
// Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round
if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) {
pool.cumulativeFeeFactor = cumulativeFactorsPool(_transcoder, lastFeeRound).cumulativeFeeFactor;
}
return pool;
}
/**
* @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm
* @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate
* @param _startRound The round for the start cumulative factors
* @param _endRound The round for the end cumulative factors
* @param _stake The delegator's initial stake before including earned rewards
* @param _fees The delegator's initial fees before including earned fees
* @return cStake , cFees where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees
*/
function delegatorCumulativeStakeAndFees(
Transcoder storage _transcoder,
uint256 _startRound,
uint256 _endRound,
uint256 _stake,
uint256 _fees
) internal view returns (uint256 cStake, uint256 cFees) {
// Fetch start cumulative factors
EarningsPool.Data memory startPool = cumulativeFactorsPool(_transcoder, _startRound);
// If the start cumulativeRewardFactor is 0 set the default value to PreciseMathUtils.percPoints(1, 1)
if (startPool.cumulativeRewardFactor == 0) {
startPool.cumulativeRewardFactor = PreciseMathUtils.percPoints(1, 1);
}
// Fetch end cumulative factors
EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound);
// If the end cumulativeRewardFactor is 0 set the default value to PreciseMathUtils.percPoints(1, 1)
if (endPool.cumulativeRewardFactor == 0) {
endPool.cumulativeRewardFactor = PreciseMathUtils.percPoints(1, 1);
}
cFees = _fees.add(
PreciseMathUtils.percOf(
_stake,
endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor),
startPool.cumulativeRewardFactor
)
);
cStake = PreciseMathUtils.percOf(_stake, endPool.cumulativeRewardFactor, startPool.cumulativeRewardFactor);
return (cStake, cFees);
}
/**
* @notice Return the pending stake and fees for a delegator
* @param _delegator Address of a delegator
* @param _endRound The last round to claim earnings for when calculating the pending stake and fees
* @return stake , fees where stake is the delegator's pending stake and fees is the delegator's pending fees
*/
function pendingStakeAndFees(address _delegator, uint256 _endRound)
internal
view
returns (uint256 stake, uint256 fees)
{
Delegator storage del = delegators[_delegator];
Transcoder storage t = transcoders[del.delegateAddress];
fees = del.fees;
stake = del.bondedAmount;
uint256 startRound = del.lastClaimRound.add(1);
address delegateAddr = del.delegateAddress;
bool isTranscoder = _delegator == delegateAddr;
// Make sure there is a round to claim i.e. end round - (start round - 1) > 0
if (startRound <= _endRound) {
(stake, fees) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees);
}
// cumulativeRewards and cumulativeFees will track *all* rewards/fees earned by the transcoder
// so it is important that this is only executed with the end round as the current round or else
// the returned stake and fees will reflect rewards/fees earned in the future relative to the end round
if (isTranscoder) {
stake = stake.add(t.cumulativeRewards);
fees = fees.add(t.cumulativeFees);
}
return (stake, fees);
}
/**
* @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The delegate to increase the stake for
* @param _amount The amount to increase the stake for '_delegate' by
*/
function increaseTotalStake(
address _delegate,
uint256 _amount,
address _newPosPrev,
address _newPosNext
) internal {
if (isRegisteredTranscoder(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.add(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
// If the transcoder is already in the active set update its stake and return
if (transcoderPool.contains(_delegate)) {
transcoderPool.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.earningsPoolPerRound[nextRound].setStake(newStake);
t.lastActiveStakeUpdateRound = nextRound;
} else {
// Check if the transcoder is eligible to join the active set in the update round
tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext);
}
}
// Increase delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount);
}
/**
* @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The transcoder to decrease the stake for
* @param _amount The amount to decrease the stake for '_delegate' by
*/
function decreaseTotalStake(
address _delegate,
uint256 _amount,
address _newPosPrev,
address _newPosNext
) internal {
if (transcoderPool.contains(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.sub(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
transcoderPool.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.lastActiveStakeUpdateRound = nextRound;
t.earningsPoolPerRound[nextRound].setStake(newStake);
}
// Decrease old delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount);
}
/**
* @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full
* @param _transcoder The transcoder to insert into the transcoder pool
* @param _totalStake The total stake for '_transcoder'
* @param _activationRound The round in which the transcoder should become active
*/
function tryToJoinActiveSet(
address _transcoder,
uint256 _totalStake,
uint256 _activationRound,
address _newPosPrev,
address _newPosNext
) internal {
uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake;
if (transcoderPool.isFull()) {
address lastTranscoder = transcoderPool.getLast();
uint256 lastStake = transcoderTotalStake(lastTranscoder);
// If the pool is full and the transcoder has less stake than the least stake transcoder in the pool
// then the transcoder is unable to join the active set for the next round
if (_totalStake <= lastStake) {
return;
}
// Evict the least stake transcoder from the active set for the next round
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPool.remove(lastTranscoder);
transcoders[lastTranscoder].deactivationRound = _activationRound;
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake);
emit TranscoderDeactivated(lastTranscoder, _activationRound);
}
transcoderPool.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext);
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake);
Transcoder storage t = transcoders[_transcoder];
t.lastActiveStakeUpdateRound = _activationRound;
t.activationRound = _activationRound;
t.deactivationRound = MAX_FUTURE_ROUND;
t.earningsPoolPerRound[_activationRound].setStake(_totalStake);
nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake;
emit TranscoderActivated(_transcoder, _activationRound);
}
/**
* @dev Remove a transcoder from the pool and deactivate it
*/
function resignTranscoder(address _transcoder) internal {
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPool.remove(_transcoder);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder));
uint256 deactivationRound = roundsManager().currentRound().add(1);
transcoders[_transcoder].deactivationRound = deactivationRound;
emit TranscoderDeactivated(_transcoder, deactivationRound);
}
/**
* @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed.
* See SortedDoublyLL.sol for details on list hints
* @param _transcoder Address of transcoder
* @param _rewards Amount of rewards
* @param _round Round that transcoder is updated
* @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool
* @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool
*/
function updateTranscoderWithRewards(
address _transcoder,
uint256 _rewards,
uint256 _round,
address _newPosPrev,
address _newPosNext
) internal {
Transcoder storage t = transcoders[_transcoder];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round];
EarningsPool.Data memory prevEarningsPool = cumulativeFactorsPool(t, t.lastRewardRound);
t.activeCumulativeRewards = t.cumulativeRewards;
uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards);
// Calculate the rewards earned by the transcoder's earned rewards
uint256 transcoderRewardStakeRewards = PreciseMathUtils.percOf(
delegatorsRewards,
t.activeCumulativeRewards,
earningsPool.totalStake
);
// Track rewards earned by the transcoder based on its earned rewards and rewardCut
t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards);
// Update cumulative reward factor with new rewards
// The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated)
// Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field
earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards);
// Update transcoder's total stake with rewards
increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext);
}
/**
* @dev Update a delegator with token pools shares from its lastClaimRound through a given round
* @param _delegator Delegator address
* @param _endRound The last round for which to update a delegator's stake with earnings pool shares
* @param _lastClaimRound The round for which a delegator has last claimed earnings
*/
function updateDelegatorWithEarnings(
address _delegator,
uint256 _endRound,
uint256 _lastClaimRound
) internal {
Delegator storage del = delegators[_delegator];
uint256 startRound = _lastClaimRound.add(1);
uint256 currentBondedAmount = del.bondedAmount;
uint256 currentFees = del.fees;
// Only will have earnings to claim if you have a delegate
// If not delegated, skip the earnings claim process
if (del.delegateAddress != address(0)) {
(currentBondedAmount, currentFees) = pendingStakeAndFees(_delegator, _endRound);
// Check whether the endEarningsPool is initialised
// If it is not initialised set it's cumulative factors so that they can be used when a delegator
// next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees())
Transcoder storage t = transcoders[del.delegateAddress];
EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound];
if (endEarningsPool.cumulativeRewardFactor == 0) {
uint256 lastRewardRound = t.lastRewardRound;
if (lastRewardRound < _endRound) {
endEarningsPool.cumulativeRewardFactor = cumulativeFactorsPool(t, lastRewardRound)
.cumulativeRewardFactor;
}
}
if (endEarningsPool.cumulativeFeeFactor == 0) {
uint256 lastFeeRound = t.lastFeeRound;
if (lastFeeRound < _endRound) {
endEarningsPool.cumulativeFeeFactor = cumulativeFactorsPool(t, lastFeeRound).cumulativeFeeFactor;
}
}
if (del.delegateAddress == _delegator) {
t.cumulativeFees = 0;
t.cumulativeRewards = 0;
// activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards
}
}
emit EarningsClaimed(
del.delegateAddress,
_delegator,
currentBondedAmount.sub(del.bondedAmount),
currentFees.sub(del.fees),
startRound,
_endRound
);
del.lastClaimRound = _endRound;
// Rewards are bonded by default
del.bondedAmount = currentBondedAmount;
del.fees = currentFees;
}
/**
* @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional
* list hint if needed. See SortedDoublyLL.sol for details on list hints
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool
*/
function processRebond(
address _delegator,
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
) internal {
Delegator storage del = delegators[_delegator];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID");
uint256 amount = lock.amount;
// Increase delegator's bonded amount
del.bondedAmount = del.bondedAmount.add(amount);
// Delete lock
delete del.unbondingLocks[_unbondingLockId];
increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext);
emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount);
}
/**
* @dev Return LivepeerToken interface
* @return Livepeer token contract registered with Controller
*/
function livepeerToken() internal view returns (ILivepeerToken) {
return ILivepeerToken(controller.getContract(keccak256("LivepeerToken")));
}
/**
* @dev Return Minter interface
* @return Minter contract registered with Controller
*/
function minter() internal view returns (IMinter) {
return IMinter(controller.getContract(keccak256("Minter")));
}
/**
* @dev Return RoundsManager interface
* @return RoundsManager contract registered with Controller
*/
function roundsManager() internal view returns (IRoundsManager) {
return IRoundsManager(controller.getContract(keccak256("RoundsManager")));
}
function _onlyTicketBroker() internal view {
require(msg.sender == controller.getContract(keccak256("TicketBroker")), "caller must be TicketBroker");
}
function _onlyRoundsManager() internal view {
require(msg.sender == controller.getContract(keccak256("RoundsManager")), "caller must be RoundsManager");
}
function _onlyVerifier() internal view {
require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier");
}
function _currentRoundInitialized() internal view {
require(roundsManager().currentRoundInitialized(), "current round is not initialized");
}
function _autoClaimEarnings() internal {
uint256 currentRound = roundsManager().currentRound();
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
if (lastClaimRound < currentRound) {
updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound);
}
}
}
| Represents a delegator's current state | struct Delegator {
}
| 13,004,493 | [
1,
23869,
87,
279,
11158,
639,
1807,
783,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
24117,
639,
288,
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
] |
./full_match/1/0x7A40F0d4674baD90D8Dd0c4D355E52347d861931/sources/contracts/MZS.sol | * @dev Recover signer address/ | function recoverAddr(address addr, string memory str, bytes memory _signature) public pure returns (address) {
return keccak256(abi.encode(str, addr)).toEthSignedMessageHash().recover(_signature);
}
| 17,012,869 | [
1,
27622,
10363,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5910,
3178,
12,
2867,
3091,
16,
533,
3778,
609,
16,
1731,
3778,
389,
8195,
13,
1071,
16618,
1135,
261,
2867,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
701,
16,
3091,
13,
2934,
869,
41,
451,
12294,
1079,
2310,
7675,
266,
3165,
24899,
8195,
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
] |
// PixelCoins Source code
pragma solidity ^0.4.11;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title A facet of PixelCore that manages special access privileges.
/// @author Oliver Schneider <[email protected]> (https://pixelcoins.io)
contract PixelAuthority {
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
address public authorityAddress;
uint public authorityBalance = 0;
/// @dev Access modifier for authority-only functionality
modifier onlyAuthority() {
require(msg.sender == authorityAddress);
_;
}
/// @dev Assigns a new address to act as the authority. Only available to the current authority.
/// @param _newAuthority The address of the new authority
function setAuthority(address _newAuthority) external onlyAuthority {
require(_newAuthority != address(0));
authorityAddress = _newAuthority;
}
}
/// @title Base contract for PixelCoins. Holds all common structs, events and base variables.
/// @author Oliver Schneider <[email protected]> (https://pixelcoins.io)
/// @dev See the PixelCore contract documentation to understand how the various contract facets are arranged.
contract PixelBase is PixelAuthority {
/*** EVENTS ***/
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a Pixel
/// ownership is assigned.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
uint32 public WIDTH = 1000;
uint32 public HEIGHT = 1000;
/*** STORAGE ***/
/// @dev A mapping from pixel ids to the address that owns them. A pixel address of 0 means,
/// that the pixel can still be bought.
mapping (uint256 => address) public pixelIndexToOwner;
/// Address that is approved to change ownship
mapping (uint256 => address) public pixelIndexToApproved;
/// Stores the color of an pixel, indexed by pixelid
mapping (uint256 => uint32) public colors;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Assigns ownership of a specific Pixel to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Can no overflowe since the number of Pixels is capped.
// transfer ownership
ownershipTokenCount[_to]++;
pixelIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete pixelIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev Checks if a given address is the current owner of a particular Pixel.
/// @param _claimant the address we are validating against.
/// @param _tokenId Pixel id
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return pixelIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Pixel.
/// @param _claimant the address we are confirming pixel is approved for.
/// @param _tokenId pixel id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return pixelIndexToApproved[_tokenId] == _claimant;
}
}
/// @title The facet of the PixelCoins core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Oliver Schneider <[email protected]> (https://pixelcoins.io), based on Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PixelCore contract documentation to understand how the various contract facets are arranged.
contract PixelOwnership is PixelBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "PixelCoins";
string public constant symbol = "PXL";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
string public metaBaseUrl = "https://pixelcoins.io/meta/";
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @notice Returns the number ofd Pixels owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Pixel to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// PixelCoins specifically) or your Pixel may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Pixel to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any pixel (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// You can only send your own pixel.
require(_owns(msg.sender, _tokenId));
// address is not currently managed by the contract (it is in an auction)
require(pixelIndexToApproved[_tokenId] != address(this));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific pixel via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the pixel that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// address is not currently managed by the contract (it is in an auction)
require(pixelIndexToApproved[_tokenId] != address(this));
// Register the approval (replacing any previous approval).
pixelIndexToApproved[_tokenId] = _to;
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Pixel owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the pixel to be transfered.
/// @param _to The address that should take ownership of the Pixel. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Pixel to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own anyd Pixels (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of pixels currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return WIDTH * HEIGHT;
}
/// @notice Returns the address currently assigned ownership of a given Pixel.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = pixelIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns the addresses currently assigned ownership of the given pixel area.
function ownersOfArea(uint256 x, uint256 y, uint256 x2, uint256 y2) external view returns (address[] result) {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
result = new address[]((y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
result[r] = pixelIndexToOwner[tokenId + j];
r++;
}
}
}
/// @notice Returns a list of all Pixel IDs assigned to an address.
/// @param _owner The owner whosed Pixels we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Pixel array looking for pixels belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPixels = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all pixels have IDs starting at 0 and increasing
// sequentially up to the totalCat count.
uint256 pixelId;
for (pixelId = 0; pixelId <= totalPixels; pixelId++) {
if (pixelIndexToOwner[pixelId] == _owner) {
result[resultIndex] = pixelId;
resultIndex++;
}
}
return result;
}
}
// Taken from https://ethereum.stackexchange.com/a/10929
function uintToString(uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
str = string(s);
}
// Taken from https://ethereum.stackexchange.com/a/10929
function appendUintToString(string inStr, uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
function setMetaBaseUrl(string _metaBaseUrl) external onlyAuthority {
metaBaseUrl = _metaBaseUrl;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Pixel whose metadata should be returned.
function tokenMetadata(uint256 _tokenId) external view returns (string infoUrl) {
return appendUintToString(metaBaseUrl, _tokenId);
}
}
contract PixelPainting is PixelOwnership {
event Paint(uint256 tokenId, uint32 color);
// Sets the color of an individual pixel
function setPixelColor(uint256 _tokenId, uint32 _color) external {
// check that the token id is in the range
require(_tokenId < HEIGHT * WIDTH);
// check that the sender is owner of the pixel
require(_owns(msg.sender, _tokenId));
colors[_tokenId] = _color;
}
// Sets the color of the pixels in an area, left to right and then top to bottom
function setPixelAreaColor(uint256 x, uint256 y, uint256 x2, uint256 y2, uint32[] _colors) external {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
require(_colors.length == (y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
if (_owns(msg.sender, tokenId + j)) {
uint32 color = _colors[r];
colors[tokenId + j] = color;
Paint(tokenId + j, color);
}
r++;
}
}
}
// Returns the color of a given pixel
function getPixelColor(uint256 _tokenId) external view returns (uint32 color) {
require(_tokenId < HEIGHT * WIDTH);
color = colors[_tokenId];
}
// Returns the colors of the pixels in an area, left to right and then top to bottom
function getPixelAreaColor(uint256 x, uint256 y, uint256 x2, uint256 y2) external view returns (uint32[] result) {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
result = new uint32[]((y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
result[r] = colors[tokenId + j];
r++;
}
}
}
}
/// @title all functions for buying empty pixels
contract PixelMinting is PixelPainting {
uint public pixelPrice = 3030 szabo;
// Set the price for a pixel
function setNewPixelPrice(uint _pixelPrice) external onlyAuthority {
pixelPrice = _pixelPrice;
}
// buy en empty pixel
function buyEmptyPixel(uint256 _tokenId) external payable {
require(msg.value == pixelPrice);
require(_tokenId < HEIGHT * WIDTH);
require(pixelIndexToOwner[_tokenId] == address(0));
// increase authority balance
authorityBalance += msg.value;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, msg.sender, _tokenId);
}
// buy an area of pixels, left to right, top to bottom
function buyEmptyPixelArea(uint256 x, uint256 y, uint256 x2, uint256 y2) external payable {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
require(msg.value == pixelPrice * (x2-x) * (y2-y));
uint256 i;
uint256 tokenId;
uint256 j;
// check that all pixels to buy are available
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
require(pixelIndexToOwner[tokenId + j] == address(0));
}
}
authorityBalance += msg.value;
// Do the actual transfer
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
_transfer(0, msg.sender, tokenId + j);
}
}
}
}
/// @title all functions for managing pixel auctions
contract PixelAuction is PixelMinting {
// Represents an auction on an NFT
struct Auction {
// Current state of the auction.
address highestBidder;
uint highestBid;
uint256 endTime;
bool live;
}
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
// Allowed withdrawals of previous bids
mapping (address => uint) pendingReturns;
// Duration of an auction
uint256 public duration = 60 * 60 * 24 * 4;
// Auctions will be enabled later
bool public auctionsEnabled = false;
// Change the duration for new auctions
function setDuration(uint _duration) external onlyAuthority {
duration = _duration;
}
// Enable or disable auctions
function setAuctionsEnabled(bool _auctionsEnabled) external onlyAuthority {
auctionsEnabled = _auctionsEnabled;
}
// create a new auctions for a given pixel, only owner or authority can do this
// The authority will only do this if pixels are misused or lost
function createAuction(
uint256 _tokenId
)
external payable
{
// only authority or owner can start auction
require(auctionsEnabled);
require(_owns(msg.sender, _tokenId) || msg.sender == authorityAddress);
// No auction is currently running
require(!tokenIdToAuction[_tokenId].live);
uint startPrice = pixelPrice;
if (msg.sender == authorityAddress) {
startPrice = 0;
}
require(msg.value == startPrice);
// this prevents transfers during the auction
pixelIndexToApproved[_tokenId] = address(this);
tokenIdToAuction[_tokenId] = Auction(
msg.sender,
startPrice,
block.timestamp + duration,
true
);
AuctionStarted(_tokenId);
}
// bid for an pixel auction
function bid(uint256 _tokenId) external payable {
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
Auction storage auction = tokenIdToAuction[_tokenId];
// Revert the call if the bidding
// period is over.
require(auction.live);
require(auction.endTime > block.timestamp);
// If the bid is not higher, send the
// money back.
require(msg.value > auction.highestBid);
if (auction.highestBidder != 0) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it could execute an untrusted contract.
// It is always safer to let the recipients
// withdraw their money themselves.
pendingReturns[auction.highestBidder] += auction.highestBid;
}
auction.highestBidder = msg.sender;
auction.highestBid = msg.value;
HighestBidIncreased(_tokenId, msg.sender, msg.value);
}
/// Withdraw a bid that was overbid.
function withdraw() external returns (bool) {
uint amount = pendingReturns[msg.sender];
if (amount > 0) {
// It is important to set this to zero because the recipient
// can call this function again as part of the receiving call
// before `send` returns.
pendingReturns[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// No need to call throw here, just reset the amount owing
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
// /// End the auction and send the highest bid
// /// to the beneficiary.
function endAuction(uint256 _tokenId) external {
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
Auction storage auction = tokenIdToAuction[_tokenId];
// 1. Conditions
require(auction.endTime < block.timestamp);
require(auction.live); // this function has already been called
// 2. Effects
auction.live = false;
AuctionEnded(_tokenId, auction.highestBidder, auction.highestBid);
// 3. Interaction
address owner = pixelIndexToOwner[_tokenId];
// transfer money without
uint amount = auction.highestBid * 9 / 10;
pendingReturns[owner] += amount;
authorityBalance += (auction.highestBid - amount);
// transfer token
_transfer(owner, auction.highestBidder, _tokenId);
}
// // Events that will be fired on changes.
event AuctionStarted(uint256 _tokenId);
event HighestBidIncreased(uint256 _tokenId, address bidder, uint amount);
event AuctionEnded(uint256 _tokenId, address winner, uint amount);
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address highestBidder,
uint highestBid,
uint endTime,
bool live
) {
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.highestBidder,
auction.highestBid,
auction.endTime,
auction.live
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getHighestBid(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
return auction.highestBid;
}
}
/// @title PixelCore: Pixels in the blockchain
/// @author Oliver Schneider <[email protected]> (https://pixelcoins.io), based on Axiom Zen (https://www.axiomzen.co)
/// @dev The main PixelCoins contract
contract PixelCore is PixelAuction {
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main PixelCore smart contract instance.
function PixelCore() public {
// the creator of the contract is the initial authority
authorityAddress = msg.sender;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyAuthority {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
// @dev Allows the authority to capture the balance available to the contract.
function withdrawBalance() external onlyAuthority returns (bool) {
uint amount = authorityBalance;
if (amount > 0) {
authorityBalance = 0;
if (!authorityAddress.send(amount)) {
authorityBalance = amount;
return false;
}
}
return true;
}
} | buy an area of pixels, left to right, top to bottom check that all pixels to buy are available Do the actual transfer | function buyEmptyPixelArea(uint256 x, uint256 y, uint256 x2, uint256 y2) external payable {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
require(msg.value == pixelPrice * (x2-x) * (y2-y));
uint256 i;
uint256 tokenId;
uint256 j;
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
require(pixelIndexToOwner[tokenId + j] == address(0));
}
}
authorityBalance += msg.value;
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
_transfer(0, msg.sender, tokenId + j);
}
}
}
| 10,120,708 | [
1,
70,
9835,
392,
5091,
434,
8948,
16,
2002,
358,
2145,
16,
1760,
358,
5469,
866,
716,
777,
8948,
358,
30143,
854,
2319,
2256,
326,
3214,
7412,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
1921,
9037,
5484,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
16,
2254,
5034,
619,
22,
16,
2254,
5034,
677,
22,
13,
3903,
8843,
429,
288,
203,
3639,
2583,
12,
92,
22,
405,
619,
597,
677,
22,
405,
677,
1769,
203,
3639,
2583,
12,
92,
22,
1648,
22631,
597,
677,
22,
1648,
4194,
7700,
1769,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
4957,
5147,
380,
261,
92,
22,
17,
92,
13,
380,
261,
93,
22,
17,
93,
10019,
203,
540,
203,
3639,
2254,
5034,
277,
31,
203,
3639,
2254,
5034,
1147,
548,
31,
203,
3639,
2254,
5034,
525,
31,
203,
3639,
364,
261,
77,
273,
677,
31,
277,
411,
677,
22,
31,
277,
27245,
288,
203,
5411,
1147,
548,
273,
277,
380,
22631,
31,
203,
5411,
364,
261,
78,
273,
619,
31,
525,
411,
619,
22,
31,
525,
27245,
288,
203,
7734,
2583,
12,
11743,
1016,
774,
5541,
63,
2316,
548,
397,
525,
65,
422,
1758,
12,
20,
10019,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
11675,
13937,
1011,
1234,
18,
1132,
31,
203,
203,
3639,
364,
261,
77,
273,
677,
31,
277,
411,
677,
22,
31,
277,
27245,
288,
203,
5411,
1147,
548,
273,
277,
380,
22631,
31,
203,
5411,
364,
261,
78,
273,
619,
31,
525,
411,
619,
22,
31,
525,
27245,
288,
203,
7734,
389,
13866,
12,
20,
16,
1234,
18,
15330,
16,
1147,
548,
397,
525,
1769,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/*
.___ ___. __ _______ ___ _______. _______ ______ __ _______
| \/ | | | | \ / \ / | / _____| / __ \ | | | \
| \ / | | | | .--. | / ^ \ | (----` | | __ | | | | | | | .--. |
| |\/| | | | | | | | / /_\ \ \ \ | | |_ | | | | | | | | | | |
| | | | | | | '--' | / _____ \ .----) | | |__| | | `--' | | `----.| '--' |
|__| |__| |__| |_______/ /__/ \__\ |_______/ \______| \______/ |_______||_______/
*/
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 "./interfaces/ILiquidityMigrator.sol";
import "./interfaces/ILayeredMdgToken.sol";
contract LayerRewardPool {// all 'mdg' in this contract represents MDG2, MDG3, etc.
using SafeMath for uint256;
using SafeERC20 for IERC20;
// uint256 public constant BLOCKS_PER_DAY = 28800; // 86400 / 3;
uint256 public constant BLOCKS_PER_WEEK = 201600; // 28800 * 7;
address public operator = address(0xD025628eEe504330f1282C96B28a731E3995ff66); // governance
bool public initialized = false;
address public reserveFund = address(0x39d91fb1Cb86c836da6300C0e700717d5dFe289F);
uint256 public reservePercent = 0; // 1% ~ 100
uint256 public lockPercent = 5000; // 50%
uint256 public rewardHalvingRate = 7500; // 75%
address public mdg; // address of Mdg[N]Token
uint256 public mdgPoolId;
uint256 public layerId; // from 2
uint256 public totalAllocPoint = 0;// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public rewardPerBlock; // 0.1 * 1e18
uint256 public startBlock; // The block number when Mdg[N] mining starts.
uint256 public endBlock; // default = startBlock + 8 weeks
uint256 public bigHalvingBlock; // The block to reduce 50% of rewardPerBlock. Default = startBlock + 2 weeks
uint256 public lockUntilBlock; // default = startBlock + 4 weeks
uint256 public nextHalvingBlock;
uint256 public halvingPeriod; // default = 1 week;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 lockDebt;
uint256 reward2Debt;
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
address reward2; // additional reward
uint256 allocPoint; // How many allocation points assigned to this pool. Mdg[N]s to distribute per block.
uint256 lastRewardBlock; // Last block number that Mdg[N]s distribution occurs.
uint256 accMdgPerShare; // Accumulated Mdg[N] per share, times 1e18. See below.
uint256 accLockPerShare;
uint256 accReward2PerShare;
uint256 reward2PerBlock; // 0.1 * 1e18
uint256 reward2EndBlock;
uint16 depositFeeBP; // Deposit fee in basis points
bool isStarted; // if lastRewardBlock has passed
}
PoolInfo[] public poolInfo; // Info of each pool.
mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Info of each user that stakes LP tokens.
// The liquidity migrator contract. It has a lot of power. Can only be set through governance (owner).
ILiquidityMigrator public migrator;
/* =================== Added variables (need to keep orders for proxy to work) =================== */
bool public halvingChecked = true;
/* ========== EVENTS ========== */
event Initialized(address indexed executor, uint256 at);
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 RewardPaid(address indexed user, address indexed token, uint256 amount);
// Locker {
uint256 public startReleaseBlock;
uint256 public endReleaseBlock;
uint256 public totalLock;
mapping(address => uint256) public mdgLocked;
mapping(address => uint256) public mdgReleased;
event Lock(address indexed to, uint256 value);
// }
function initialize(
uint256 _layerId,
address _mdg, // Mdg[N]Token contract
uint256 _rewardPerBlock,//0.06 * 1e18
uint256 _startBlock,
address _reserveFund,
address _operator
) public {
require(!initialized || (startBlock > block.number && poolInfo.length == 0 && operator == msg.sender), "initialized");
require(block.number < _startBlock, "late");
require(_layerId >= 2, "from 2");
// require(_endReleaseBlock > _startReleaseBlock, "endReleaseBlock < startReleaseBlock");
layerId = _layerId;
mdg = _mdg;
rewardPerBlock = _rewardPerBlock; // start at 0.1 Mdg[N] per block for the first week
startBlock = _startBlock;
endBlock = _startBlock + BLOCKS_PER_WEEK * 8;
bigHalvingBlock = _startBlock + BLOCKS_PER_WEEK * 2;
lockUntilBlock = _startBlock + BLOCKS_PER_WEEK * 4;// _startBlock + 4 weeks
nextHalvingBlock = startBlock.add(BLOCKS_PER_WEEK);
reserveFund = _reserveFund;
operator = _operator;
halvingChecked = true;
halvingPeriod = BLOCKS_PER_WEEK;
reservePercent = 0; // 1% ~ 100
lockPercent = 5000; // 50%
rewardHalvingRate = 7500; // 75%
totalAllocPoint = 0;
// Locker
startReleaseBlock = lockUntilBlock;//_startReleaseBlock;
endReleaseBlock = endBlock;//_endReleaseBlock;
initialized = true;
emit Initialized(msg.sender, block.number);
}
modifier onlyOperator() {
require(operator == msg.sender, "LayerRewardPool: caller is not the operator");
_;
}
modifier checkHalving() {
if (halvingChecked) {
halvingChecked = false;
uint256 target = block.number < endBlock ? block.number : endBlock;
while (target >= nextHalvingBlock) {
massUpdatePools(nextHalvingBlock);
if (nextHalvingBlock >= bigHalvingBlock && nextHalvingBlock.sub(halvingPeriod) < bigHalvingBlock) {
rewardPerBlock = rewardPerBlock.mul(5000).div(10000); // decrease 50%
} else {
rewardPerBlock = rewardPerBlock.mul(rewardHalvingRate).div(10000); // x75% (25% decreased every-week)
}
nextHalvingBlock = nextHalvingBlock.add(halvingPeriod);
}
halvingChecked = true;
}
_;
}
function setHalvingPeriod(uint256 _halvingPeriod, uint256 _nextHalvingBlock) external onlyOperator {
require(_halvingPeriod >= 100, "zero"); // >= 5 minutes
require(_nextHalvingBlock > block.number, "over");
halvingPeriod = _halvingPeriod;
nextHalvingBlock = _nextHalvingBlock;
}
function setReserveFund(address _reserveFund) external onlyOperator {
reserveFund = _reserveFund;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(ILiquidityMigrator _migrator) public onlyOperator {
migrator = _migrator;
}
// Migrate lp token to another lp contract.
function migrate(uint256 _pid) public onlyOperator {
require(block.number >= startBlock + BLOCKS_PER_WEEK * 4, "DON'T migrate too soon sir!");
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;
}
function checkPoolDuplicate(IERC20 _lpToken) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].lpToken != _lpToken, "LayerRewardPool: existing pool?");
}
}
// Add a new lp to the pool. Can only be called by the owner.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
uint16 _depositFeeBP,
uint256 _lastRewardBlock
) public onlyOperator {
require(_allocPoint <= 500000, "too high allocation point"); // <= 500x
require(_depositFeeBP <= 1000, "too high fee"); // <= 10%
checkPoolDuplicate(_lpToken);
massUpdatePools();
if (block.number < startBlock) {
// chef is sleeping
if (_lastRewardBlock == 0) {
_lastRewardBlock = startBlock;
} else {
if (_lastRewardBlock < startBlock) {
_lastRewardBlock = startBlock;
}
}
} else {
// chef is cooking
if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) {
_lastRewardBlock = block.number;
}
}
bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
reward2: address(0),
allocPoint: _allocPoint,
lastRewardBlock: _lastRewardBlock,
accMdgPerShare: 0,
accLockPerShare: 0,
accReward2PerShare: 0,
reward2PerBlock: 0,
reward2EndBlock: 0,
depositFeeBP: _depositFeeBP,
isStarted: _isStarted
})
);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
if (mdgPoolId == 0 && _lpToken == IERC20(mdg)) {
mdgPoolId = poolInfo.length - 1;
}
}
// Update the given pool's Mdg[N] allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP) public onlyOperator {
require(_allocPoint <= 500000, "too high allocation point"); // <= 500x
require(_depositFeeBP <= 1000, "too high fee"); // <= 10%
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
}
pool.allocPoint = _allocPoint;
pool.depositFeeBP = _depositFeeBP;
}
// Add additional reward for a pool
function setReward2(uint256 _pid, address _reward2, uint256 _reward2PerBlock, uint256 _reward2EndBlock) external onlyOperator {
PoolInfo storage pool = poolInfo[_pid];
require(_reward2 != address(0), "address(0)");
require(_reward2PerBlock < 0.9 ether, "too high reward");
if (_reward2 == pool.reward2) {// update info
updatePool(_pid);
if (_reward2EndBlock > 0) {
require(pool.reward2EndBlock > block.number, "reward2 is over");
require(_reward2EndBlock > block.number, "late");
require(_reward2EndBlock <= endBlock, "reward2 is redundant");
pool.reward2EndBlock = _reward2EndBlock;
}
pool.reward2PerBlock = _reward2PerBlock;
} else {
require(pool.reward2 == address(0), "don't support multiple additional rewards in a pool");
// require(!pool.isStarted, "Pool started");
require(_reward2EndBlock > block.number, "late");
require(_reward2PerBlock > 0, "zero");
pool.reward2 = _reward2;
pool.accReward2PerShare = 0;
pool.reward2PerBlock = _reward2PerBlock;
pool.reward2EndBlock = _reward2EndBlock > endBlock ? endBlock : _reward2EndBlock;
}
}
// Return accumulate rewarded blocks over the given _from to _to block.
function getRewardBlocks(uint256 _from, uint256 _to, uint256 _endBlock) internal view returns (uint256) {
if (_from >= _to) return 0;
if (_from >= _endBlock) return 0;
if (_to <= startBlock) return 0;
if (_to > _endBlock) _to = _endBlock;
return _to.sub(_from <= startBlock ? startBlock : _from);
}
// View function to see pending Mdg[N]s on frontend.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMdgPerShare = pool.accMdgPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 _generatedReward = getRewardBlocks(pool.lastRewardBlock, block.number, endBlock).mul(rewardPerBlock);
uint256 _mdgReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accMdgPerShare = accMdgPerShare.add(_mdgReward.mul(1e18).div(lpSupply));
}
return user.amount.mul(accMdgPerShare).div(1e18).sub(user.rewardDebt);
}
function pendingReward2(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
if (pool.reward2 == address(0)) return 0;
UserInfo storage user = userInfo[_pid][_user];
uint256 accReward2PerShare = pool.accReward2PerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 _reward2 = getRewardBlocks(pool.lastRewardBlock, block.number, pool.reward2EndBlock).mul(pool.reward2PerBlock);
accReward2PerShare = accReward2PerShare.add(_reward2.mul(1e18).div(lpSupply));
}
return user.amount.mul(accReward2PerShare).div(1e18).sub(user.reward2Debt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public checkHalving {
massUpdatePools(block.number);
}
function massUpdatePools(uint256 _targetTime) private {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid, _targetTime);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public checkHalving {
updatePool(_pid, block.number);
}
function updatePool(uint256 _pid, uint256 _targetTime) private {
PoolInfo storage pool = poolInfo[_pid];
if (_targetTime <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = _targetTime;
return;
}
if (!pool.isStarted) { // note: pool.lastRewardBlock < _targetTime <= block.number
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getRewardBlocks(pool.lastRewardBlock, _targetTime, endBlock);
uint256 _mdgReward = _generatedReward.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accMdgPerShare = pool.accMdgPerShare.add(_mdgReward.mul(1e18).div(lpSupply));
if (pool.lastRewardBlock < lockUntilBlock) {
pool.accLockPerShare = pool.accLockPerShare.add(_mdgReward.mul(lockPercent).div(10000).mul(1e18).div(lpSupply));
}
if (pool.lastRewardBlock < pool.reward2EndBlock) {
uint256 _reward2 = getRewardBlocks(pool.lastRewardBlock, _targetTime, pool.reward2EndBlock).mul(pool.reward2PerBlock);
pool.accReward2PerShare = pool.accReward2PerShare.add(_reward2.mul(1e18).div(lpSupply));
}
}
pool.lastRewardBlock = _targetTime;
}
function _harvestReward(uint256 _pid, address _account) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_account];
uint256 newRewardDebt = user.amount.mul(pool.accMdgPerShare).div(1e18);
uint256 newLockDebt = user.amount.mul(pool.accLockPerShare).div(1e18);
uint256 newReward2Debt = user.amount.mul(pool.accReward2PerShare).div(1e18);
uint256 _pendingReward = newRewardDebt.sub(user.rewardDebt);
uint256 _pendingLock = newLockDebt.sub(user.lockDebt);
uint256 _pendingReward2 = newReward2Debt.sub(user.reward2Debt);
user.rewardDebt = newRewardDebt;
user.lockDebt = newLockDebt;
user.reward2Debt = newReward2Debt;
if (_pendingReward > 0) {
_safeMdgMint(_account, _pendingReward, _pendingLock);
emit RewardPaid(_account, mdg, _pendingReward);
}
if (_pendingReward2 > 0) {
_safeTokenTransfer(pool.reward2, _account, _pendingReward2);
emit RewardPaid(_account, pool.reward2, _pendingReward2);
}
}
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public checkHalving {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid, block.number);
if (user.amount > 0) {
_harvestReward(_pid, _sender);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_sender, address(this), _amount);
if (pool.depositFeeBP > 0) {
uint256 _depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(reserveFund, _depositFee);
user.amount = user.amount.add(_amount).sub(_depositFee);
} else {
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accMdgPerShare).div(1e18);
user.lockDebt = user.amount.mul(pool.accLockPerShare).div(1e18);
user.reward2Debt = user.amount.mul(pool.accReward2PerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public checkHalving {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid, block.number);
_harvestReward(_pid, _sender);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accMdgPerShare).div(1e18);
user.lockDebt = user.amount.mul(pool.accLockPerShare).div(1e18);
user.reward2Debt = user.amount.mul(pool.accReward2PerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
function harvestAllRewards() public checkHalving {
uint256 length = poolInfo.length;
for (uint256 _pid = 0; _pid < length; ++_pid) {
if (userInfo[_pid][msg.sender].amount > 0) {
withdraw(_pid, 0);
}
}
}
function harvestAndRestake() external {
require(mdgPoolId > 0, "Stake pool hasn't been opened");// pool-0 is always LP of previous layer MDG[N-1]
harvestAllRewards();
uint256 _mdgBal = IERC20(mdg).balanceOf(msg.sender);
if (_mdgBal > 0) {
IERC20(mdg).safeIncreaseAllowance(address(this), _mdgBal);
deposit(mdgPoolId, _mdgBal);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external checkHalving {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.lockDebt = 0;
user.reward2Debt = 0;
pool.lpToken.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
function _safeMdgMint(address _to, uint256 _amount, uint256 _lockAmount) internal {
if (ILayeredMdgToken(mdg).isMinter(address(this)) && _to != address(0)) {
ILayeredMdgToken mdgToken = ILayeredMdgToken(mdg);
uint256 _totalSupply = IERC20(mdg).totalSupply() + mdgToken.getBurnedAmount();
uint256 _cap = mdgToken.cap();
uint256 _mintAmount = (_totalSupply.add(_amount) <= _cap) ? _amount : _cap.sub(_totalSupply);
if (_mintAmount > 0) {
mdgToken.mint(address(this), _mintAmount);
uint256 _transferAmount = _mintAmount;
if (_lockAmount > 0) {
if (_lockAmount > _mintAmount) _lockAmount = _mintAmount;
_transferAmount = _transferAmount.sub(_lockAmount);
mdgLocked[_to] = mdgLocked[_to].add(_lockAmount);
totalLock = totalLock.add(_lockAmount);
emit Lock(_to, _lockAmount);
}
IERC20(mdg).safeTransfer(_to, _transferAmount);
if (reservePercent > 0 && reserveFund != address(0)) {
uint256 _reserveAmount = _mintAmount.mul(reservePercent).div(10000);
_totalSupply = IERC20(mdg).totalSupply() + mdgToken.getBurnedAmount();
_cap = mdgToken.cap();
_reserveAmount = (_totalSupply.add(_reserveAmount) <= _cap) ? _reserveAmount : _cap.sub(_totalSupply);
if (_reserveAmount > 0) {
mdgToken.mint(reserveFund, _reserveAmount);
}
}
}
}
}
function _safeTokenTransfer(address _token, address _to, uint256 _amount) internal {
uint256 _tokenBal = IERC20(_token).balanceOf(address(this));
if (_amount > _tokenBal) {
_amount = _tokenBal;
}
if (_amount > 0) {
IERC20(_token).safeTransfer(_to, _amount);
}
}
function setMdgPoolId(uint256 _mdgPoolId) external onlyOperator {
mdgPoolId = _mdgPoolId;
}
function setRates(uint256 _reservePercent, uint256 _lockPercent, uint256 _rewardHalvingRate) external onlyOperator { // tune and vote
require(_rewardHalvingRate < 10000, "exceed 100%");
require(_rewardHalvingRate > 0, "shouldn't set to 0%"); // can't trace
require(_reservePercent <= 2000, "exceed 20%");
require(_lockPercent <= 9000, "exceed 90%");
massUpdatePools();
reservePercent = _reservePercent;
lockPercent = _lockPercent;
rewardHalvingRate = _rewardHalvingRate;
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOperator {
require(_rewardPerBlock <= 0.2 ether, "too high reward"); // <= 0.2 MDG per block
massUpdatePools();
rewardPerBlock = _rewardPerBlock;
}
function setHalvingChecked(bool _halvingChecked) external onlyOperator {
halvingChecked = _halvingChecked;
}
function setLastRewardBlock(uint256 _pid, uint256 _lastRewardBlock) external onlyOperator {
require(_lastRewardBlock >= startBlock, "bad _lastRewardBlock");
require(_lastRewardBlock > block.number, "late");
PoolInfo storage pool = poolInfo[_pid];
require(!pool.isStarted || startBlock > block.number, "Pool started!");
require(_lastRewardBlock != pool.lastRewardBlock, "no change");
pool.lastRewardBlock = _lastRewardBlock;
if (pool.isStarted) {
pool.isStarted = false;
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint);
} else if (_lastRewardBlock == startBlock) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
}
function setStartBlock(uint256 _startBlock, uint256 _lockUntilBlock, uint256 _bigHalvingBlock, uint256 _endBlock) external onlyOperator {
if (_startBlock > block.number) {
require(block.number < startBlock, "The layer started!");
startBlock = _startBlock;
nextHalvingBlock = startBlock.add(BLOCKS_PER_WEEK);
bigHalvingBlock = startBlock + BLOCKS_PER_WEEK * 2;
lockUntilBlock = startBlock + BLOCKS_PER_WEEK * 4;
endBlock = startBlock + BLOCKS_PER_WEEK * 8;
uint256 plen = poolInfo.length;
for (uint256 pid = 0; pid < plen; ++pid) {
PoolInfo storage pool = poolInfo[pid];
if (pool.isStarted) {
pool.lastRewardBlock = startBlock;
} else {
if (pool.lastRewardBlock <= startBlock) {
pool.isStarted = true;
pool.lastRewardBlock = startBlock;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
}
}
}
if (_bigHalvingBlock > block.number) bigHalvingBlock = _bigHalvingBlock;
if (_endBlock > block.number) {
require(block.number < endBlock, "Layer finished");
endBlock = _endBlock;
}
if (_lockUntilBlock > block.number) {
require(block.number < lockUntilBlock, "Lock has released");
require(_lockUntilBlock > startBlock, "Bad _lockUntilBlock");
lockUntilBlock = _lockUntilBlock;
}
if (lockUntilBlock > endBlock) lockUntilBlock = endBlock;
startReleaseBlock = lockUntilBlock;
endReleaseBlock = endBlock;
}
function poolLength() public view returns (uint256) {
return poolInfo.length;
}
// locker_field {
function canUnlockAmount(address _account) public view returns (uint256) {
if (block.number < startReleaseBlock) return 0;
if (block.number >= endReleaseBlock) return mdgLocked[_account].sub(mdgReleased[_account]);
uint256 _releasedBlock = block.number.sub(startReleaseBlock);
uint256 _totalVestingBlock = endReleaseBlock.sub(startReleaseBlock);
return mdgLocked[_account].mul(_releasedBlock).div(_totalVestingBlock).sub(mdgReleased[_account]);
}
function unlock() external {
require(block.number > startReleaseBlock, "still locked");
require(mdgLocked[msg.sender] >= mdgReleased[msg.sender], "no locked");
uint256 _amount = canUnlockAmount(msg.sender);
IERC20(mdg).safeTransfer(msg.sender, _amount);
mdgReleased[msg.sender] = mdgReleased[msg.sender].add(_amount);
totalLock = totalLock.sub(_amount);
}
// } end_locker_field
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator {
if (block.number < startBlock + BLOCKS_PER_WEEK * 104) {
// do not allow to drain lpToken if less than 2 years after farming
require(address(_token) != mdg, "mdg");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.lpToken, "!pool.lpToken");
}
}
_token.safeTransfer(to, amount);
}
}
| default = startBlock + 4 weeks
| uint256 public lockUntilBlock; | 5,461,372 | [
1,
1886,
273,
787,
1768,
397,
1059,
17314,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
2176,
9716,
1768,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "./libs/LibAccess.sol";
import "./libs/LibStorage.sol";
import "./Types.sol";
import "hardhat/console.sol";
abstract contract BaseAccess {
using LibAccess for Types.AccessControl;
//bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant ADMIN_ROLE = 0xa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c21775;
//bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant PAUSER_ROLE = 0x65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a;
//bytes32 public constant RELAY_ROLE = keccak256("RELAY_ROLE");
bytes32 public constant RELAY_ROLE = 0x077a1d526a4ce8a773632ab13b4fbbf1fcc954c3dab26cd27ea0e2a6750da5d7;
//bytes32 public constant ACTION_ROLE = keccak256("ACTION_ROLE");
bytes32 public constant ACTION_ROLE = 0xd95061bdf0c43d77b6cbe1c15072292976244ec8d5012de75baa36e42da4625e;
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function hasRole(bytes32 role, address actor) public view returns (bool) {
return LibStorage.getAccessStorage().hasRole(role, actor);
}
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "Not admin");
_;
}
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Not pauser");
_;
}
modifier onlyRelay() {
require(hasRole(RELAY_ROLE, _msgSender()), "Not relay");
_;
}
modifier initializer() {
Types.InitControls storage ic = LibStorage.getInitControls();
require(ic.initializing || !ic.initialized, "Already initialized");
bool tlc = !ic.initializing;
if(tlc) {
ic.initializing = true;
ic.initialized = true;
}
_;
if(tlc) {
ic.initializing = false;
}
}
modifier nonReentrant() {
require(!LibStorage.getAccessStorage().reentrantFlag, "Attempting to re-enter function recursively");
LibStorage.getAccessStorage().reentrantFlag = true;
_;
LibStorage.getAccessStorage().reentrantFlag = false;
}
//================ MUTATIONS ===============/
function addRole(bytes32 role, address actor) public onlyAdmin {
_setupRole(role, actor);
}
function revokeRole(bytes32 role, address actor) public onlyAdmin {
LibStorage.getAccessStorage()._revokeRole(role, actor);
}
function _setupRole(bytes32 role, address actor) internal {
LibStorage.getAccessStorage()._addRole(role, actor);
}
function initAccess() internal initializer {
address o = _msgSender();
_setupRole(ADMIN_ROLE, o);
_setupRole(PAUSER_ROLE, o);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "../Types.sol";
library LibAccess {
function hasRole(Types.AccessControl storage ac, bytes32 role, address actor) external view returns (bool) {
return ac.roles[role][actor];
}
function _addRole(Types.AccessControl storage ac, bytes32 role, address actor) internal {
ac.roles[role][actor] = true;
}
function _revokeRole(Types.AccessControl storage ac, bytes32 role, address actor) internal {
delete ac.roles[role][actor];
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../Types.sol";
library LibStorage {
//keccak256("com.buidlhub.config.ConfigStorage");
bytes32 constant CONFIG_STORAGE_KEY = 0xf5b4be0a744c821d14f78bf26d55a308f420d78cebbfac103f2618fba32917b9;
//keccak256("com.buidlhub.access.AccessControls");
bytes32 constant ACCESS_STORAGE_KEY = 0x3a83b1278d351a40f18bb9e8e77896e8c1dc812ffaed5ea63e0e837a6dae57e9;
//keccak256("com.buidlhub.init.InitControls");
bytes32 constant INIT_STORAGE_KEY = 0xd59dd79cfd4373c6c6547848d91fc2ea67c8aec9053f7028828216c5af1d4741;
//keccak256("com.buidlhub.gastank.GasStorage");
bytes32 constant GAS_STORAGE_KEY = 0x8c89fc81d9ea4103ca01a6b8674fdaec22ec47acad49dcba52ad9c3d556ea075;
//============= STORAGE ACCESSORS ==========/
function getConfigStorage() internal pure returns (Types.Config storage cs) {
assembly { cs.slot := CONFIG_STORAGE_KEY }
}
function getAccessStorage() internal pure returns (Types.AccessControl storage acs) {
assembly { acs.slot := ACCESS_STORAGE_KEY }
}
function getInitControls() internal pure returns (Types.InitControls storage ic) {
assembly { ic.slot := INIT_STORAGE_KEY }
}
function getGasStorage() internal pure returns (Types.GasBalances storage gs) {
assembly { gs.slot := GAS_STORAGE_KEY }
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library Types {
struct TokenAmount {
IERC20 token;
uint112 amount;
}
//status of order. Only tracked on action from user/miners
enum OrderStatus {
UNDEFINED,
PENDING,
FILLED,
CANCELLED,
PENALIZED
}
enum OrderType {
EXACT_IN,
EXACT_OUT
}
struct Order {
//fee offered (120+128 = 248)
uint128 fee;
//the fee that needs to be paid to a target DEX in ETH
uint128 dexFee;
//trader that owns the order
address trader;
//the type of trade being made
OrderType orderType;
//token being offered
TokenAmount input;
//token wanted
TokenAmount output;
}
/**
* A trader's gas tank balance and any amount that's
* thawing waiting for withdraw.
*/
struct Gas {
//available balance used to pay for fees
uint112 balance;
//amount user is asking to withdraw after a that period expires
uint112 thawing;
//the block at which any thawing amount can be withdrawn
uint256 thawingUntil;
}
//============== CONFIG STATE =============/
struct Config {
//dev team address (120b)
address devTeam;
//min fee amount (128b, 248b chunk)
uint128 minFee;
//penalty a user faces for removing assets or
//allowances before a trade
uint128 penaltyFee;
//number of blocks to lock stake and order cancellations
uint8 lockoutBlocks;
}
//============== ACCESS STATE =============/
//storage structure of access controls
struct AccessControl {
bool reentrantFlag;
mapping(bytes32 => mapping(address => bool)) roles;
}
//============== INITIALIZATION STATE =============/
struct InitControls {
bool initialized;
bool initializing;
}
//=============== GAS TANK STATE =============/
struct GasBalances {
mapping(address => Gas) balances;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "hardhat/console.sol";
import "../../Types.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../IDexRouter.sol";
import "../../BaseAccess.sol";
// @dev The ZrxRouter is used by settlement to execute orders through 0x
contract ZrxRouter is BaseAccess, IDexRouter {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
function initialize() public initializer {
BaseAccess.initAccess();
}
// @dev Executes a call to 0x to make fill the order
// @param order - contains the order details from the Smart Order Router
// @param orderCallData - abi encoded swapTarget address and data from 0x API
function fill(Types.Order calldata order, bytes calldata orderCallData)
external override returns (bool success, string memory failReason) {
//call data contains the target address and data to pass to it to execute
(address swapTarget, address allowanceTarget, bytes memory data) = abi.decode(orderCallData, (address,address,bytes));
console.log("Going to swap target", swapTarget);
console.log("Approving allowance for", allowanceTarget);
//Settlement transferred token input amount so we can swap
uint256 balanceBefore = order.output.token.balanceOf(address(this));
console.log("Balance of input token b4", balanceBefore);
//for protocols that require zero-first approvals
require(order.input.token.approve(allowanceTarget, 0));
//make sure 0x target has approval to spend this contract's tokens
require(order.input.token.approve(allowanceTarget, order.input.amount));
//execute the swap, forwarding any ETH fee if needed. The ETH fee was
//transferred to this contract by Settlement if it was needed
console.log("Swapping...");
(bool _success,) = swapTarget.call{value: order.dexFee, gas: gasleft()}(data);
if(!_success) {
console.log("Failed to swap");
return (false, "SWAP_CALL_FAILED");
}
//make sure we received tokens
uint256 balanceAfter = order.output.token.balanceOf(address(this));
uint256 diff = balanceAfter.sub(balanceBefore);
console.log("Balance received", diff);
require(diff >= order.output.amount, "Insufficient output amount");
if(!order.output.token.transfer(order.trader, diff)) {
console.log("Could not transfer tokens to trader");
return (false, "Failed to transfer funds to trader");
}
return (true,"");
}
// Payable fallback to allow this contract to receive protocol fee refunds.
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./Types.sol";
/**
* Abstraction of DEX integration with simple fill function.
*/
interface IDexRouter {
/**
* Fill an order using the given call data details.
*/
function fill(Types.Order memory order, bytes calldata swapData) external returns (bool status, string memory failReason);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IDexRouter.sol";
import "./GasTank.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Types.sol";
contract Settlement is GasTank {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint128;
using SafeMath for uint;
using SafeERC20 for IERC20;
//============= EVENT DEFS =================/
event TraderPenalized(address indexed trader, uint256 penalty, uint256 gasPaid, string reason);
event SwapFailed(address indexed trader, uint gasPaid, string reason);
event SwapSuccess(address indexed trader,
address indexed executor,
uint inputAmount,
uint outputAmount,
uint fee,
uint gasPaid);
//============== CONSTANTS ==============/
//estimate gas usage for testing a user's deposit
uint256 constant GAS_ESTIMATE = 450_000;
//extra overhead for transferring funds
uint256 constant GAS_OVERHEAD = 60_000;
//gas needed after action executes
uint256 constant OP_GAS = 80_000;
struct BalTracking {
uint256 inBal;
uint256 outBal;
uint256 afterIn;
uint256 afterOut;
}
/**
* Fill an order using the given router and forwarded call data.
*/
function fill(Types.Order memory order, IDexRouter router, bytes calldata data) public onlyRelay nonReentrant {
uint256 startGas = gasleft();
//pre-trade condition checks
BalTracking memory _tracker = _preCheck(order);
//execute action
(bool success, string memory failReason) = performFill(order, router, data);
//post-trade condition check
_postCheck(order, _tracker, success);
//post-trade actions to transfer fees, etc.
_postActions(order, success, failReason, _tracker, startGas);
}
// @dev initialize the settlement contract
function initialize(Types.Config memory config) public initializer {
BaseConfig.initConfig(config);
}
// @dev whether the trader has gas funds to support order at the given gas price
function _hasFunds(Types.Order memory order, uint256 gasPrice) internal view returns (bool) {
require(order.fee >= LibStorage.getConfigStorage().minFee, "Order has insufficient fee");
uint256 gas = GAS_ESTIMATE.mul(gasPrice);
uint256 total = gas.add(order.fee)
.add(order.dexFee)
.add(LibStorage.getConfigStorage().penaltyFee);
bool b = this.hasEnoughGas(order.trader, total);
return b;
}
// @dev whether the trader has a token balance to support input side of order
function _hasTokens(Types.Order memory order) internal view returns (bool) {
bool b = order.input.token.balanceOf(order.trader) >= order.input.amount;
return b;
}
// @dev whether the trader has approved this contract to spend enought for order
function _canSpend(Types.Order memory order) internal view returns (bool) {
bool b = order.input.token.allowance(order.trader, address(this)) >= order.input.amount;
return b;
}
function _preCheck(Types.Order memory order) internal view returns (BalTracking memory) {
require(_hasFunds(order, tx.gasprice), "Insufficient gas tank funds");
require(_hasTokens(order), "Insufficient input token balance to trade");
require(_canSpend(order), "Insufficient spend allowance on input token");
//before balances
return BalTracking(
order.input.token.balanceOf(order.trader),
order.output.token.balanceOf(order.trader),
0,0
);
}
function _preActions(Types.Order memory order, IDexRouter router) internal {
//transfer input tokens to router so it can perform dex trades
order.input.token.safeTransferFrom(order.trader, address(router), order.input.amount);
if(order.dexFee > 0) {
//pay ETH fee to DEX if rquired
payable(address(router)).transfer(order.dexFee);
}
}
function performFill(Types.Order memory order, IDexRouter router, bytes calldata data) internal returns (bool success, string memory failReason) {
//execute action. This is critical that we use our own internal call to actually
//perform swap inside trycatch. This way, transferred funds to script are
//reverted if swap fails
try this._trySwap{
gas: gasleft().sub(OP_GAS)
}(order, router, data) returns (bool _success, string memory _failReason) {
return (_success, _failReason);
} catch Error(string memory err) {
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
}
function _trySwap(Types.Order calldata order, IDexRouter router, bytes calldata data) external returns (bool success, string memory failReason) {
require(msg.sender == address(this), "Can only be called by settlement contract");
_preActions(order, router);
(bool s, string memory err) = router.fill(order, data);
if(!s) {
revert(err);
}
return (s, err);
}
function _postCheck(Types.Order memory order, BalTracking memory _tracking, bool success) internal view {
_tracking.afterIn = order.input.token.balanceOf(order.trader);
if(!success) {
//have to revert if funds were not refunded in order to roll everything back.
//in this case, the router is at fault, which is Dexible's fault and therefore
//Dexible relay address should eat the cost of failure
console.log("Input bal b4", _tracking.inBal);
console.log("Input bal after", _tracking.afterIn);
require(_tracking.afterIn == _tracking.inBal, "failed trade action did not refund input funds");
} else {
_tracking.afterOut = order.output.token.balanceOf(order.trader);
//if the in/out amounts don't line up, then transfers weren't made properly in the
//router.
console.log("Trader token balance before swap", _tracking.outBal);
console.log("New trader balance", _tracking.afterOut);
require(_tracking.afterOut.sub(_tracking.outBal) >= order.output.amount, "Trade action did not transfer output tokens to trader");
require(_tracking.afterIn < _tracking.inBal, "Input tokens not used!");
require(_tracking.inBal.sub(_tracking.afterIn) <= order.input.amount, "Used too many input tokens");
}
}
function _postActions(Types.Order memory order,
bool success,
string memory failReason,
BalTracking memory _tracking,
uint startGas) internal {
if(!success) {
//pay relayer back their gas but take no fee
uint256 totalGasUsed = startGas.sub(gasleft()).add(GAS_OVERHEAD);
uint256 gasFee = totalGasUsed.mul(tx.gasprice);
deduct(order.trader, uint112(gasFee));
//tell trader it failed
emit SwapFailed(order.trader, gasFee, failReason);
//console.log("Paying gas", gasFee);
_msgSender().transfer(gasFee);
} else {
//otherwise, pay fee and gas
uint256 totalGasUsed = startGas.sub(gasleft()).add(GAS_OVERHEAD);
uint256 gasFee = totalGasUsed.mul(tx.gasprice);
deduct(order.trader, uint112(gasFee.add(order.fee).add(order.dexFee)));
_msgSender().transfer(gasFee);
payable(LibStorage.getConfigStorage().devTeam).transfer(order.fee);
console.log("Successful swap");
emit SwapSuccess(order.trader,
_msgSender(),
_tracking.inBal.sub(_tracking.afterIn),
_tracking.afterOut.sub(_tracking.outBal),
order.fee.add(order.dexFee),
gasFee);
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./BaseConfig.sol";
import "./libs/LibGas.sol";
abstract contract GasTank is BaseConfig {
using LibGas for Types.GasBalances;
//========== VIEWS =============/
/**
* Determine how much of the gas tank balance is available for withdraw after having
* waited a sufficient thaw period.
*/
function availableGasForWithdraw(address owner) external view returns (uint256) {
return LibStorage.getGasStorage().availableForWithdraw(owner);
}
/**
* Determine the amount of eth available to use to pay for fees. This includes
* any thawing funds that have not yet reached the thaw expiration block.
*/
function availableForUse(address owner) external view returns (uint256) {
return LibStorage.getGasStorage().availableForUse(owner);
}
/**
* Determine the amount of funds actively awaiting the thaw period.
*/
function thawingFunds(address owner) external view returns (uint256) {
return LibStorage.getGasStorage().thawingFunds(owner);
}
// @dev check whether the given holder has enough gas to pay the bill
function hasEnoughGas(address holder, uint256 due) external view returns (bool) {
return LibStorage.getGasStorage().availableForUse(holder) >= due;
}
// ========= MUTATIONS =============/
/**
* Deposit funds into the gas tank
*/
function depositGas() external payable {
require(msg.value > 0, "No funds provided for gas deposit");
LibStorage.getGasStorage().deposit(_msgSender(), uint112(msg.value));
}
/**
* Request that funds be thawed and prepared for withdraw after thaw period expires.
*/
function requestWithdrawGas(uint112 amount) external {
require(amount > 0, "Cannot withdraw 0 amount");
LibStorage.getGasStorage().thaw(_msgSender(),amount);
}
/**
* Withdraw fully thawed funds.
*/
function withdrawGas(uint112 amount) external nonReentrant {
require(amount > 0, "Cannot withdraw 0 amount");
LibStorage.getGasStorage().withdraw(_msgSender(), amount);
_msgSender().transfer(amount);
}
/**
* Deduct the given amount from a trader's available funds.
*/
function deduct(address trader, uint112 amount) internal {
LibStorage.getGasStorage().deduct(trader, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./Types.sol";
import "./libs/LibStorage.sol";
import "./libs/LibConfig.sol";
import "./BaseAccess.sol";
abstract contract BaseConfig is BaseAccess {
using LibConfig for Types.Config;
/**
* Initialize config settings. This is called at initialization time when contracts
* are first deployed.
*/
function initConfig(Types.Config memory config) internal {
LibStorage.getConfigStorage().store(config);
BaseAccess.initAccess();
}
/**
* Get the current configuration struct
*/
function getConfig() external view returns (Types.Config memory) {
return LibStorage.getConfigStorage().copy();
}
//============== VIEWS ================/
/**
* Get the dev team wallet/multi-sig address
*/
function getDevTeam() external view returns (address) {
return LibStorage.getConfigStorage().devTeam;
}
/**
* Get the number of blocks to wait before trader can withdraw gas tank funds
* marked for withdraw.
*/
function getLockoutBlocks() external view returns (uint8) {
return LibStorage.getConfigStorage().lockoutBlocks;
}
/**
* Get the minimum fee required for all orders
*/
function getMinFee() external view returns (uint128) {
return LibStorage.getConfigStorage().minFee;
}
/**
* Get the penalty fee to asses when trader removes tokens or funds after
* Dexible submits orders on-chain.
*/
function getPenaltyFee() external view returns (uint128) {
return LibStorage.getConfigStorage().penaltyFee;
}
//=============== MUTATIONS ============/
/**
* Set the current configuration as a bulk setting
*/
function setConfig(Types.Config memory config) public onlyAdmin {
LibStorage.getConfigStorage().store(config);
}
/**
* Set the dev team wallet/multi-sig address
*/
function setDevTeam( address team) external onlyAdmin {
LibStorage.getConfigStorage().devTeam = team;
}
/**
* Set the number of blocks to wait before thawed withdraws are allowed
*/
function setLockoutBlocks(uint8 blocks) external onlyAdmin {
LibStorage.getConfigStorage().lockoutBlocks = blocks;
}
/**
* Set the minimum fee for an order execution
*/
function setMinFee(uint128 fee) external onlyAdmin {
LibStorage.getConfigStorage().minFee = fee;
}
/**
* Set the penalty assessed when a user removes tokens or gas tank funds
*/
function setPenaltyFee(uint128 fee) external onlyAdmin {
LibStorage.getConfigStorage().penaltyFee = fee;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./LibStorage.sol";
import "../Types.sol";
import "hardhat/console.sol";
library LibGas {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
//emitted when gas is deposited
event GasDeposit(address indexed trader, uint112 amount);
//emitted when gas is marked for thaw period
event GasThawing(address indexed trader, uint112 amount);
//emitted when gas is withdrawn
event GasWithdraw(address indexed trader, uint112 amount);
// ============ VIEWS ==============/
/**
* Determine how much of an account's gas tank balance can be withdrawn after a thaw period
* has expired.
*/
function availableForWithdraw(Types.GasBalances storage gs, address account) external view returns (uint256) {
Types.Gas storage gas = gs.balances[account];
if(gas.thawingUntil > 0 && gas.thawingUntil <= block.number) {
return gas.thawing;
}
return 0;
}
/**
* Determine how much of an account's gas tank balance is availble to pay for fees
*/
function availableForUse(Types.GasBalances storage gs, address account) internal view returns (uint256) {
Types.Gas storage gas = gs.balances[account];
//console.log("Current block", block.number);
//console.log("Expired block", gas.thawingUntil);
if(gas.thawingUntil > 0 && gas.thawingUntil > block.number) {
//we have some funds thawing, which are still usable up until its expiration block
return gas.balance.add(gas.thawing);
}
//otherwise we can only use balance funds
return gas.balance;
}
/**
* Determine how much of an account's gas tank is waiting for a thaw period before it's
* available for withdraw
*/
function thawingFunds(Types.GasBalances storage gs, address account) internal view returns (uint256) {
Types.Gas storage gas = gs.balances[account];
//so long as the thaw period hasn't expired
if(gas.thawingUntil > 0 && gas.thawingUntil > block.number) {
//the funds are not available for withdraw
return gas.thawing;
}
return 0;
}
/**
* Determine if the account has enough in the tank to pay for estimated usage for given price
*/
function hasEnough(Types.GasBalances storage gs, address account, uint256 estimateUse, uint112 price) internal view returns (bool) {
require(price > 0, "Cannot estimate with 0 gas price");
require(estimateUse > 0, "Cannot estimate with 0 gas use");
uint112 amount = uint112(estimateUse.mul(price));
uint112 _total = uint112(availableForUse(gs, account));
return _total > amount;
}
// ============ MUTATIONS ==========/
/**
* Deposit funds into the gas tank.
*/
function deposit(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
//add incoming amount to the current balance
gas.balance = uint112(gas.balance.add(amount));
//tell the world about it
emit GasDeposit(account, amount);
}
/**
* Mark
*/
function thaw(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
//following will fail if amount is more than gas tank balance so no need
//to check and waste cycles
gas.balance = uint112(gas.balance.sub(amount));
//add to thawing total
gas.thawing = uint112(gas.thawing.add(amount));
//set withdraw to next lockout period blocks. Note that this locks up any
//previously thawed funds as well.
gas.thawingUntil = block.number.add(LibStorage.getConfigStorage().lockoutBlocks);
//tell the world about it
emit GasThawing(account, amount);
}
/**
* Try to withdraw any fully thawed funds
*/
function withdraw(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
require(gas.thawingUntil > 0, "Must first request a withdraw");
require(gas.thawingUntil < block.number, "Cannot withdraw inside lockout period");
//this will fail if amount is more than thawing amount so no need to check amount
gas.thawing = uint112(gas.thawing.sub(amount));
}
/**
* Deduct from the trader's balance after an action is complete
*/
function deduct(Types.GasBalances storage gs, address account, uint112 amount) internal {
Types.Gas storage gas = gs.balances[account];
if(amount == 0) {
return;
}
uint112 _total = uint112(availableForUse(gs, account));
require(_total > amount, "Insufficient gas to pay amount");
if(gas.balance >= amount) {
//if the balance has enough to pay, just remove it
gas.balance = uint112(gas.balance.sub(amount));
} else {
//otherwise, this means there are thawing funds that have not fully thawed yet
//but are stll available for use. So use them.
gas.thawing = uint112(gas.thawing.sub(amount.sub(gas.balance)));
gas.balance = 0;
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../Types.sol";
library LibConfig {
function store(Types.Config storage cs, Types.Config memory config) public {
cs.devTeam = config.devTeam;
cs.minFee = config.minFee;
cs.penaltyFee = config.penaltyFee;
cs.lockoutBlocks = config.lockoutBlocks;
require(cs.devTeam != address(0), "Invalid dev team address");
}
function copy(Types.Config storage config) public view returns(Types.Config memory) {
Types.Config memory cs;
cs.devTeam = config.devTeam;
cs.minFee = config.minFee;
cs.penaltyFee = config.penaltyFee;
cs.lockoutBlocks = config.lockoutBlocks;
require(cs.devTeam != address(0), "Invalid dev team address");
return cs;
}
//============== VIEWS ================/
function getDevTeam(Types.Config storage _config) external view returns (address) {
return _config.devTeam;
}
function getLockoutBlocks(Types.Config storage _config) external view returns (uint8) {
return _config.lockoutBlocks;
}
function getMinFee(Types.Config storage _config) external view returns (uint128) {
return _config.minFee;
}
function getPenaltyFee(Types.Config storage _config) external view returns (uint128) {
return _config.penaltyFee;
}
//=============== MUTATIONS ============/
function setDevTeam(Types.Config storage _config, address team) external{
_config.devTeam = team;
}
function setLockoutBlocks(Types.Config storage _config, uint8 blocks) external{
_config.lockoutBlocks = blocks;
}
function setMinFee(Types.Config storage _config, uint128 fee) external{
_config.minFee = fee;
}
function setPenaltyFee(Types.Config storage _config, uint128 fee) external{
_config.penaltyFee = fee;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../Types.sol";
import "../../IDexRouter.sol";
import "../../BaseAccess.sol";
import "../../interfaces/uniswap/IPair.sol";
import "../../interfaces/uniswap/IPairFactory.sol";
import "../../interfaces/uniswap/IV2Router.sol";
import "hardhat/console.sol";
contract UniswapDex is BaseAccess, IDexRouter{
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
uint256 constant public MAX_INT_TYPE = type(uint256).max;
IPairFactory factory;
IV2Router router;
function initialize(IPairFactory uniFactory, IV2Router v2Router) public initializer {
BaseAccess.initAccess();
factory = uniFactory;
router = v2Router;
}
function revokeTokenAllowance(IERC20 token) external onlyAdmin {
token.approve(address(router), 0);
}
function fill(Types.Order calldata order, bytes calldata data) external override returns (bool success, string memory failReason) {
address[] memory path = abi.decode(data, (address[]));
verifyRouterAllowance(order.input.token, order.input.amount);
if(order.orderType == Types.OrderType.EXACT_IN) {
//console.log("Expecting output amount", order.output.amount);
try router.swapExactTokensForTokens{
gas: gasleft()
}(
order.input.amount,
order.output.amount,
path,
order.trader,
block.timestamp+1
)
{
success = true;
} catch Error(string memory err) {
//console.log("Problem in fill", err);
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
} else {
try router.swapTokensForExactTokens{
gas: gasleft()
}(
order.output.amount,
order.input.amount,
path,
order.trader,
block.timestamp + 1
)
{
success = true;
} catch Error(string memory err) {
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
}
}
function verifyRouterAllowance(IERC20 token, uint256 minAmount) internal {
uint allow = token.allowance(address(this), address(router));
if(allow < minAmount) {
token.approve(address(router), minAmount);
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
interface IPair {
function addLiquid(uint amount0, uint amount1) external;
function getReserves() external view returns (uint, uint, uint);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
interface IPairFactory {
function createPair(address a, address b) external returns (address);
function getPair(address tokenA, address tokenB) external view returns (address);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IV2Router {
function addLiquidity(IERC20 tokenA, uint aAmount, IERC20 tokenB, uint bAmount)
external
returns (address);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
external
view
returns (uint amount);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
external
view
returns (uint amount);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../Types.sol";
import "../../IDexRouter.sol";
import "../../BaseAccess.sol";
import "../../interfaces/uniswap/IPair.sol";
import "../../interfaces/uniswap/IPairFactory.sol";
import "../../interfaces/uniswap/IV2Router.sol";
import "hardhat/console.sol";
contract SushiswapDex is BaseAccess, IDexRouter{
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
uint256 constant public MAX_INT_TYPE = type(uint256).max;
IPairFactory factory;
IV2Router router;
function initialize(IPairFactory uniFactory, IV2Router v2Router) public initializer {
BaseAccess.initAccess();
factory = uniFactory;
router = v2Router;
}
function revokeTokenAllowance(IERC20 token) external onlyAdmin {
token.approve(address(router), 0);
}
function fill(Types.Order calldata order, bytes calldata data) external override returns (bool success, string memory failReason) {
address[] memory path = abi.decode(data, (address[]));
verifyRouterAllowance(order.input.token, order.input.amount);
if(order.orderType == Types.OrderType.EXACT_IN) {
console.log("Expecting output amount", order.output.amount);
console.log("Given input amount", order.input.amount);
try router.swapExactTokensForTokens{
gas: gasleft()
}(
order.input.amount,
order.output.amount,
path,
order.trader,
block.timestamp+1
)
{
success = true;
} catch Error(string memory err) {
console.log("Problem in Sushiswap", err);
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
} else {
try router.swapTokensForExactTokens{
gas: gasleft()
}(
order.output.amount,
order.input.amount,
path,
order.trader,
block.timestamp + 1
)
{
success = true;
} catch Error(string memory err) {
success = false;
failReason = err;
} catch {
success = false;
failReason = "Unknown fail reason";
}
}
}
function verifyRouterAllowance(IERC20 token, uint256 minAmount) internal {
uint allow = token.allowance(address(this), address(router));
if(allow < minAmount) {
token.approve(address(router), minAmount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Proxy.sol";
import "../utils/Address.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./UpgradeableProxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is UpgradeableProxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin_);
}
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _admin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external virtual ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin {
_upgradeTo(newImplementation);
Address.functionDelegateCall(newImplementation, data);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/Ownable.sol";
import "./TransparentUpgradeableProxy.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/proxy/ProxyAdmin.sol";
contract DeploymentAdmin is ProxyAdmin {
}
| ========= MUTATIONS =============/* Deposit funds into the gas tank/ | function depositGas() external payable {
require(msg.value > 0, "No funds provided for gas deposit");
LibStorage.getGasStorage().deposit(_msgSender(), uint112(msg.value));
}
| 5,969,286 | [
1,
1432,
33,
490,
1693,
15297,
422,
1432,
12275,
19,
4019,
538,
305,
284,
19156,
1368,
326,
16189,
268,
2304,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
27998,
1435,
3903,
8843,
429,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
405,
374,
16,
315,
2279,
284,
19156,
2112,
364,
16189,
443,
1724,
8863,
203,
3639,
10560,
3245,
18,
588,
27998,
3245,
7675,
323,
1724,
24899,
3576,
12021,
9334,
2254,
17666,
12,
3576,
18,
1132,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.